Library Classes and Packages
Library Classes and Packages
▪ Example
▪ import java.util.Scanner;
▪ In the example above, java.util is a package,
while Scanner is a class of
the java.util package.
▪ To use the Scanner class, create an object of
the class and use any of the available
methods found in the Scanner class
documentation. In our example, we will use
the nextLine() method, which is used to read
a complete line:
▪ Example
▪ Using the Scanner class to get user input:
▪ import java.util.Scanner; class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username"); String
userName = myObj.nextLine();
System.out.println("Username is: " +
userName); } }
▪ Import a Package
▪ There are many packages to choose from. In
the previous example, we used
the Scanner class from the java.util package.
This package also contains date and time
facilities, random-number generator and
other utility classes.
▪ To import a whole package, end the sentence
with an asterisk sign (*). The following
example will import ALL the classes in
the java.util package:
▪ Example
▪ import java.util.*;
User-defined Packages