Page 1 of 1
About Question enthuware.ocajp.i.v7.2.1137 :
Posted: Mon Jul 27, 2015 7:19 am
by Roibeard
int index = 1; String[] strArr = new String[5]; String myStr = strArr[index]; System.out.println(myStr);
Returns null.
However in
viewtopic.php?f=2&t=1065 I see:
Passing null in itself never causes NPE. Accessing null always causes NPE.
What is the difference between printing an element which is initialized to null, and accessing a null element?
Re: About Question enthuware.ocajp.i.v7.2.1137 :
Posted: Mon Jul 27, 2015 8:00 am
by admin
When you try to access a null i.e. try it call a method on it or try to refer to a field of that class, the JVM throws a NPE because there is no object to access.
By "printing", if you mean passing null to the println method, then you are not accessing null, you are calling the print method of System class's out variable (i.e. you are accessing out, not null). Inside the code of the class of out variable, you will see that it doesn't access null. It does something like this:
if(refToBePrinted == null){
print("null"); //this part is hardcoded in the code.
}
YOu should check out the source code of the class to see exactly what it does.
HTH,
Paul.
Re: About Question enthuware.ocajp.i.v7.2.1137 :
Posted: Mon Jul 27, 2015 8:03 am
by Roibeard
Thank you
Re: About Question enthuware.ocajp.i.v7.2.1137 :
Posted: Thu Nov 21, 2024 8:01 am
by MarkWebDeveloper
Hi, everyone! This is a curious exercise. I thought the code would not compile since assigning a null value to a variable marked with var is prohibited. But it turns out that in this case the compiler has enough information about the type of the object, since it is taken from an array of Strings. So, in this case it works. Am I right?
Re: About Question enthuware.ocajp.i.v7.2.1137 :
Posted: Fri Nov 22, 2024 7:22 am
by admin
Yes, that is right.
Re: About Question enthuware.ocajp.i.v7.2.1137 :
Posted: Wed Dec 18, 2024 6:00 pm
by raphaelzintec
i'm starting loving entuwear for real, because i have not seen this in my learning materials but i like the fact that entuwear put these type of questions on purpose for our exam
in my case i chose option non of above because i tought wont compile as well
but now i understand that it has enough informations about the type