0

In JAVA world, field variables have default values if you don't initialize them, while local variables don't.

I have considered a lot and searched a lot but I still don't understand. Why does JAVA world design like that? By the way, I think it has something to do with heap and stack.

guo
  • 9,674
  • 9
  • 41
  • 79
  • 1
    See [Jon Skeet's answer](http://stackoverflow.com/a/1560704/3788176) to a related question. – Andy Turner Jul 28 '16 at 11:22
  • @AndyTurner Good that you put a link there. I am almost for that for each and good question/answer around here, one answer came from Jon ;-) – GhostCat Jul 28 '16 at 11:35

2 Answers2

1

Local variables are much easier to check that a variable is always initialised in a relatively limited scope when you can determine the code paths. It doesn't always get it right but does a good job unless the code is confusing.

final fields also have to be initialised, though only once. When one constructor calls another, it can get confused.

For non final fields, it is very hard to ensure a field is initialised before it is used for all possible code paths. e.g. how can it ensure a setter is always called before a getter if those calls are made from another class which might be changed in the future.

Instead the JVM leaves default values and makes it your problem to worry about.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Well, it is very good design in my opinion. The compiler is trying to check if programmer did not make any mistakes. Local variable should be initialized manually to avoid unexpected problems because it is usually used to do some additional calculations or actions and with default value it can be very difficult to track such a bug in the future. It is programmer responsibility to initialize local variable properly and use it in short block of code.

Planck Constant
  • 1,406
  • 1
  • 17
  • 19