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 .

The Author

Narayanaswamy

Hello! I am Narayanaswamy founder and admin of narayanatutorial.com. I have been working in IT industry more than 7 years. NarayanaTutorial is my web technologies blog. My specialties are Java / J2EE, Spring, Hibernate, Struts, Webservices, PHP, Oracle, MySQL, SQLServer, Web Hosting and Website Development. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

Leave a Reply