About Question enthuware.ocajp.i.v8.3.1486 :
Posted: Sat May 29, 2021 5:26 am
Is that explanation trying to say null.url is valid?
Java Certification Resources and Java Discussion Forum
https://enthuware.com/forum/
What it is trying to say is that even if the reference resolves to null at runtime, it doesn't matter because the JVM doesn't need the object reference to access static members anyway. The compiler replaces getDatabase().url with DatabaseWrapper.url!Note the method signature. It returns a reference to an object of class DatabaseWrapper. Thus, getDatabase().url means we are accessing url field of the object returned by the method. Now, since the class of the object returned by the method is DatabaseWrapper and the field url is a static field of the class, the compiler creates the instruction for the JVM to access this field directly using the class reference instead of the object reference returned by the method at runtime. Thus, the JVM does not need to depend on the actual object returned by the method at run time to access url. So even if the method returns null at run time, it doesn't matter because the JVM doesn't even access the reference returned by the method.
If this is the case why it is the getDatabase() method getting evaluated and prints "Getting Db..."?The compiler replaces getDatabase().url with DatabaseWrapper.url!
Here, you can see that return value of invokestatic at 3: is popped off the stack at 6. It is not used for accessing the url field. The url field is accessed independently.public static void main(java.lang.String[]);
Code:
0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
3: invokestatic #21 // Method getDatabase:()LDatabaseWrapper;
6: pop
7: getstatic #27 // Field url:Ljava/lang/String;
0: getstatic #15 // Field java/lang/System.out:Ljava/io/PrintStream;
3: invokestatic #29 // Method getDatabase:()LDatabaseWrapper;
6: getfield #9 // Field url:Ljava/lang/String;