I don't understand the meaning of the keyword static
when I import System
class:
import static java.lang.System.*
I'm reading the book about Java and it's written there:
Any import declaration that doesn't use the word
static
must start with the name of a package and must end with either of the following:
- The name of a class within that package
- An asterisk (indicating all classes within that package)
For example, the declaration import
java.util.Scanner;
is valid becausejava.util
is the name of a package in the Java API, andScanner
is the name of a class in thejava.util
package.Here’s another example. The declaration
import javax.swing.*;
is valid becausejavax.swing
is the name of a package in the Java API, and the asterisk refers to all classes in thejavax.swing
package.
And I have the following code:
public class Addition {
public static void main(String[] args) {
double num;
num = 100.53;
num = num + 1000;
// So when I want to import the whole package java.lang as written in the book, it doesn't work:
// import java.lang.*;
// or like this:
// import static java.lang.*;
// NetBeans in both cases doesn't see these abbreviated names `out` and throws errors. Why?
out.print("The result is ");
out.print(num);
out.println(" .");
}
}
And it works when I import this way:
import static java.lang.System.out;
import static java.lang.System.*
But doesn't work when I try do this:
import java.lang.System.out;
import java.lang.System.*
What's the meaning of the static
keyword in this particular case?
And why import java.lang.*;
doesn't import the whole package with System
class in it?
A static
import allows you to write this:
out.print("The result is ");
rather than this:
System.out.print("The result is ");
See e.g. http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html.
I often use static imports in my unit tests, like so:
import static org.junit.Assert.*;
This allows me to write this code:
assertEquals(2, list.size());
Instead of this code:
Assert.assertEquals(2, list.size());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With