Java 5: Static import

  Java Features     Java 5     Java 7     Java 8  
Java 5 features
 Enhanced for Loop |   Varargs |   Static import |   Autoboxing and unboxing |   Enum types |   Generics |   Annotations |   By date 

To access a static member in earlier Java versions we needed to write the class name first followd by the name of the static member. For example to access the static method max of the class Math, we wrote the statement as follows: Math.max(3, 6). The static import allows you to access the method max directly as follows: max(3, 6);. In order to do so you need to import the method as shown below:

import static java.lang.Math.max;

For more info click here to read Oracle’s explanation.

Example 1: Static import code

What is the output of the following code?

// import the static methods
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.System.out;

public class StaticImport
{
  public static void main(String args[])
  {
    /* use max(22, 32) instead 
     * of Math.max(22, 32)
     */
    int maximum = max(22, 32);
    /*use min(-3, 1) instead 
     * of Math.min(-3, 1)
     */
    int minimum = min(-3, 1);
    /* use out.print instead 
     * of System.out.print
     */
    out.print(maximum + ", ");
    out.print(minimum);
  }
}
Author: Sar Maroof

Answer explanation

The correct answer is: 32, -3.





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *