Page 189 - Introduction to Programming with Java: A Problem Solving Approach
P. 189
The asterisk is a wildcard. In the above statement, the asterisk causes all classes in the java.util package to be imported—not just the Scanner class. There’s no inefficiency in using the wildcard notation. The compiler includes only as much as it needs in the compiled program.
Several classes are so important that the Java compiler automatically imports them for you. These au- tomatically imported classes are in the java.lang package, where lang stands for “language.” In effect, the Java compiler automatically inserts this statement at the top of every Java program:
import java.lang.*;
Since this is automatic and understood, there’s no need to write it explicitly.
The Math class is in the java.lang package, so there’s no need for you to import the Math class if
you want to perform math operations. Likewise, the System class is in the java.lang package, so there’s no need for you to import the System class if you want to perform a System.out.println command.
Headings for API Methods
To use an API class, you don’t need to know the internals of the class; you just need to know how to “inter- face” with it. To interface with a class, you need to know how to use the methods within the class. For ex- ample, to perform input, you need to know how to use the Scanner class’s methods—next, nextLine, nextInt, nextDouble, and so on. To use a method, you need to know what type of arguments to pass to it and what type of value it returns. Arguments are the input you supply to a method when you call it, or ask it to do something for you, and the value it returns is the answer it gives you back.
The standard way to present method-interface information is to show the method’s source code head- ing. For example, here’s the source code heading for the Scanner class’s nextInt method:
Apago PDF Enhancer
public int nextInt()
In the above nextInt heading, the public access modifier should look familiar because your main method headings all use public. We’ll discuss private methods in Chapter 8. They’re accessible only from within the class that defines them. Note that the nextInt method returns an int value and that it has no arguments inside the parentheses. Here’s an example of a Java statement that shows how you might call the nextInt method:
int days = stdIn.nextInt();
5.3 Math Class
The Math class is one of the pre-built classes in the always-available java.lang package. This class contains methods which implement standard mathematical functions. A mathematical function generates a
5.3 Math Class 155
The arguments that you pass to the method go inside the parentheses (no arguments are passed to the nextInt method).
The return type (int in this example) indicates the type of the value that’s being returned from the method.
public means that the method is directly accessible from everywhere; that is, the “public” can access it.