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?

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

1)Where is this quote from? 2)Does this apply also to arrays?
Yes it applies to Object aswell, the link is provided at the end of quote
1

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

1 Comment

Ah!Ok. So the compiler here is not smart enough to understand that it will go in the loop?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.