tags:

views:

163

answers:

2

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

    }

}
+11  A: 

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

Try:

public static void main(String[] args) {
    int x;
    x = 4;
}
Ken Browning
Easy rep points ;)
Richie_W
Hey, I'll take them where I can get them :)
Ken Browning
I voted up but would still like to see an explanation about redefining a variable...and maybe a description of the compiler error for super rep points
Paxic
+10  A: 

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.

OscarRyz