The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

How to use static imports

Ever got tired of having to type Math.PI whenever you want to access PI?

There is a way to get around this (edit: must be Java 1.5 or new) by using static imports. Basically, static imports allow you to import static members of a class to be used without the class qualifier.

example:

// import PI statically from Math.PIimportstatic java.lang.Math.PI;publicclass MyClass
{publicstaticvoid main(String[] args){// we can use PI without having to type Math.PISystem.out.println("pi is "+ PI);}

You should only use this feature SPARINGLY! It can become extremely confusing if you import every static field from other classes in this manner. Also note that this method only imports the static fields/members, you still need to import the class in order to instantiate that class.

You may not statically import all static members from a package, and you must qualify the members you want to import from the class.

// illegal: java.lang is a packageimportstatic java.lang.*;// illegal: you must qualify which fields from the class you want to importimportstatic java.lang.math;