Reputation: 319
It is my my second day on java. IN C++, if we include a class, and if some header files are already contained in that class, we do not need to put header files declaration in the main file again!
while in java, I find that we do not declare the class we use if it is under the source file. So I am wondering, if in the class we want to use some methods in library say math. Do we need to import math in both main file and this class file, or declare once and where to declare it?
thanks!
Upvotes: 0
Views: 2054
Reputation: 13
Is this what you mean?
import java.util.*;
public class GangstaName {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Type ya full name, playa: ");
String name = console.nextLine();
// split name into first/last name and initials
String first = name.substring(0, name.indexOf(" "));
String last = name.substring(name.indexOf(" ") + 1);
last = last.toUpperCase();
String fInitial = first.substring(0, 1);
System.out.println("Ya gangsta name be \"" + fInitial + ". Diddy " + last + " " + first + "-izzle\"");
}
}
In the sample code above, the import java.util line is written above and outside the class. It allows us to use Math class as well as the Scanner and String
Upvotes: 0
Reputation: 178263
A Java import
is not a C++ include
. Theoretically, it's possible for Java source code not to have any import
s at all, by using fully qualified class names where necessary.
java.util.Scanner scanner = new java.util.Scanner(System.in);
This is in contrast to a C++ include
which inserts the code from the included file directly into the compilation unit.
An import introduces the ability to refer to classes in other packages by their simple name, not just their fully-qualified class name. But that scope is limited to the source code file that the import
statement is in. Import all classes from other packages that are used in the source code file, in each source code file.
Upvotes: 3