Default Values and Initialization in Java

Default values and initialization in Java

In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.

In the second code sample, a is class member variable, hence it will be initialized to the default value.

Default initialization in java

Is this true of all objects? Does using the new keyword initialize an
object regardless of whether it's a class variable or local variable?

When you use new keyword. it means that you have initialized your Object. doesn't matter if its declared at method level or instance level.

public void method(){
Object obj1;// not initialized
Object obj2 = new Object();//initialized
}

Default values in java

Only instance variables, static(Class) variables and array components are initialized to default values.

Local variables cannot be used unless they are initialized as they are not assigned default values.

Why is it necessary that variables should be initialized to default values in Java

Can anyone kindly explain that what is meant by unpredictable data and unpredictable behavior here.

If you programmed in C/C++, you would notice that an uninitialized variable carries some garbage value, present in the memory location allocated to it, interpreted as per the data type of the variable. The compiler doesn't complain about such variables and if the developer forgets to initialize them properly, the garbage values gets used, resulting in unexpected behavior of the program.

In Java, the JVM initializes all member variables to the default values based on the data type of the variable and complains about local variables that are not initialized during compilation, to avoid such unexpected behavior and making the developer always use initialized variables.

What is the default initialization of an array in Java?

Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.

  • For references (anything that holds an object) that is null.
  • For int/short/byte/long that is a 0.
  • For float/double that is a 0.0
  • For booleans that is a false.
  • For char that is the null character '\u0000' (whose decimal equivalent is 0).

When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new.

Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.

Relying on default field initialisation - is bad programming style?

The quoted text is:

"Relying on such default values, however, is generally considered bad programming style."

Cynically: "it is generally considered that" is often a way of saying that the author hasn't tried to find an authoritative source for the statement being presented.

In this case the assertion is clearly questionable. Evidence: 5 out of 5 Java Style Guides sampled do NOT say anything about whether you should or should relying on default values:

  • Google Java Style Guide
  • Twitter Java Style Guide
  • Java Programming Style Guide - JavaRanch (dubious)
  • Java Code Style Guidelines - Cornell University CS.
  • The OpenJDK Draft Java Style Guide

(Note, my methodology for sampling was to look at the first 5 distinct Google search hits for "java style guide". Then I searched each document for "default". This is not a thorough analysis, but it serves to make my point.)


OK. So does it really aid readability of Java code?

This is debatable.

On one hand, a novice Java programmer who hasn't learned about default initialization may be baffled about where the zeros or nulls are coming from. But if they bother to look for an explicit initialization and find there isn't one, that should be sufficient to cause them to read a tutorial or book to find out about default initialization. (You would hope!)

On the other hand, we don't normally expect novice Java programmers to be maintaining production code-bases. For an experienced Java programmer a redundant initialization does not improve readability. It is (at best) noise.

To my mind, the only thing that is achieved by a redundant initialization of a field is to signal to a future reader of your code that you have thought about the the initial value. (As @GhostCat expressed it, default initialization does not communicate intent.)

But conversely if I was that reader, I would not necessarily trust the thinking of the code author. So the value of this "signal" is also questionable.


What about reliability?

In Java it makes no difference. The JLS specifies that default initialization does occur for fields. And conversely, for local variables it is a compilation error to try to use a variable that has not been definitely initialized.

In short, the runtime behavior of a variable that is not explicitly initialized is entirely predictable.

By contrast in languages like C or C++ where variables may not be initialized, the behavior is unspecified, and can lead to crashes, and differences in behavior on different platforms. The case for always explicitly initializing variables is much stronger here.


What about performance?

It should make no difference. The JIT compiler should be able to treat a redundant initialization and default initialization as the same.



Related Topics



Leave a reply



Submit