File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in nullpointerException. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in nullpointerException." Watch "Doubt in nullpointerException." New topic

Doubt in nullpointerException.

Amit Batra
Ranch Hand

Joined: Mar 04, 2006
Posts: 361

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

Joined: Sep 03, 2006
Posts: 3
Because the cycle doesn't execute.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Amit Batra
Ranch Hand

Joined: Mar 04, 2006
Posts: 361
Thats the whole point. there isnt anything in those elements. So how am I being able to do this:


I felt that there shouldve been a nullpointer exception being that element 0 has nothing in it.
Amit Batra
Ranch Hand

Joined: Mar 04, 2006
Posts: 361
Charith Fernando
Ranch Hand

Joined: Sep 12, 2005
Posts: 67
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.

Charith I Fernando<br />SCJP5, SCWCD, SCBCD, BSc(Hons) IS<br />+94 773 263 222 (mobile)
I agree. Here's the link:
subject: Doubt in nullpointerException.
It's not a secret anymore!