javaandroidprimitive-types

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?


Solution

  • According to Java primitive data types tutorial: When fields are declared without initialization, the compiler will assign a sensible default value. Typically, this default would be zero or null, based on the data type.

    byte    0
    short   0
    int     0
    long    0L
    float   0.0f
    double  0.0d
    char    '\u0000'
    String (or any object)      null
    boolean false
    

    A good practice: initialize values before using them to prevent unexpected behavior.