I'm curious to know how would you explain this task I found in this quiz?
Even when the getFoo method returns null, the output is still Getting Object JavaQuiz . I think it should be NullPointerException.
public class Foo {
static String name = " JavaQuiz";
static Foo getFoo() {
System.out.print("Getting Object");
return null;
}
public static void main(String[] args) {
System.out.println(getFoo().name);
}
}
Accessing a static method or variable can be done via a null reference for the class that contains that static method/variable.
Since name is static, getFoo().name has the same result as Foo.name or just name, regardless of whether or not getFoo() returns null.
However, it is always better to use the class name when accessing a static method/variable, since it makes it clear that you intended to access a static member.
static members of a class are class level Members its means there is no need of Object to access these static Members.`
It automatically loaded when classloader of jvm loads the class. So here in this case
static String name = " JavaQuiz"; //load when class get loaded by JVM class loader.
This static variable will exists in memory just after class Foo is getting loaded into the jvm.
static Foo getFoo() { //method is also a static Member automatically loaded at Class Loading.
System.out.print("Getting Object");
return null;
}
And same will be applied with this static method getFoo().
So Here System.out.println(getFoo().name);.
Here is a example to abbriviate my Answer
class StaticExample
{
static String abc ="India";
public static void main (String[] args) throws java.lang.Exception
{
StaticExample obj = null;
System.out.println("Value is ==>" + obj.abc + StaticExample.abc + abc);
}
}
Output:-
Value is ==>IndiaIndiaIndia
here this line of code will also produce the output.
System.out.println(((Ideone)null).abc); // this will also print India.
Output:-
Value is ==>India
Note:- I think there is confusion about
getFoo()method but if.namemakes a ambiguity.nameis a static member so it can access using eitherclassNameor anynullreference . So, Here you may assume this scenario such that thisnamevariable is accessed with any null reference .
Hope you Got the point.
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