When should we use / not use initialization in Java?

92 views Asked by At

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();
        }
    }
}
2

There are 2 answers

0
rghome On BEST ANSWER

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

1
Ezzored On

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