Nouvel Travay Nouvel Travay - 9 months ago 54
Java Question

Initialize int to 0 or not?

In the android source code I see they define four variables as

protected int mPaddingRight = 0;
protected int mPaddingLeft = 0;
protected int mPaddingTop;
protected int mPaddingBottom;

In Java, what is the difference in initializing a variable to 0 or not? I don’t understand that in some compilers I cannot do a comparison unless I initialize the field. But that is not the case here. Does this have to do with optimization? Or is this just inconsistent/bad coding practice?


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