What is a Package in Java?

Types of Packages in Java
A package can either be defined by the user (custom package) or provided by the system called the built-in packages. Some of the most handy and widely used built-in packages are java.util, java.math, java.io, java.awt etc.
Fig1: Java providing built-in packages
Why use a package?
Packaging different classes helps structure your project better, eliminates naming conflicts and controls the access level of files in that package. For instance if you’re developing an enterprise level application with hundreds of distinct classes then you need the relevant files to be placed together. Finding the right file before each access won’t only squander time but will testify your naive approach.How to Import a package?
You need to use the keyword “import” in order to import package(s) depending on your requirements. Let’s look at an example to see how it works.Import java.util.*
package com.importpackage.core;
// * imports all classes available in "util"
import java.util.*;
public class ImportUtilPackage {
public static void main(String[] args) {
// List and ArrayList are two distinct classes provided by "java.util" package
List<String> weekDays = new ArrayList<String>(
Arrays.asList("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"));
System.out.println("Days of the week are: " + weekDays.toString());
weekDays.remove("Monday");
System.out.println("Days of the week are: " + weekDays.toString());
// Date is another class implemented to process the Date by "java.util"
Date today = new Date();
System.out.println("Today's Date: " + today);
// Scanner is a class to take user inputs from console
// A built-in functionality provided by Java
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Your name: " + name);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Your age: " + age);
}
}
Kindly note that “java.util.*” imports all the available classes in the package “java.util”. You can individually import classes too like the following.
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
Output
Days of the week are: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
Days of the week are: [Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
Today's Date: Tue Apr 27 22:48:51 PKT 2021
Enter your name: Lizz (user typed)
Your name: Lizz
Enter your age: 22 (user typed)
Your age: 22
GO TO FULL VERSION