Reputation: 88
I tried compiling this code in Java:
class D
{
public static void main(String arg[])
{
f1();
}
static void f1()
{
int a;
int b=5;
for(;b<=10;b++)
a=b;
System.out.println(a);
}
}
But it generates an error that says: Variable 'a' might not have been initialized. Why is this happening, although a
is set in the for loop?
Upvotes: 0
Views: 124
Reputation: 787
Initialise variable
int a = 0;
because a is local variable and local variable is created on stack and variable created on stack memory does not assign any default value. So we must have to initialize local variable.
Upvotes: 0
Reputation: 88707
The loop might not run (the compiler doesn't know for sure) and thus a
might not be initialized.
This doesn't execute the print statement in the loop, just the assignment:
for(;b<=10;b++)
a=b;
System.out.println(a); //this will only run after the loop.
In the above case if b
was > 10 before the loop then a=b;
would never be executed and the print statement would get un initialized a
.
I assume you mean this instead:
for(;b<=10;b++) {
a=b;
System.out.println(a);
}
If you intend to print a
after the loop, initialize it to whatever value is appropriate, e.g. int a = 0;
.
Upvotes: 5
Reputation: 161
The static error check isn't that clever. It doesn't know that your loop will always run, therefore you may output 'a' without initializing it.
That type of issue is only picked up at run time, so it warns you.
Upvotes: 2
Reputation: 48404
Variables inside method bodies are not assigned default values like they would as instance fields, etc.
Therefore your int a
declaration, which does not initialize a
with a value, generates your compile error.
Assign a
with a default value to get rid of this.
int a = 0;
... or declare it outside the method body:
static int a;
static void f1() {
...
System.out.println(a); // no errors
}
Upvotes: 2