-1

While reading some java books, I came to know about static imports. I have some doubts in my mind.

  1. What is static imports.
  2. When and why to use it.

Explaination with examples will be helpful.

Pankaj Shinde
  • 3,361
  • 2
  • 35
  • 44

2 Answers2

1

One example is JUnit tests

import static org.junit.Assert.assertEquals;
 ...
 assertEquals(x, y);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

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.

Ted Bigham
  • 4,237
  • 1
  • 26
  • 31