Reputation: 4597
In the language specification it says:
local variables are definitely set before use. While all other variables are automatically initialized to a default value, the Java programming language does not automatically initialize local variables in order to avoid masking programming errors.
What is exactly masking programming errors are in Java?
An example explaining this, would be nice.
Thanks
Upvotes: 2
Views: 1043
Reputation: 24134
To understand this, you need to compare with what C/C++ do. In C/C++, a local variable contains garbage value when declared. So, if you forget to assign a value, the compiler won't complain and all references to such a local variable will work with the garbage value, resulting in unexpected behavior.
In Java, such an uninitialized local variable results in a compile-time error making the developer explicitly initialize it to a meaningful default value before using it.
C/C++
int do_something(int value) {
int i;
if (value > 10) {
i = value;
}
return i;
}
The above snippet is valid in C++, but invalid in java.
int doSomething(int value) {
int i;
if (value > 10) {
i = value;
}
//
// This line will throw a compile-time error that
// `i` may not have been initialized.
//
return i;
}
Upvotes: 6
Reputation: 1165
"Masking programming errors" are not a particular kind of error. It means that it doesn't want to "mask" (hide, obfuscate, make it difficult to detect) errors in your programming. For instance, the following code has a bad error. I never set the String variable to anything.
String theString;
System.out.println(theString);
This code will compile but won't run. You'll get a null reference exception or the like. The reason is because the variable theString
is never set to a value. If, on the other hand, Java set the variable theString
to a value (say, an empty string, ""), the program would run but wouldn't print anything. You might spend a long time trying to figure this out because Java would "mask" the error by setting a default value.
The compiler is trying to help here because local variables can be the source of a lot of issues. Anything Java can do to expose these issues (the opposite of masking them) is helpful.
Upvotes: -1