Are there any advantages of using static import over import?

Ruchira Gayan Ranaweera picture Ruchira Gayan Ranaweera · Sep 16, 2013 · Viewed 24.8k times · Source

Consider the following class

public final class Constant {
  public static final String USER_NAME="user1";
  //more constant here
}

This class in the package B.

Now I am going to use this in package A. Consider following two ways which can use.

Method 1- use import B.Constant

import B.Constant;

public class ValidateUser {
public static void main(String[] args) {
   if(Constant.USER_NAME.equals("user1")){

   }
  }
 }

Method 2- use import static B.Constant.USER_NAME;

import static B.Constant.USER_NAME;

public class ValidateUser {
public static void main(String[] args) {
   if(USER_NAME.equals("user1")){

   }
 }
}

My question is is there any difference or advantage normal import over static import in this case?

Answer

Donal Fellows picture Donal Fellows · Sep 16, 2013

The only difference between a normal import and an import static is that the latter is for moving static members of some other class or interface — especially constants — into scope. It's up to you whether you use it; I like it because it keeps the body of the class shorter, but YMMV.

There are no performance benefits or penalties to using them (except possibly when compiling, as if you care about that) as they compile into identical bytecode.