GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Why XX and not X?????? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why XX and not X??????" Watch "Why XX and not X??????" New topic
Author

Why XX and not X??????

Carol Murphy
village idiot
Bartender

Joined: Mar 15, 2001
Posts: 1195
Okay you gurus of java, I can't figure out what the difference is between these two programs. One compiles and runs just fine, the other doesn't. The difference is in the flip() method. One explicitly goes through the array, the other tries to use a for loop to do the same, but it doesn't work. Why won't the for loop work?
class XX
{
public static void main( String[] args )
{
boolean[] b = new boolean[ 4 ] ;
b[ 0 ] = false ;
b[ 1 ] = true ;
b[ 2 ] = false ;
b[ 3 ] = true ;

System.out.println( b[ 0 ] ) ;
System.out.println( b[ 1 ] ) ;
System.out.println( b[ 2 ] ) ;
System.out.println( b[ 3 ] ) ;

flip( b ) ;
System.out.println( b[ 0 ] ) ;
System.out.println( b[ 1 ] ) ;
System.out.println( b[ 2 ] ) ;
System.out.println( b[ 3 ] ) ;
}
static void flip( boolean[] b )
{
System.out.print("b is "+ b.length +" items long. \n" );
b[ 0 ] = !b[ 0 ] ;
b[ 1 ] = !b[ 1 ] ;
b[ 2 ] = !b[ 2 ] ;
b[ 3 ] = !b[ 3 ] ;
}
}
class X
{
public static void main( String[] args )
{
boolean[] b = new boolean[ 4 ] ;
b[ 0 ] = false ;
b[ 1 ] = true ;
b[ 2 ] = false ;
b[ 3 ] = true ;

System.out.println( b[ 0 ] ) ;
System.out.println( b[ 1 ] ) ;
System.out.println( b[ 2 ] ) ;
System.out.println( b[ 3 ] ) ;

flip( b ) ;
System.out.println( b[ 0 ] ) ;
System.out.println( b[ 1 ] ) ;
System.out.println( b[ 2 ] ) ;
System.out.println( b[ 3 ] ) ;
}
static void flip( boolean[] b )
{
System.out.print("b is "+ b.length +" items long. \n" );
for( int x = 0; x<=b.length; x++)
{
b[ x ] = !b[ x ] ;
}
}
}
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
Notice the "=" in x<=b.length, this is where the ArrayIndexOutOfBoundException come.

static void flip( boolean[] b )
{
System.out.print("b is "+ b.length +" items long. \n" );
for( int x = 0; x<=b.length; x++)
{
b[ x ] = !b[ x ] ;
}
}
}
[ November 01, 2003: Message edited by: chi Lin ]

not so smart guy still curious to learn new stuff every now and then
Doug Dunn
Author
Ranch Hand

Joined: Aug 03, 2003
Posts: 66
The standard idiom for looping through an array is as follows.

Do you see the difference? In this case, the length of the array is four, but the highest index value is three.


Download a copy of <a href="http://www.javarules.com" target="_blank" rel="nofollow"><i>"Mastering The Fundamentals of The Java Programming Language"</i></a>
Carol Murphy
village idiot
Bartender

Joined: Mar 15, 2001
Posts: 1195
Doh!!!
What the heck was I thinking?
Oh, wait, I wasn't thinking!
Thanks for pointing that out to me!!!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why XX and not X??????