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
}
}
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
}
}
You have declared two int
variables; both named x
. This is not allowed.
Try:
public static void main(String[] args) {
int x;
x = 4;
}
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.