In Java, packages serve to group related classes, akin to folders in a file directory. They are utilized to prevent name conflicts and enhance code maintainability. Packages are categorized into two types:
The library is structured into packages and classes, offering the flexibility to import either individual classes with their methods and attributes or entire packages containing all classes associated with the specified package.
To utilize a class or a package from the library, you must employ the import keyword.
import import |
When you identify a class you wish to use, such as the Scanner class for obtaining user input, you would write the following code:
|
In the provided example, java.util represents a package, whereas Scanner is a class within the java.util package.
To utilize the Scanner class, instantiate an object of the class and employ any of the methods detailed in the Scanner class documentation. In this instance, we’ll utilize the nextLine() method, designed to read an entire line of input:
Utilizing the Scanner class for obtaining user input:
import
String
}
|
Numerous packages are available for selection. In the preceding example, we employed the Scanner class from the java.util package. This package also encompasses date and time functionalities, a random-number generator, and various other utility classes.
To import an entire package, conclude the statement with an asterisk sign ( * ). The subsequent example will import ALL the classes in the java.util package:
import
|
To establish your own package, it’s essential to comprehend that Java utilizes a file system directory to store them, akin to folders on your computer.
└── root
└── mypack
└── MyPackageClass.java
|
Use the package
keyword to create a package :
package |
Save the file as MyPackageClass.java and proceed with compiling it.
C:\Users\Your Name>javac MyPackageClass.java
|
Next, compile the package.
C:\Users\Your Name>javac -d . MyPackageClass.java
|
This compels the compiler to create the “mypack” package. The Note: To prevent conflicts with class names, the package name should be written in lowercase. |
After compiling the package in the aforementioned example, a new folder titled “mypack” was generated.To execute the
MyPackageClass.java file, use the following command:
C:\Users\Your Name>java mypack.MyPackageClass
|
Upon execution, the output will be:
This is my package!
|