• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NullPointerException

 
Gautham Muralidharan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The output for the above code snippet is a NullPointerException.
But it was mentioned that the answer is null in the webpage where I found the question.
Which is the correct output?
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3819
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happened when you tried to compile and run it?
 
Narayana Bojja
Ranch Hand
Posts: 135
4
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gautham,

The correct output is NullPointerException.
Why you are getting NullPointerException ? First Understand the internal working of for-each loop. when you compile your code for-each loop code will converted into equivalent for loop code .

See , how you code changes after compilation



Observe the below two lines


At first line xx is reference variable for int array,But it is assigned with null. At Second line, you calling xx.length, means null.length gives you NullPointerException. Remember when you call methods or properties on a reference variable which is null, you will get NullPointerException.

Hope it helps !
 
Mala Gupta
Author
Ranch Hand
Posts: 363
11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gautham Muralidharan wrote:

The output for the above code snippet is a NullPointerException.
But it was mentioned that the answer is null in the webpage where I found the question.
Which is the correct output?


Hi Gautham -

To prepare for this exam, write, compile and execute multiple code snippets; to understand Java topics.

The questions in this exam will try to ensure that you know your Java inside out. Only reading and trying to comprehend code won't help.

Good Luck to you.

With much respect,
Mala
 
Ganesh Patekar
Bartender
Posts: 696
23
Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Oracle Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please always QuoteYourSources
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic