Variables and Initialization

Java supports variables of three different lifetimes:

Member variable

A member variable of a class is created when an instance is created, and it is destroyed when the object is destroyed.

All member variables that are not explicitly assigned a value upon declaration are automatically assigned an initial value.

The initialization value for member variables depends on the member variable's type.

Element TypeInitial Value
byte0
short0
int0
long0L
float0.0f
double0.0d
char'\u0000'
booleanfalse
object referencenull
In the following example, the variable x is set to 20 when the variable is declared.

public class Main{
   int x = 20;
}
The following example shows the default value if you don't set them.

class MyClass {
  int i;

  boolean b;

  float f;

  double d;

  String s;

  public MyClass() {
    System.out.println("i=" + i);
    System.out.println("b=" + b);
    System.out.println("f=" + f);
    System.out.println("d=" + d);
    System.out.println("s=" + s);
  }

}

public class Main {
  public static void main(String[] argv) {
    new MyClass();

  }
}

The output:


i=0
b=false
f=0.0
d=0.0
s=null

Automatic variable(method local variables)

An automatic variable of a method is created on entry to the method and exists only during execution of the method.

Automatic variable is accessible only during the execution of that method. (An exception to this rule is inner classes)

Automatic variable(method local variables) are not initialized by the system.

Automatic variable must be explicitly initialized before being used.

For example, this method will not compile:


public class Main{
    public int wrong() { 
      int i;
      return i+5;
    } 
 
}
The output when compiling the code above:

The local variable i may not have been initialized

Class variable (static variable)

There is only one copy of a class variable, and it exists regardless of the number of instances of the class.
Static variables are initialized at class load time; here y would be set to 30 when the Main class is loaded.

public class Main{ 
  static int y = 30;
}
Home 
  Java Book 
    Class  

Class Creation:
  1. Introducing Classes
  2. A Simple Class
  3. A Closer Look at new
  4. Variables and Initialization
  5. this Keyword
  6. A Demo Class
  7. The Person class: another demo
  8. Understanding static