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:
The Java API (Application Programming Interface) is a library of pre-written classes that are free to use, included in the Java Development Environment.
The library contains components for managing input, database programming, networking, and much more. The library is divided into packages and classes. This means 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.
Syntax:
import package.name.Class; // Import a single class import package.name.*; // Import the whole package
If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code:
import java.util.Scanner;class Main { 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); } }
Note: The live editor uses sample input because it cannot accept keyboard input through
System.in.
There are many packages to choose from. In the previous example, we imported the Scanner class from the java.util package. This package also contains other useful classes, like ArrayList, HashMap, and Date.
To import the whole package, end the sentence with an asterisk (*).
import java.util.*;class Main { public static void main(String[] args) { // Now we can use Scanner, ArrayList, etc. without separate imports Scanner myObj = new Scanner(System.in); ArrayList
list = new ArrayList (); list.add("Test"); System.out.println(list.get(0)); } }
Note: The
java.langpackage is automatically imported in every Java program. It contains fundamental classes likeString,Integer,System, andObject.
To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer.
To create a package, use the package keyword at the very top of your Java file.
// Save this file as MyPackageClass.java in a folder named "mypack" package mypack;class MyPackageClass { public static void main(String[] args) { System.out.println("This is my package!"); } }
You would then compile and run it from outside the package directory, which is a more advanced topic involving classpath management.