Use static Import for sqrt() and pow() methods in class Math in Java


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 methods sqrt() and pow() in the package java.lang are static imported. A program that demonstrates this is given as follows:

Example

 Live Demo

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

Output

The number is: 4.0
The square root of the above number is: 2.0
The square of the above number is: 16.0

Now let us understand the above program.

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

double num = 4.0;
System.out.println("The number is: " + num);
System.out.println("The square root of the above number is: " + sqrt(num));
System.out.println("The square of the above number is: " + pow(num, 2));

Updated on: 30-Jul-2019

710 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements