Java Packages Import With Example

In Java, a package is a namespace mechanism that groups related classes and interfaces. This grouping helps to modularize code and avoid name clashes of classes across projects.

The import statement in Java allows a Java class to use a class or an interface from another package without referring to them with their full, qualified names.

Java Packages Import With Example Intro

What is a Java Package?

In Java, a package is a namespace that organizes a set of related classes and interfaces. It’s similar to folders on your computer where you group related files together. Packages are both a naming and a visibility control mechanism.

Advantages of Using Packages:

  1. Avoiding Naming Conflicts: By putting your classes into packages, you can avoid conflicts with other classes that may have the same name.

  2. Easier Maintenance: Packages help in organizing files, making it easier to locate and maintain them.

  3. Access Protection: It provides visibility control by using access modifiers with classes, interfaces, methods, and fields.

Java Packages Import With Example

Importing Package:

When you want to use a class from another package, you typically need to tell your program where to find it. This is where the import keyword comes into play.

Types Of Import:

1. Single Type Import:

This imports only a single class or interface from the specified package.

import java.util.ArrayList;

2. On-Demand (Wildcard) Import:

This imports all the classes and interfaces from the specified package.

import java.util.*;

Although this can make your code a bit more concise, it’s generally discouraged because it can lead to ambiguity, especially if two packages have classes with the same name.

3. Static Import:

This is a feature introduced in Java 5 that allows members (fields and methods) defined as public static in a class to be used without specifying the class name.

import static java.lang.Math.*;

public class Main {
    public static void main(String[] args) {
        double result = sqrt(25); // No need to write Math.sqrt
        System.out.println(result);
    }
}

Importing Rules:

1. Explicit Class Import Has Precedence:

If both explicit and wildcard imports are used, explicit imports take precedence.

import static java.lang.Math.*;

public class Main {
    public static void main(String[] args) {
        double result = sqrt(25); // No need to write Math.sqrt
        System.out.println(result);
    }
}

2. Compilation Error on Ambiguity: 

If there’s ambiguity, and it’s not resolved by an explicit import, then the code won’t compile.

import java.sql.Date;
import java.util.Date;  // Error: ambiguous class

Date date; 

3.  Classes from java.lang Package:

Classes from the java.lang package are implicitly imported. So, you don’t need to explicitly import classes like String, System, etc.

Relation to the File System:

The package name is directly related to the directory structure of the stored .java and .class files. If you have a package com.example.shapes, the directory structure would be:

com/
|-- example/
    |-- shapes/
        |-- Circle.java
        |-- Circle.class

Java Packages Import With Example

Code 1 : Basic Package Import

Run
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        Date today = new Date();
        System.out.println("Today's date: " + today);
    }
}

Output :

Today's date: Sat Sep 02 06:32:23 GMT 2023

Explanantion :

In this code, we’re importing the Date class from the java.util package. We then create an instance of this class and print the current date and time.

Code 2 : Wildcard Import and Name Clash Resolution

Run

import java.util.*;
import java.sql.Timestamp;

public class Main {
    public static void main(String[] args) {
        Date utilDate = new Date();
        Timestamp sqlTimestamp = new Timestamp(utilDate.getTime());
        
        System.out.println("java.util.Date: " + utilDate);
        System.out.println("java.sql.Timestamp: " + sqlTimestamp);
    }
}

Output :

java.util.Date: Sat Sep 02 06:42:30 GMT 2023
java.sql.Timestamp: 2023-09-02 06:42:30.72

Explanantion :

We’re importing all classes from the java.util package using a wildcard. There’s a Date class in java.util and another in java.sql. To avoid naming conflicts, we’re explicitly importing Timestamp from java.sql. We then create instances of both java.util.Date and java.sql.Timestamp and print them.

Code 3 : Static Import

Run
import static java.lang.Math.PI;
import static java.lang.Math.pow;

public class Main {
    public static void main(String[] args) {
        double radius = 5.0;
        double area = PI * pow(radius, 2);
        System.out.println("Area of circle with radius 5: " + area);
    }
}

Output :

Area of circle with radius 5: 78.53981633974483

Explanantion :

We’re statically importing the constant PI and the method pow from the java.lang.Math class. This allows us to use them directly without prefixing with Math.. The program calculates the area of a circle with radius 5.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription