Import statement in java
1. The import statement provides a convenient way to identify
classes that you want to reference to your class.import java.util.Date;
2.You can import a single class or an entire package;
3. You can include multiple import statements.
import java.util.Date;
import java.util.Calender;
you could refer to a class using it's fully qualified
namespace in your application, as in the following example.
java.util.Date date = new java.util.Date();
but that would lead to a lot of typing instead java provides
the import statement to allow you to declare that you want a reference a class
in another package.
Here's an example program that uses Scanner, with an import
statement:
import java.util.Scanner;
public class ScannerTest{
public static void
main(String arg[]){
// scanner gets
its input from the console.
Scanner scanner =
new Scanner(System.in);
String fname =
"";
// Get the user's
name.
System.out.print("Your name, adventurer? >");
fname =
scanner.next();
System.out.println();
// Print their
name in a a message.
System.out.println("Welcome, " + fname + " to Java tutorial Blog!");
}
}
We import just the class Scanner from java.util in the import statement in this program. If we'd been using multiple classes from java.util, we could have made all the classes in java.util accessible to us by using this import statement:
import java.util.*;
The * is a "regular expression operator" that will match any mixture of characters. Therefore, this import statement will import everything in java.util. If you have tried entering and running the example program above, you can alter the import statement to this one.
If we need multiple classes from different packages, we use an import statement for each package from which we need to import classes (or interfaces, or any other part of that package we need.) It's not unusual to see a sequence of import statements near the start of a program file:
0 comments:
Post a Comment