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 | public int incorrect(){ |
1 | public int correct(){ |
1 | public int incorrect(){ |
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 |