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
posted
0
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
posted
0
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
posted
0
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).]