Static import the Math Class Methods in Java

Java 8Object Oriented ProgrammingProgramming

Static import means that the fields and methods in a class can be used in the code without specifying their class if they are defined as public static.

The Math class method sqrt() in the package java.lang is static imported.

A program that demonstrates this is given as follows:

Example

 Live Demo

import static java.lang.Math.sqrt;
public class Demo {
   public static void main(String[] arg) {
      double num = 36.0;
      System.out.println("The number is: " + num);
      System.out.println("The square root of the above number is: " + sqrt(num));
   }
}

Output

The number is: 36.0
The square root of the above number is: 6.0

Now let us understand the above program.

The Math class is not required along with the method sqrt() as static import is used for the java.lang package. The number num and its square root is displayed. A code snippet which demonstrates this is as follows:

double num = 36.0;
System.out.println("The number is: " + num);
System.out.println("The square root of the above number is: " + sqrt(num));
raja
Published on 19-Feb-2019 10:03:05
Advertisements