Initialize int to 0 or not?

In the Android source code, I see that 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 when initializing a variable to 0 or not? I do not understand that in some compilers I cannot perform a comparison if I do not initialize this field. But this is not so. Is it related to optimization? Or is this just an inconsistent / bad coding practice?

+6
source share
4 answers

According to Java primitive turorial data types , all primitive data types have a default value. Thus, initialization is implied. Good practice: initialize values ​​before use 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 
+8
source

As noted in the comments, there is no difference. They will be inactivated with 0. However, if you use a good IDE or have other tools, it will be very easy for you to search and replace = 0; at = SomeOtherValueHere; .

I also find it always useful to start your variables before you get them.

+1
source

It is good coding practice to initialize variables.

From Oracle docs:

It is not always necessary to assign a value when declaring a field. Fields declared but not initialized will be set to a reasonable default compiler. Generally speaking, this default value will be zero or null, depending on the data type. Based on such default values, however, the style is usually considered poor programming.

The benefits of initializing variables are as follows:

  • It’s easier to keep track of your code.
  • Easily facilitates the work of static analysis tools.
  • In most common design patterns, you are prompted to initialize a variable to the default value, so that the programmer knows exactly what value the variable initializes.
  • Initializing variables is always recommended to prevent undefined behavior later in the program.
  • Debugging is easier if you initialize the variables.
+1
source

Others have indicated that class properties are initialized with default values ​​for you.

So, semantically, it makes no difference if you explicitly set them to 0 (or, for the properties of an object, set them to null.)

However, there may be a difference at the bytecode level. There is no guarantee that code that differs only in class properties that are implicitly and explicitly set by default will have exactly the same bytecode.

Older versions of the JDK are used to generate larger and longer code for explicit initialization, which was easy to verify with javap . (This fact was sometimes used as the basis for interview questions.) I did not check the latest JDK versions to make sure that this is still the case.

0
source

All Articles