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:
- β
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. - β It is the same as the import statement.
This is false. The regularimport
statement is for importing types (classes or interfaces), whilestatic import
is specifically for static members. - β 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. - β 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 isimport 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.