Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in nullpointerException.

 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The above code when run with no arguments doesnt throw a nullpointer exception. Why? The object inside the array are strngs if Im not mistaken? I am calling a method length() on a null string?
 
Josef Zdepa
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the cycle doesn't execute.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your System.out.println call is not executed. Check the condition part of the for loop. args does not necessarily have to be null, it can be a String array with no elements.
 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats the whole point. there isnt anything in those elements. So how am I being able to do this:

System.out.println(args[x].length())

I felt that there shouldve been a nullpointer exception being that element 0 has nothing in it.
 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
crappola.
 
Charith Fernando
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as said by a fellow rancher, this statement doesnt get executed.



in this for loop first of all the variable x is assigned the value 0 and then it checks the condition whether x is less than the length of the args array (in this case since there's no arguments passed as you say).. the condition fails and the for block never gets executed....

try putting the println statement outside the for block...



if you put this outside the for loop you may get a ArrayIndexOutOfBoundsException rather than a NullPointer since 0th index is not present in an array.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic