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
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
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.
As noted in the comments, no there is no difference. They’ll be initalized with 0 implicitly. However if you use good IDE or have other tools, it would be really easy for you to search and replace
= 0; with
Also I think it is a good practice to always initialzie your variables before you access them.
Others have pointed out that class properties are initialized to default values for you.
So, semantically, there is no difference if you set them explicitly to 0 (or, for object properties, set those to null.)
However, there may in fact be a difference at the bytecode level. There is no guarantee that code that differs only in class properties that are implicitly vs. explicitly set to default values will have exactly the same bytecode.
Older versions of the JDK used to generate larger and longer code for explicit initialization, which was easy to check with
javap. (This fact was occasionally used as the basis for interview questions.) I haven’t checked recent versions of the JDK to see if this is still the case.