Packages


A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories: Built-in Packages
The Java API is a library of prewritten classes, which are free to use, included in the Java Development Environment. The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracle’s website: https://docs.oracle.com/javase/8/docs/api/ . The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contains all the classes that belong to the specified package.

To use a class or a package from the library, you need to use the import keyword:
// Import a single class.
import package.name.Class;
// Import the whole package.
import package.name.*;

Importing a Class
If you find a class you want to use, for example, the ArrayList class, which is used to get user input, write the code:
import java.util.ArrayList;

In the example above, java.util is a package, while ArrayList is a class of the java.util package. To use the ArrayList class, create an object of the class and use any of the available methods found in the ArrayList class documentation. The following example will use the add() method, which appends the specified element to the end of this list, and check whether the last parameter is in the previous parameters:

MyCars.java (a package example)

 import java.util.ArrayList;
 public class MyCars {
   public static void main( String[ ] args ) {
     ArrayList<String> cars = new ArrayList<String>( );

     // Populate the ArrayList with various number of parameters
     for ( int i=0; i < args.length-1; i++ )  cars.add( args[i] );
     
     // Find whether the last parameter is in the previous parameters.
     System.out.print( cars.( args[args.length-1] ) );
   }
 }
shell> java MyCars           

Output:           Result:




      “Perhaps the rare and simple pleasure of being seen for    
      what one is compensates for the misery of being it.”    
      ― Margaret Drabble