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 Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "increment operator " Watch "increment operator " New topic
Author

increment operator

Nirav Parghi
Greenhorn

Joined: Nov 01, 2000
Posts: 10
Why does this code
public class strprint {
public static void main (String[] args) {
StringBuffer str1 = new StringBuffer(50) ;
for(int i=0; i++<args.length {>
str1 = str1.append(args[i]);
str1 = str1.append(" "); }
System.out.println(str1);
}
}
give me an ArrayOutOfBoundsException ?
strangely, when I substitute with this line
for(int i=0; i<args.length;i++ )>
it works ! (ideally I think this should not happen ?)
I'm confused !!
faiza haris
Ranch Hand

Joined: Oct 17, 2000
Posts: 173
The problem is with line
str1 = str1.append(args[i]); when the argument list is out of bound, then obviously it would give the ArrayOutofBoundException.
I have given the arguments
java hello pal
and after printing these two it gives the Exception.So with minor changes to your code:

public class Strprint {
public static void main (String[] args) {
StringBuffer str1 = new StringBuffer(50) ;
for(int i=0; ;i++)
{str1 = str1.append(args[i]);
System.out.println(args[i]);
str1 = str1.append(" ");
}
//System.out.println(str1);
}
}
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
It is more readeable by using the [ c o d e ] and [ / c o d e ] (remove spaces) UBB tags respectively before and after your code samples.
You must also put spaces around the < character!
Like this:

PS: To learn more about UBB, click HERE.
Cheers,
Beno�t
[This message has been edited by Beno�t d'Oncieu (edited November 01, 2000).]
rajesh dalvi
Greenhorn

Joined: Oct 24, 2000
Posts: 7
It gives ArrayIndexOutOfBoundsException for the last element.
This is because first condition is checked and then immdiately it increaments i.
so for last element value of i is actualy args.length.
here is some alternate working code:-

public class strprint {
public static void main (String[] args) {
StringBuffer str1 = new StringBuffer(50) ;
for(int i=0; i < args.length; ) {
str1 = str1.append(args[i++]);
str1 = str1.append(" "); }
System.out.println(str1);
}
}
value of i should be incremented after use in args[i]

[This message has been edited by rajesh dalvi (edited November 01, 2000).]
 
 
subject: increment operator
 
Threads others viewed
Advice me on JQ+ and some else...
modify the arrray to string
reverse a string
Teach Yourself : Gain Performance in 1 minutes
StringBuffer var as an argument
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com