The Artima Developer Community
Sponsored Link

Object Initialization in Java
Object Initialization in the Java Language and Virtual Machine
by Bill Venners
First Published in JavaWorld, February 1998

<<  Page 2 of 8  >>

Advertisement

Default initial values
If you provide no explicit initialization to instance variables, they will be awarded predictable default initial values, which are based only on the type of the variable. Table 1 shows the default initial values for each of the variable types. (These are the default initial values for both instance and class variables. Local variables are not given default initial values. They must be initialized explicitly before they are used.)

Type Default Value
boolean false
byte (byte) 0
short (short) 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
object reference null

Table 1. Default values for fields

If you don't explicitly initialize an instance variable, that variable will retain its default initial value when new returns its object reference. For example, here is a class, named CoffeeCup, whose innerCoffee field is not explicitly initialized (there are no constructors or initializers in the class):

// In source packet in file init/ex1/CoffeeCup.java
// This class has no constructors or initializers
class CoffeeCup {
    private int innerCoffee;
    //...
}

As a result, when the reference to a new CoffeeCup object is first returned by new, the innerCoffee field will be its default initial value. Because innerCoffee is an int, its default initial value is zero.

Note that this means that if you explicitly initialize innerCoffee, say to a value of 100, then when each CoffeeCup object is created, innerCoffee will, in effect, be initialized twice. First, innerCoffee will be given its default initial value of zero. Later, the zero will be overwritten with the proper initial value of 100. All of this takes place while the Java virtual machine is creating the new object -- before it returns the reference to the new object. By the time the reference to a new CoffeeCup object is returned from the new operator, the innerCoffee field will be set to 100.

<<  Page 2 of 8  >>


Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2014 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us