Reputation: 10058
I understand that it is illegal to declare local variables of the same name in the same scope. I wrote this very simple class, and yes, the IDE does display an error next to int i = 10;
. But when I run the code, everything seem to be fine.
public class VariableWithSameName {
static void myMethod(int i){
int i = 10; //error: variable i already defined in method
}
public static void main(String[] args){
}
}
It is only when I called myMethod
did a run time error occurred.
public class VariableWithSameName {
static void myMethod(int i){
int i = 10; //error: variable i already defined in method
}
public static void main(String[] args){
myMethod(1);
}
}
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - variable i is already defined in method myMethod(int)
So why runnning the first version does not results in a run time error?
Upvotes: 0
Views: 666
Reputation: 16485
Just adding my 2 cents, If you are wondering how a class with compile error is getting compiled , take a look here https://stackoverflow.com/a/7590454/6785908
The IDE's internal compiler is - at least in some cases - able to keep going with the build, even when some classes don't compile fully. It will even produce class files for the broken classes if possible, generating methods which throw an exception as soon as they're called.
Upvotes: 1
Reputation: 77187
This is a compile-time error. Presumably you successfully compiled before introducing the error and are still executing that .class
file.
Upvotes: 1
Reputation: 1674
Because in run time. You never called your method "VariableWithSameName" and that's why. run time error will only occur if a system run onto an error . but compile time error will determine all possible errors that in can found during compilation
Upvotes: 2