Java does its best to ensure that all variables are initialized correctly before they are used. If it is defined as a "local" variable relative to a method, the guarantee is expressed through a compile-time error message. Therefore, if you use the following code:
void F () {
int i;
i++;
} The
will receive an error message telling you I may not have been initialized. Of course, the compiler can also give me a default value, but it looks more like a programmer's fault, at which point the default will be "counterproductive." If a programmer is forced to provide an initial value, it can often help him or her to correct "bugs" in the program.
However, if you set the base type (the primary type) to be a data member of a class, the situation becomes slightly different. Since any method can initialize or use that data, it may not be practical to force the programmer to initialize it to an appropriate value before the data is formally used. However, it is also very unsafe to give it a garbage value. Therefore, all the base type data members of a class are guaranteed to get an initial value. You can see these values in the following applet:
: Initialvalues.java
//shows default initial values
class measurement {
Boolean t;
char c;
byte B;
Short S;
int i;
Long L;
float F;
Double D;
void print () {
System.out.println (
"Data type inital value\n" +
"Boolean " + t + "\ n" +
") Char "+ C +" \ n "+
" byte + B + "\ n" +
"short " + S + "\ n" +
"int " + i + "\ n" +
"long" + L + "\ n" +
"float " + f + "\ n" +
"double " + D);
}
public class Initialvalues {public
static void Main (string[] args) {
measurement d = new Measurement ();
D.print ();
/* In the case you could also say:
new Measurement (). print ();
*/
}
} ///:~
Enter the results as follows:
Data type inital value
Boolean false
char
byte 0
short 0
int 0
Long 0
float 0.0
double 0.0
Where the char value is null (NULL) and no data is printed.
As you'll see later, when you define an object handle inside a class, that handle gets a null value if you don't initialize it as a new object.