Why is int face; not initialized in this code? And when I should use or not use initialization?
import java.util.Random;
public class RandomIntegers
{
public static void main( String[] args )
{
Random randomNumbers = new Random( 3 );
int face;
for( int counter = 1; counter <=20; counter++)
{
face = 1 + randomNumbers.nextInt( 6 );
System.out.printf("%d ", face );
if( counter % 5 ==0 )
System.out.println();
}
}
}
Actually, this is an interesting question.
The compiler sees that
face
is only used in the for loop. So if the for loop is entered (which it will be in this case) theface
will always be initialised where it is used.If you use
face
outside the loop you get an error as the compiler thinks the loop may not have been executed (although in your case, it always is).