code: class kon { public static void main(String args[]) { String a[] = new String[5]; for(int i=0; i<5; a[i++]="hi");
System.out.println(a[6]); //statement 1 System.out.println(a[5]); //statement 2 } } i am getting strange results when i execute the above code. If we initialize the array elements without using for or while loop, it works fine and throws ArrayIndexOutOfBounds Exception as it should be. But if we use the for loop as per above then it shows as following: on executing only statement 1 - null on executing only statement 2 - throws NoSuchFieldException on executing both the statements- throws NullPointerException can u please help me why is it so? (replace the for loop with while loop and then execute both the statements changing the order, it's different from the for loop too).
Rashmi Tambe
Ranch Hand
Joined: Aug 07, 2001
Posts: 418
posted
0
Hey, I got results as follows... On executing Only 1st Stmt - ArrayIndexOutOfBoundsException On executing 2nd stmt - ArrayIndexOutOfBoundsException On executing BOth - ArrayIndexOutOfBoundsException How come u r getting null for the first one? Compile it once again...and even after using while loop the result is the same. so i dont understand what do u mean by...
(replace the for loop with while loop and then execute both the statements changing the order, it's different from the for loop too).
Guoqiao Sun<br />SCJP2 SCWCD2<br />Creator of <a href="http://www.jiris.com/" target="_blank" rel="nofollow">www.jiris.com</a>, Java resource, mock exam, forum
Nils W Widmer
Greenhorn
Joined: Aug 13, 2001
Posts: 14
posted
0
what I find cool u can actually initialise an array this way, if someone has some other cool things BTW: I get ArrayIndexOutOfBoundsException using JDK1.3
------------------ [-_-]
[-_-]
ashok khetan
Ranch Hand
Joined: Jul 29, 2001
Posts: 153
posted
0
hi all! I compiled it again and i am getting the same results as i have written in my query. I am using JDK1.2.2. Don't know why it is displaying the output in this way.. anyway i would like to go with what majority says.. quote: ------------------------------------------------------------------------------- (replace the for loop with while loop and then execute both the statements changing the order, it's different from the for loop too). -------------------------------------------------------------------------------- In the above quote, i actually mean that if we use while loop and execute both the statements by changing their order(like stmt2 first and then stmt1), then the result will be different than what we get in case of 'for' loop using the order what we use with while.