Java Program to demonstrate static import.
Objective
Write a Java program to demonstrate the use of static imports.
Algorithm / Approach
- At the top of the file, use the static import statement:
import static java.lang.Math.*;. - Add another static import:
import static java.lang.System.*;. - Inside the main method, calculate the square root directly using
sqrt(4)instead ofMath.sqrt(4). - Calculate a power directly using
pow(2,5). - Print the results directly using
out.println()instead ofSystem.out.println().
Test.java
import java.util.*;
import static java.lang.Math.*;
import static java.lang.System.*;
class Test {
public static void main(String[] a)
{
double x = sqrt(4);
double y = pow(2,5);
out.println("Square root of 4- "+x);
out.println("5 to the power of 2- "+y);
}
}
Expected Output
Square root of 4- 2.0 5 to the power of 2- 32.0
Explanation of the Program
- Static imports were introduced in Java 5 to make code more readable by eliminating the need to repeatedly type the class name for static members.
- By statically importing
java.lang.Math.*, we bring all of its static methods (likesqrtandpow) directly into our current scope. - Similarly,
System.outis a static variable inside the System class. By statically importingSystem.*, we can just typeout.println(). - While highly convenient, static imports should be used sparingly, as overusing them can cause naming collisions and make it hard to tell which class a method actually belongs to.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)