static import is a feature which allows us to use all the static members (fields and methods ) of any class without specifying the class in which the field is defined.

This feature was introduced in java 5.

  • How to use static import in program.

    There are 2 ways in which we can use static import-

    1) by importing particular static data member or static method of class.
    import static packageName. ClassName. staticMemberName ;

    2) by importing all the static members of the class.
    import static packageName.ClassName.* ;

  • 1) importing single static member of any class .

    Example)
    drag_handle
     import static java.lang.System.out;//importing single static member
    
    class Example {
    	public static void main(String arr[]) {
    		out.println("Hello static import....");
    		out.println("Import me....");
    	}
    }
    
    Output:
    Hello static import....
    Import me....
    
  • 2) importing all the static members of any class.

    Example)
    drag_handle
     import static java.lang.System.*;//importing all the static members of System
    import static java.lang.Math.*;//importing all the static members of Math
    
    class Example {
    	public static void main(String arr[]) {
    		int n = 5;
    		double power = pow(n, 2);
    		out.println("Power of " + n + " is " + power);
    		out.println("************************");
    		int a = 45, b = 76;
    		int max = max(a, b);
    		out.println("Max of " + a + " and " + b + " is " + max);
    
    	}
    }
    
    Output:
    Power of 5 is 25.0
    ************************
    Max of 45 and 76 is 76
  • So when should you use static import?

    Use it when you require frequent access to static members from one or two classes.

  • What is the disadvantage of static import?

    If you overuse the static import feature, static import can make your program unreadable and unmaintainable.

  • What is the difference between import and static import?

    The import allows the java programmer to access classes of a package without using fully qualified name of the class whereas the static import feature allows to access the static members of a class without specifying the class name. The import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.

What next?

The next topic is Access Modifiers in java

Share this page