-5

In Java, why doesn't the compiler simply assume that an uninitialised variable should have 0 as its value, like C does? Is this just BetterPractice in general, or is there another reason that is particular to Java?

wafflesausage
  • 295
  • 5
  • 14
  • 9
    Automatic variables in C have indeterminate values, static variables are zero initialized though. – Shafik Yaghmour Jul 07 '14 at 01:34
  • I don't think it's particular to Java. – Thilo Jul 07 '14 at 01:36
  • 2
    It *does* assume that for member variables. It doesn't do that for local variables, doubtless for performance reasons, but the only person who really knows the answer is Jim Gosling. There's nothing Java-specific about this practice though. – user207421 Jul 07 '14 at 01:38
  • Java is strongly typed language. You can't make every variable initialize to zero since zero (0) might be the wrong type. Is (0) an integer or is it float or is it char or ??? – Nasser Jul 07 '14 at 01:39
  • @Nasser: well, the same rules as for member fields could apply (the appropriate 0, or false, or null). – Thilo Jul 07 '14 at 01:40
  • I think it depends on the scope of your variable. If its a class variable(variable inside class), java gave it a default value, but if its a method variable(variable inside method) , you must instantiate it. – bumbumpaw Jul 07 '14 at 01:41
  • and even member variables need to be initialised if they are final. – Thilo Jul 07 '14 at 01:41

2 Answers2

2

Because the code that uses a variable that has not been initialized, leading to unpredictable or unintended results.

I guess java designers must have faced lot of problems while programming with C like stuck in loop, So probably when they were developing java they decided to get rid of this problem. And that is why we call java a robust language.

And also assigning variables initial values is not always fine. For example

int i;      // uninitialized variable ,suppose it is initialize to 0 by compiler
int j=5/i;  // run time error  
A.s. Bhullar
  • 2,680
  • 2
  • 26
  • 32
  • 1
    Note that the JVM for all practical purposes set variables to a variant of zero when allocated (as opposed to C where the content is undefined). The additional restrictions are enforced by the compiler. – Thorbjørn Ravn Andersen Jul 07 '14 at 12:20
1

For most situations using a variable before assigning it to anything is a mistake, and by having the compiler explicitly consider it an error it helps catching these bugs very early in the programming process.

Saying that uninitialized variables contain zero remove this capability. It is my guess that having the programmer type some more to explicitly assign variables to zero was found to be less important than finding some rather tricky bugs at runtime.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347