Showing posts with label Static Import. Show all posts
Showing posts with label Static Import. Show all posts

Tuesday, 8 September 2015

Java Tutorial : Java Static Import

Master Core Java Concepts!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!

Subscribe Now on YouTube

What Is Static Import in Java?

The static import feature in Java allows you to access any static member (static fields and static methods) of a class directly without qualifying it with the class name.

For example, using import static java.lang.Math.*; lets you call min(), max(), or PI directly instead of writing Math.min(), Math.max(), or Math.PI.

import vs. static import

  • import: Provides accessibility to classes and interfaces of a package without package qualification (e.g., import java.lang.*;).
  • static import: Provides accessibility to static members of a class without class qualification (e.g., import static java.lang.Math.*;).

Advantage & Disadvantage of Static Import

✔️ Advantage: Less coding is required if you need to access a class's static members frequently.

⚠️ Disadvantage: Overusing static import can make your program harder to read and maintain.

Code Example: Without vs. With Static Import

// Without Static Import
import java.lang.*;

public class WithoutStaticImportExample {
  public static void main(String[] args) {
    System.out.println(Math.min(2, 10));
    System.out.println(Math.max(12, 30));
    System.out.println(Math.PI);
  }
}
// With Static Import
import static java.lang.Math.*;

public class StaticImportExample {
  public static void main(String[] args) {
    System.out.println(min(2, 10));
    System.out.println(max(12, 30));
    System.out.println(PI);
  }
}

Watch More Java Tutorials:

Tutorials