help on this scope question# Java - 爪哇娇娃
l*r
1 楼
I have two pieces of code
1) has compilation error:
class TestScope {
public void test() {
int x = 2;
if ( true ) {
int x = 1;
System.out.println( "In if: " + x );
}
System.out.println( "Out If: " + x );
}
}
2) compiled and output is: In if: 1 Out If: 2
class TestScope {
int x = 2;
public void test() {
if ( true ) {
int x = 1;
System.out.println( "In if: " + x );
}
System.out.println( "Out If: " + x );
}
}
Can you tell me why Java support this differently?
Thanks!
1) has compilation error:
class TestScope {
public void test() {
int x = 2;
if ( true ) {
int x = 1;
System.out.println( "In if: " + x );
}
System.out.println( "Out If: " + x );
}
}
2) compiled and output is: In if: 1 Out If: 2
class TestScope {
int x = 2;
public void test() {
if ( true ) {
int x = 1;
System.out.println( "In if: " + x );
}
System.out.println( "Out If: " + x );
}
}
Can you tell me why Java support this differently?
Thanks!