Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit initialization of primitives

I understand that Java primitives have default initialization values; for example 0 for int.

From my research it seems that I should not rely on these values. Should I always provide an explicit initialization and if so, where?

Here's part of my program:

public class Calculator {

// Initialize value where it's declared?
private int value;

public Calculator() {
    // Initialize value in constructor?
}

public void add(int other) {
    value += other;
}
}
like image 343
Kyle T Avatar asked Jun 20 '13 17:06

Kyle T


2 Answers

Using default values produced by Java is absolutely OK, you do not need to explicitly initialize instance or static fields of your class. Java Language Specification requires this, so any implementation of the language must comply. In other words, your code would remain 100% portable if you use default values of member variables. This applies to both primitive and reference types (the later are initialized with null).

See Java Language Specification, page 81, for more details.

4.12.5 Initial Values of Variables

Every variable in a program must have a value before its value is used: - Each class variable, instance variable, or array component is initialized with a default value when it is created

The only case where you must provide explicit initialization is when you declare local variables:

A local variable must be explicitly given a value before it is used, by either initialization or assignment, in a way that can be verified using the rules for definite assignment.

However, since failure to initialize a local is a compile-time error, the compiler will pinpoint every missing initialization before you can run your program.

like image 132
Sergey Kalinichenko Avatar answered Sep 21 '22 07:09

Sergey Kalinichenko


From my research it seems that I should not rely on these values.

You can rely on them. There will be no harm, as it is done by default as you already know.

Should I always provide an explicit initialization and if so, where?

For primitives, no it's not necessary to provide the explicit initialization, and I prefer not to. I rarely do and see people to do an initialization like - int i = 0; for instance variables. But, if you are talking about local variables, then you need to give them explicit values. The defaults are not implicit there.

But when the case comes for non-primitives, then you should do an explicit initialization, either at the point of declaration, or inside the constructor, as the values are by default null, which might result in NPE, if not taken care of. The benefit of initializing at the point of declaration is that, you won't have to put the initialization in each of your constructors.

like image 38
Rohit Jain Avatar answered Sep 20 '22 07:09

Rohit Jain