Static Import in Java with Example

In this article, we will discuss static import in Java.

Just as import statements are used to access a class without its package qualification. In a similar manner, static imports are used to access static members without their class qualification.

Some basic static methods used with the class names are as follows:

Math.sqrt(4): It is used to find the square root of the given number.

Math.max(4, 2): It is used to find the maximum of the given numbers.

Math.min(4, 2): It is used to find the minimum value between the given values.

Math.pow(4, 2): This function returns a number raised to a given power. In this example, 4 raised to the power of 2.

Math.abs(-4): It is used to find the absolute value of the given number.

Static Import in Java

By using static imports, we don’t need to use the class name. We can directly call them.

Program:

Output:

4
2
2.0
16.0
4

If we wish to use the System method, we can write System.out.println(“text”);

Program:

Output:

4
2
2.0
16.0
4

The system is a class and out is a static variable. System class present in java.lang package and out present in System class.

Ambiguity in Static Import

When we use two static members with the same name of different classes, then the compiler throws an error. This is because of the ambiguity to decide the class to which the static member belongs.

 Program:

Output:

In the above program, we import two classes: ‘Integers’ and ‘Byte’ respectively and we use one static member ‘ MAX_VALUE’ common to both the classes. So, in this case, the reference of MAX_VALUE is ambiguous.

Difference between Import and Static Import

import static import
With the help of import, we can access classes or interfaces which are present in any package. With the help of static import, we can access all the static variables without calling their class name.
Classname.data_member(System.out) is less readable. Classname.data_member(out) is more readable.

So, that’s all about static import in Java. You can ask your queries in the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *