Reputation: 21
I'm kind of confused about the outputs.
This is the first program.
class A {
private int price;
private String name;
public int getPrice() {
return price;
}
public String getName() {
return name;
}
}
class B {
public static void main(String[] args) {
A a = new A();
System.out.println(a.getName());
System.out.println(a.getPrice());
}
}
This program compile without error. And the variables have values.
output -
null
0
Second program is,
class B {
public void value() {
int x;
System.out.println(x);
}
}
This program won't even compile.
B.java:4: error: variable x might not have been initialized
The question is why these variables act different? What is the reason. This may be a very simple question. But kindly explain me.
Thanks.
Upvotes: 1
Views: 125
Reputation: 2832
Instance variables are declared inside a class
. not within a method
.
class A {
private int price; //instance variable
private String name; //instance variable
}
And instance variables always get a default value( integers 0, floating points 0.0, booleans false, String / references null
).
Local variables are declared within a method
.
class B {
public void value() {
int x; // local variable
}
}
Local variables must be initialized before use.
class B {
public void value() {
int x = 2; // initialize before use it.
System.out.println(x);
}
}
Upvotes: 8