Initialize int to 0 or not?
It is a good coding practice to initialize variables.
From Oracle Docs:
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.
The benefits of initializing the variables are as following:
- Makes it easier to follow your code
- Makes life easier for static analysis tools.
- Most of the prevalent design patterns asks you to initialize variable to a default value, so that the programmer knows exactly to which value the variable is initialized.
- It is always good practice to initialize variables to prevent undefined behavior later in the program.
- Debugging becomes easier if you initialize the variables.
Local variables must be initialized before use.
class Main {
public static void main(String[] args) {
int x;
System.out.println(x);
}
}
This code does not compile. However instance variables (or class in case they are static
) have default values.
According to Java primitive data types turorial , all primitive data types have a default value. So the initialization it's implicit. A good practice: initialize values before using to prevent unexpected behavior.
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false