Nouvel Travay Nouvel Travay - 2 years ago 134
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download