Static Import Concept in Java

Author: neptune | 31st-Dec-2022
#Java

In Java, static import concept is introduced in the 1.5 version. With the help of static import, we can access the static members of a class directly without a class name or any object. 

Example:
we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(), but by using static import we can access sqrt() method directly as shown below


Example:

import static java.lang.Math.*;

class StaticImportExample {

    public static void main(String[] args)

    {

        System.out.println(sqrt(6));

        System.out.println(pow(3, 3));

        System.out.println(abs(7.4));

    }

}

Output: 

>>> 36

>>> 27

>>> 7


Ambiguity in static import:

When we import two static members having the same name but imported from multiple different classes, the compiler will throw an error, as it will not be able to determine which member to use in the absence of class name qualification. 

Example: 

Here MAX_VALUE is imported from Integer and Byte.

import static java.lang.Integer.*;

import static java.lang.Byte.*;

class AmbiguousImport {

    public static void main(String[] args)

    {

        System.out.println(MAX_VALUE);

    }

}

Output:

>>> Error: Reference to MAX_VALUE is ambiguous


Advantage of static import

  • Less coding is required if you have access any static member of a class oftenly.

Disadvantage of static import

  • If you overuse the static import feature, it makes the program unreadable and unmaintainable.


Conclusion

According to SUN Microsystem, it will improve the code readability and enhance coding. But according to programming experts, it will lead to confusion and is not good for programming. If there is no specific requirement then we should not go for static import.




Related Blogs
Where you applied OOPs in Automation Testing?
Author: neptune | 28th-Aug-2023
#Interview #Java
You may face this question Where you have applied OOPs concept in Automation Framework? in almost all the Selenium Interviews. Let's learn OOP’s concept in Java before going further...

How to access Simple and Nested JSON Object in Java ?
Author: neptune | 30th-Mar-2023
#Java
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write for humans and machines...

How to use wait commands in Selenium WebDriver in Java ?
Author: neptune | 22nd-Feb-2022
#Selenium #Testing #Java
We are going to explore different types of waits in Selenium WebDriver. Implicit wait, Explicit wait, and Fluent wait with examples...

Best way to reverse a String for beginners in Java.
Author: neptune | 15th-Jun-2023
#Java
We will explore How to reverse a String in Java using simple way. If you are beginner in Java then you are at the right place...

25 Basic Java interview questions.
Author: neptune | 30th-May-2022
#Interview #Java
We will explore 25 basic Java interview questions...

View More