Variables and Initialization
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 Type | Initial Value |
---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | '\u0000' |
boolean | false |
object reference | null |
public class Main{
int x = 20;
}
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 local variable i may not have been initialized
Class variable (static variable)
y
would be set to 30 when the Main
class is loaded.
public class Main{
static int y = 30;
}