2

Possible Duplicate:
Uninitialized variables and members in Java
Why are local variables not initialized in Java?

In Java variables have default value, right? Even arrays are initialized by compiler.
So I can't understand the following:

int c;  
for(int i = 0; i < 10; i++){  
   c = i + 5;  
}  
System.out.println("Result = "+c);  

Why do I get a compiler error:

The local variable c may not have been initialized

Isn't c initialized to 0 by default by compiler?
So why do I get this error and why does the error go away if I explicitely do int c = 0?

Community
  • 1
  • 1
Jim
  • 18,826
  • 34
  • 135
  • 254

2 Answers2

6

No local variables must have to be initialized, class field variables has the default value

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 [...]

jmj
  • 237,923
  • 42
  • 401
  • 438
1

Beucase forloop is conditional loop. And as per compiler c might not have initialized if did not went into that conditional loop

Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
  • Ah!Ok. So the compiler here is not smart enough to understand that it will go in the loop? – Jim Jul 19 '12 at 06:19