Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate static import.

Java Code Example — Package Programs

ADVERTISEMENT

Java Program to demonstrate static import.

Objective

Write a Java program to demonstrate the use of static imports.

Algorithm / Approach

  1. At the top of the file, use the static import statement: import static java.lang.Math.*;.
  2. Add another static import: import static java.lang.System.*;.
  3. Inside the main method, calculate the square root directly using sqrt(4) instead of Math.sqrt(4).
  4. Calculate a power directly using pow(2,5).
  5. Print the results directly using out.println() instead of System.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 (like sqrt and pow) directly into our current scope.
  • Similarly, System.out is a static variable inside the System class. By statically importing System.*, we can just type out.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)
ADVERTISEMENT