Which is true about the static import statement in Java? 1) It is used when one wants to use a class’s static members. 2) It is the same as the import statement. 3) When the static import statement is used in a Java source file, the classes declared in that file cannot declare any non-static members. 4) The statement can be written either as static import or import static. It does not matter how it is written.

The correct answer and explanation is:

βœ… Correct Answer: 1) It is used when one wants to use a class’s static members.


🧾 Explanation (300 words):

In Java, the static import statement allows you to access static members (fields and methods) of a class without qualifying them with the class name. This helps make code more concise and readable when you frequently use static members from a utility class like java.lang.Math.

For example:

import static java.lang.Math.*; // static import

public class Example {
    public static void main(String[] args) {
        double result = sqrt(16); // no need to write Math.sqrt(16)
        System.out.println(PI);   // no need to write Math.PI
    }
}

Without static import, you’d have to use:

double result = Math.sqrt(16);
System.out.println(Math.PI);

Let’s break down the options:

  1. βœ… It is used when one wants to use a class’s static members.
    βœ… This is correct. That’s exactly what static import is for: to use static methods or variables without class qualification.
  2. ❌ It is the same as the import statement.
    This is false. The regular import statement is for importing types (classes or interfaces), while static import is specifically for static members.
  3. ❌ When the static import statement is used in a Java source file, the classes declared in that file cannot declare any non-static members.
    This is incorrect. Static import has no effect on whether a class can declare static or non-static members. It’s just a convenience for referencing static members.
  4. ❌ The statement can be written either as static import or import static. It does not matter how it is written.
    This is false. The correct syntax is import static. Reversing the order will result in a compiler error.

βœ… Conclusion:

The correct statement is Option 1:
Static import is used when one wants to use a class’s static members without class name qualification.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *