There are two variables, a
and b
, which are not initialized. a
variable is of class Example1
and b
variable of class Main
. As we know if we not initialized any variable in java then it take default value. But when I want to print variable of Main
class it show error of initialization. But when I call the Example1
class variable then it executed successfully and gives default value.
What is the exact reason behind it?
class Example1 {
int a;
}
public class Main
{
public static void main(String[] args) {
int b;
Example1 e = new Example1();
System.out.println(e.a); // output: 0
System.out.println(b); // error: variable a might not have been initialized
}
}
When you write:
int b; // this is declaration
int b;
is a local variable. Method local variables need to be initialized before using them. And this is why you've got an error.
When you write
int b = 0; // this is initialization
When you write:
Example1 e = new Example1(); // This is an initialization
Primitive default value is zero when declared as class members.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With