This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes ArrayIndexOutOfBundsException ??? pl help !!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ArrayIndexOutOfBundsException ??? pl help !!!" Watch "ArrayIndexOutOfBundsException ??? pl help !!!" New topic

ArrayIndexOutOfBundsException ??? pl help !!!

jay nair

Joined: Sep 13, 2005
Posts: 28
class aarr


public static void main ( String args[])
int arr[][]=new int [4][5];
int i=0,j,k=0 ;

for (i=0;i<4;i++); // if i remove ; this it works fine


for ( i=0;i<4;i++)
for ( j=0;j<5;j++)
System.out.print(arr[i][j] + " " );


in the above program if i remove the semi colon for the first "for " loop it works fine , but if i dont then i get Error
" Exception in thread " main " java.lang.ArrayIndexOutOfBundsException :4 at aarr.main<>

my question is if i put the semicolon then value of i=3 and in next loop the fourth row of the array should be initialized and rest shld be zero , then why this error??

i'm pretty new to java thats why my questions might seem v confused .... any help will be appreciated
thanks !

Preparing for SCJP 5
Svend Rost
Ranch Hand

Joined: Oct 23, 2002
Posts: 904
Hey Jay,

Let's see if you can figure it out yourself.. else just reply again.

A for-loop has a body, and what (kinda) happends is that you put a pair
of {} around the statement after the for(...) statement.

Let's look at some examples:

For example here:

is transformed into:

and this:

is transformed into:

In your example you'll see the next statement can be a ; or a for statement.

Now, why do you get an error if the next statement is a forloop?

/Svend Rost
jay nair

Joined: Sep 13, 2005
Posts: 28
sorry couldnt understand what u r trying to say ,

my question is

is this correct , if it is then value of i before it enters the next for loop will be i=3,n hence the fourth row of the array shld be initialized , then why this error?

thnaks for the reply ,
sorry cudnt understand u
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
When the first loop is exited, i = 4 (the loop teminates because i is no longer less than 4) so you get a bounds error in the second loop (arr[4][j]). If the semicolon is removed, the loop outer loop is exited when i = 4, therefore no bounds error.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
jay nair

Joined: Sep 13, 2005
Posts: 28
understood , thanks a ton !!!
I agree. Here's the link:
subject: ArrayIndexOutOfBundsException ??? pl help !!!
It's not a secret anymore!