Thor
Thor

Reputation: 10058

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

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

Answers (3)

so-random-dude
so-random-dude

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

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

Upvotes: 1

jace
jace

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

Related Questions