Local variables of same name in same scope, IDE display error but when I run the program, no run time error results

假装没事ソ 提交于 2020-01-11 13:13:29

问题


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?


回答1:


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.




回答2:


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




回答3:


This is a compile-time error. Presumably you successfully compiled before introducing the error and are still executing that .class file.



来源:https://stackoverflow.com/questions/39908687/local-variables-of-same-name-in-same-scope-ide-display-error-but-when-i-run-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!