This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayIndexOutOfBundsException ??? pl help !!!

 
jay nair
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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(j=0;j<5;j++)
{
arr[i][j]=k;
k++;

}



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

}
}
}

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<aarr.java:13>

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 !
 
Svend Rost
Ranch Hand
Posts: 904
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1296
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
jay nair
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
understood , thanks a ton !!!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic