0%

JavaSE local vs instance variables

Local Variable

A local variable is defined within a method.

Warning!
Local variables must be initialized before sue. They do not have default value and contain garbage data until initialized. The compiler will not let you read an uninitialsed value.

1
2
3
4
5
6
public int incorrect(){
int y = 10;
int x;
int reply = x + y; // do not compile
return reply;
}
1
2
3
4
5
6
7
public int correct(){
int y = 10;
int x;
x = 3;
int reply = x + y;
return reply;
}
1
2
3
4
5
6
7
8
9
10
11
12
public int incorrect(){
int answer;
int onlyOneBranch;
if (check) {
onlyOneBranch = 1;
answer = 1;
} else {
answer = 2;
}
System.out.println(answer);
System.out.println(onlyOneBranch); // do not compile
}

Compiler can detect if the variables are initialized or not.

Instance Variable

Variables that are not local variables are known as instance variables or class variables.
Instances variables are also called fields. Class variables are shared across multiple objects.

Instance and class variables do not require you to initialize them because they are given default as long as you declare it.

Variables Default initialization value
boolean false
byte, short,int,long 0
float, double 0.0
char ‘\u0000’
All objects references null

Reference