I'm relatively inexperienced with java and so I was doing a little bit of testing. I came across the following behaviour which seemed odd to me.
Take the following class:
public class FooBar {
int foo;
public void bar() {
foo = foo + 1;
}
}
The above code compiles and works. When running bar()
once, foo
is set to 1
. This was surprising to me as I expected an error because when running bar()
for the first time foo
is not initialised, and so I would've thought an error would've occurred.
Naturally, I thought that if something like this works, then I would've also expected something like this to compile and run:
public class FooBar {
public int bar() {
int foo;
foo = foo + 1; // Err: The local variable foo may not have been initialized
return foo;
}
}
However, when trying to compile this code I get an error:
The local variable foo may not have been initialized
My question: Why does the first example of the class FooBar
compile and run as expected, but the second doesn't?