Search code examples
javaclanguage-design

Why Does Java Require Variables to Be Initialized?


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?


Solution

  • 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.