Green Green - 17 days ago 4
Java Question

What is the role of static keyword in importing java.lang.System class?

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
because
java.util
is the name of a package in the Java API, and
Scanner
is the name of a class in the
java.util
package.

Here’s another example. The declaration
import javax.swing.*;
is valid
because
javax.swing
is the name of a package in the Java API, and the
asterisk refers to all classes in the
javax.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?

Answer

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.

Comments