Page 1 of 1

About Question enthuware.ocajp.i.v7.2.1396 :

Posted: Sun Aug 02, 2015 3:52 pm
by philfrei
I understand that the array's 0th element is null.

What I don't understand is why the attempt to reference a null object doesn't raise a NullPointerException. Usually any attempt to make use of a property of a null object raises an NPE.

Is this a special case of how .toString()? Or does it pertain to some special exceptions of the under-the-hood objects being created by the iterator being used?

Re: About Question enthuware.ocajp.i.v7.2.1396 :

Posted: Sun Aug 02, 2015 8:10 pm
by admin
Accessing a null reference always results in the JVM throwing an NPE.
The code doesn't access null reference in the given code. It is not the .toString() that is special but the + operator that is special. It observes that one of the operands is null and instead of calling toString on that operand it just appends the string "null" to the result.

Another similar case is when you try to print null using print method. For example,
Object obj = null;
System.out.println(obj);
Here, the println method does not invoke toString on s. If you look at the code of println method, you see something like this:
if(obj != null){ //NPE is avoided using this null check.
stringToPrint = obj.toString();
}else{
stringToPrint = "null";
}

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.1396 :

Posted: Fri Mar 03, 2017 9:58 am
by EricLeesburg

Code: Select all

          public static void main(String[] args) {        

                          String[] dataArr = new String[4];        //1
                           dataArr[1] = "Bill";         
                           dataArr[2] = "Steve";              
                           dataArr[3] = "Larry";         
                     try{         
                                for(String data : dataArr)
                                      {    System.out.print(data+" ");    }       
                         }catch(Exception e)
                                      { System.out.println(e.getClass()); } 
         }

From the line 1, apparently variable dataArr is a local dataArr, which means that it doesn't come with a default value if not explicitly initialized. Why the code still get compiled? Because it is a Array?

Re: About Question enthuware.ocajp.i.v7.2.1396 :

Posted: Fri Mar 03, 2017 10:36 am
by admin
You are explicitly initializing dataArr. To new String[4]; By assigning new String[], you have already created a String array object with 4 slots. What you are not doing is explicitly initializing those 4 slots of the String array at line 1. These slots are implicitly initialized to null.

After line 1, you are explicitly initializing the second, the third, and the fourth slot. Remember that array indexing starts with 0 so the first slot is still null.

Re: About Question enthuware.ocajp.i.v7.2.1396 :

Posted: Fri Mar 03, 2017 10:44 am
by EricLeesburg
got it!
Thanks!