What is the reason for the output? I know it prints Hello World
but don’t know why as it should give NullPointerException
.
public class Null
{
public static void greet()
{
System.out.println("Hello World");
}
public static void main(String[] args)
{
((Null)null).greet();
}
}
What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.
NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
NullPointerException is thrown when program attempts to use an object reference that has the null value. These can be: Invoking a method from a null object. Accessing or modifying a null object's field.
NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference.
This is because greet()
is a static method. So
((Null)null).greet();
is equivalent to,
Null.greet()
Since greet
is a static method, a class instance is not needed (and not used...) to invoke it.
The ((Null)null)
expression doesn't dereference null
, it simply serves as a type definition used to access the static method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With