Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

dout on static imports

 
karnatam narendraprasad
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code::


import static java.lang.System.out.println;
import static java.lang.Math.sqrt;

public class Test3 {
public static void main(String[] argv) {
int number = 4;
out.println(sqrt( (Integer) number));

}
}
when i acompile this i am geting errors....


---------- compile ----------
Test3.java:1: cannot find symbol
symbol : class out
location: class java.lang.System
import static java.lang.System.out.println;
^
Test3.java:1: static import only from classes and interfaces
import static java.lang.System.out.println;
^
Test3.java:7: cannot find symbol
symbol : variable out
location: class Test3
out.println(sqrt( (Integer) number));
^
3 errors
Output completed (2 sec consumed) - Normal Termination



if i change the code like



import static java.lang.System.out;
import static java.lang.Math.sqrt;

public class Test3 {
public static void main(String[] argv) {
int number = 4;
out.println(sqrt( (Integer) number));

}
}


it compile fine ..giveing out put...
why i am not able to uderstand what internally going on ...
can any one explain...

waiting for replay....

Narendra
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
println is a method in the PrintStream class.

It is not a static field in System.
 
Amit Wadhwaa
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well .. I have a doubt about static imports..

import static java.lang.System.out;

In above Why do I have to type java.lang! When in methods JVM/Compiler can resolve System Class directly w/o java.lang prefix.

Is there a import precedence/order? So java.lang gets imported later than the import static?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know the reason behind the design decision, but it is required in the single static import and static import on demand declarations that we use the canonical, or fully-qualified, name of the class.

You can find this in the Java Language Specification under Single Static Import Declaration and Static-Import-on-Demand Declaration.

Also you'll find the rules for how the static imports are treated relative to other imports.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic