0

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?

Shnick
  • 1,199
  • 1
  • 13
  • 32
  • Instance fields have default values, objects to null. Local variables don't have defaults. Numbers default to 0. – WJS Aug 03 '19 at 01:12
  • 1
    Instance variables have defaults. In this case, zero. Locals don't. A stupid inconsistency of the language if you ask me but it is what it is. – Michael Aug 03 '19 at 01:12
  • Ah, thanks. That explains a lot. – Shnick Aug 03 '19 at 01:13
  • @Michael The performance loss if they didn't do it that way would be even more stupid. It's a normal design decision, and not exclusive to Java. – user207421 Aug 03 '19 at 03:42
  • perhaps, see also: https://stackoverflow.com/a/3426854 – riyaz-ali Aug 03 '19 at 07:09
  • 2
    @user207421 It's nothing to do with performance... Ensuring that you initialize your fields explicitly is a compile time check. Having implicit defaults is stupid. Why is zero automatically a good value for an integer? Why not the minimum value or the maximum value? – Michael Aug 03 '19 at 12:32

0 Answers0