Have a Question?

If you have any question you can ask below or enter what you are looking for!

Difference between normal import & static import?

Difference between normal import & static import?
Difference between normal import & static import?

Static import

Introduce in 1.5 version. Usually, we can access static member by using the class name but whenever we are writing static import we can access static members directly without the class name. Regular import can import only types (classes and interfaces, but not methods). Static imports can import a class’s static members (variables and methods) as well.  While resolving static member compiler will always consider the precedence in the following order.

  1. Current class static member
  2. Explicit static import
  3. Implicit static import

In a Java two packages contain a class and interface with the same name is very rare and hence ambiguity is also very rare in normal import. But two classes and interface contains a variable or method with the same name is very common and hence ambiguity is also a very common problem in static import. Uses of static import reduce readability and create confusion and hence if there is no specific requirement then it is not recommended to use the static import.

//Explain import statement and difference between normal import & static import?
package com.java4us;

import static java.lang.Math.max;
import static java.lang.Math.random;
import static java.lang.Math.sqrt;

public class Test1 {
    public static void main(String args[]) {
        System.out.println(sqrt(10));
        System.out.println(max(10, 20));
        System.out.println(random());
    }
}

Difference between normal import & static import

Normal Import:- We can use normal import to import classes and interface of a particular package. Whenever we are using normal import it is not required to use the fully qualified name and we can use short name directly.
Syntax :- import packagename.classname;
Example-- import java.util.ArrayList

Static Import:- We can use static import to import static member from a particular class and package. Whenever we are using static import it is not required to use the class name to access static member and we can use directly
Syntax :- import static packagename.classname.staticMember;
Example-- import static java.lang.Math.sqrt;

Leave a Reply

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