Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt NullPointerException : Mala Gupta's book?

 
Saloni Dangwal
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A doubt from the book OCA SE 7 Programmer I Certification Guide by Mala Gupta ( Page 381 ) : -
It says that :-

It says if Line 2 is replaced with
System.out.println( newLaptops [1] );
then it will not throw a NPE and it will print " null "

I don't understand how is this possible when newLaptops is a local variable and it is said that local variable aren't assigned any value ( neither default nor null ). Secondly, for oldLaptops when accessing its second element throws NPE then why is it not same for variable newLaptops?? Please throw some light on this.
 
Ted North
Ranch Hand
Posts: 200
1
Java Python Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The newLaptops String array is declared and initialized all on one line. I think even though it is an 'automatic variable' or local variable the elements of the array will still be initialized to their default values. This is a very interesting situation. I coded this problem on my machine and it does print 'null' if the toString() method is removed.

Also, for oldLaptops if you look closely the code is only declaring the array as a class variable. The program never initializes the array to any values or specifies its size, so it is a reference that is not pointing to any object. Remember that all arrays even of the primitive data-types are Objects. So its default value is null. In other words the oldLaptops array reference variable implicitly equals null. With this in mind a NPE is bound to be thrown because the code is trying to access an array index on a reference that points to null.

I hope this helps. This problem had me scratching my head for a while too.

Regards,

Ted
 
Roel De Nijs
Sheriff
Posts: 9780
101
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
newLaptops is a local variable and it's definitely initialized (with an array of 2 elements). If you see a variable followed by the = sign, the variable is initialized. When you do not initialize the elements of an array explicitly (using the int[] array = { 1, 2, 3}; syntax), all elements are assigned a default value: false for booleans, 0 for integers, 0.0 for decimals and null for object references (lika a String).

Hope it helps!
 
Saloni Dangwal
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ted and Roel....got it now
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic