Static Import

Static Import

This concept is introduces in 1.5, According to static import, improves readability of the code. But According to world wide experts, static import reduces readability and increases the confusion of the code. Hence if there is no specific requirement, it is not recommended to use static import.

When we are using static import, it is not required to use class name, while accessing static members.

With out static import:-

import java.lang.* ;
Class test
 Public static void main (String[] args)
{
System.out.println (Math.sqrt (4));
System.out.println (Math.randam ());
System.out.println(Math.max (10, 20));
}
}

With static import:-

import static java.lang.Math.sqrt;
import static java.lang.Math.*;

Class test
Public static void main( String[] args)
{
System.out.println (sqrt (4));
System.out.println (sqrt ());
System.out.println (max(10, 20));
}
}
import static java.lang.Byte.*;
import static java.lang.short.*;

Class test
{
Public static void main (String[] args)
{
System.out.println (MAX_VALUE);
}
}

While resolving static members, compile will always gives precedence in the following order.

  1. Current class static members.
  2. Explicit static import.
  3. Implicit static import.
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Byte.*;
Class test
{
static int MAX_VALUE = 888;
Public static void main (String[] args)
           {
          System.out.println(MAX_VALUE);
          }
}
  • If we are commenting line 1, explicit static import will be consider and we will Integer class MAX_VALUE is 2147483647.
  • If we are commenting line 1 and 2, then byte class MAX_VALUE will be consider and 127 as the output.
  • It is never recommended to use import concept until method level or variable level. But we have to use only at class level i.e general import use only at class level i.e. general import recommended to use, but not static import.

Que:- Which of the following import statements are not valid ?

  1. import static java.util.*;
  2. import static java.util.ArrayList ;
  3. import  java.util.ArrayList ;
  4. import static java.util.lang.Math.sqrt ;
  5. import java.util.ArrayList.* ;
  6. import java.util.lang.Math.sqrt ;
  7. import static java.util.lang.Math.* ;
  8. import java.util.lang.Math.* ;

Ans:- 1, 2, 4 .

Leave a Reply