I just found that Java handles variable initialization in different ways.
Case-1:
class A {
boolean x;
public static void main(String[] args) {
A a = new A();
System.out.println(a.x);
}
}
When I ran above program it shows like "false" as output. But now I am posting other piece of code:
Case-2:
class A {
public static void main(String[] args) {
boolean x;
System.out.println(x);
}
}
Now, above piece of code shows that
java.lang.Error: Unresolved compilation problem:
The local variable x may not have been initialized
Why the same thing is handled in very different ways? Thanks in advance!
From the Oracle documentation on Java Primitive Data Types:
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
So this is an interesting nuance. If a primitive type variable is locally declared, you must specify a value for it.