File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes increment operator in while loop 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 "increment operator in while loop" Watch "increment operator in while loop" New topic
Author

increment operator in while loop

uzma Akbar
Ranch Hand

Joined: Sep 21, 2005
Posts: 40
class JMM124 {
public static void main(String args[]) {
int a = 0;
while (a++ < (args.length-1) ) {
System.out.print(args[a]);
}

}}

Please explain when we run the program why nothing is printed?
Any help is appreciated.

Uzma
Gyanesh Sharma
Ranch Hand

Joined: Nov 27, 2005
Posts: 47
java JMM124 "1" "2"
prints
2
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Why are you using args.length - 1?


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

Joined: Sep 21, 2005
Posts: 40
I am using args.length-1 because without -1 it throws run time exception. I was trying JMM124 abcde...so nothing was printed as I was not using spaces in between. Thanks for your help

uzma
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by uzma Akbar:
I am using args.length-1 because without -1 it throws run time exception...

This is a little odd, so I just want to be sure you understand what's happening here.

When incrementing through an array, it's common to start the index at zero and use a test like "< args.length."

But in this case, the index is being incremented after the test: "a++ < args.length."

Using "args.length - 1" is one way to avoid a NullPointerException, but if you initialize your counter to zero, then you're also going to miss the first array element (at index 0).


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Gyanesh Sharma
Ranch Hand

Joined: Nov 27, 2005
Posts: 47
You could write the program as follows to avoid the runtime exception:

class JMM124 {
public static void main(String args[]) {
int a = 0;
do {
System.out.print(args[a]);
}
while (++a < (args.length));

}}
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Or simply use args[a-1] (along with the original while loop and the postfix increment).
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Or write it conventionally thus:




In that case you can easily use the for loop to write it a more understandable way.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: increment operator in while loop