简体   繁体   中英

Why do I get this compile error in Java?

In java why is the following code not allowed by the compiler?

public class Test {

    public static void main(String[] args) {

        int x;
        int x = 4;// the error is generated here

    }

}

Because the second

int x = 4;

Is attempting to create a variable names "x" of type int, but this variable already exists ( created in the previous line )

Probably you would like to do:

int x;
x = 4;

( not using int in the second line )

That assigns the value 4 to x.

Or even better:

int x = 4;

That creates the variable x of type int and assign the value of 4.

You have declared two int variables; both named x . This is not allowed.

Try:

public static void main(String[] args) {
    int x;
    x = 4;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM