-1

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();
        }
    }
}
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
이현정
  • 29
  • 4
  • It is worthwhile considering that initializing instance fields, though essentially a no-op (there is no logical change to the code vs. not initializing) used to (and may still) result in different, larger compiled code. –  Jun 09 '15 at 14:18

2 Answers2

1

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) the face 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).

rghome
  • 8,529
  • 8
  • 43
  • 62
-2

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style - you should always initialize variables for readability, and to avoid confusion/mistakes.

int is initialized with 0 value by default.

With that said, you have to know, that local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Oracle documentation: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Ezzored
  • 905
  • 4
  • 10
  • 1
    "Fields that are declared but not initialized will be set to a reasonable default by the compiler" ... this is not always true. Local variables and instance fields that are declared `final` are not given an initial value by the JVM and must be initialized before use. See: http://stackoverflow.com/questions/415687/why-are-local-variables-not-initialized-in-java – scottb Jun 09 '15 at 14:06