In this article, we will see sample program involving static method
Q) What will be output of following program ?
package in.bench.resources.interview;
public class DemoStatic {
// sample static method
private static void staticMethod() {
System.out.println("This is static-method with"
+ " name staticMethod();");
}
// main() - entry point to JVM execution
public static void main(String[] args) {
DemoStatic ds = null;
ds.staticMethod();
}
}
Output:
This is static-method with name staticMethod();
Explanation:
- We are invoking static-method with reference-variable which is assigned to null
- Not even created object using new operator at line 14
- So, one might think that, during execution of program it will throw NullPointerException
- But program displays correct output without error during runtime/execution
- Reason : because to invoke static-method, we don’t require actual instantiated object
- Instead static-method can be invoked with class-name like <Class-Name>.<static-method>
- Sometimes, uninitialized reference-variable is enough to call/invoke static-method, as shown in the above program
- Actually while calling/invoking static-method with reference-variable, Compiler warns with message “The static method <static-method-name()> from the type DemoStatic should be accessed in a static way“, as shown in the below screen-capture
- Correct-way to invoke static-method is,
1. <Class-Name>.<static-method> (most preferred)
2. <reference-variable>.<static-method>
Share with us, if you have faced any tricky interview question/program faced during Java Interview. We will publish along with solution.
Related Articles:
- Java – instanceof operator or keyword
- Java – final keyword
- Java – static keyword
- Java – this keyword
- Java – super keyword
- Java – Interview Question and Answers on final keyword
Happy Coding !!
Happy Learning !!