While reading some java books, I came to know about static imports. I have some doubts in my mind.
- What is static imports.
- When and why to use it.
Explaination with examples will be helpful.
While reading some java books, I came to know about static imports. I have some doubts in my mind.
Explaination with examples will be helpful.
One example is JUnit tests
import static org.junit.Assert.assertEquals;
...
assertEquals(x, y);
Imports are typing shortcuts. A "regular" import is a shortcut down to the class level...
import java.util.List
Let's you just use
List l;
Instead of
java.util.List l;
A static import is a shortcut down to the method level. The method must be static, since there is no instance to associate with it...
import static java.lang.Math.abs
Lets you just use
x = abs(y);
instead of
x = java.lang.Math.abs(y);
Imports do not effect your compiled output or running code in any way. Once something is compiled there's no way to tell if the original source had imports or not.
The static import allows you to import the static elements. Usually used when the same objects are invoked many times. An example: in your code you are usually use the element out of the class java.lang.System, you can import statically the element out simplifying and improving the code :)
import static java.lang.System.out;
public static void main(String[] args){
out.println("Hello");
out.println("World");
}