boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Java版 - help on this scope question
相关主题
问一个java的面试题 (转载)
It's a Java Bug
JAVA 求解
help "java.lang.NoSuchMethodError"
anyone saw this on code?
interesting
about loop control
eclipse how to remember a code location and jump back?
java compilation question
Help with Tomcat for Eclipse v1.03
相关话题的讨论汇总
话题: out话题: scope话题: int话题: testscope话题: variable
进入Java版参与讨论
1 (共1页)
l***r
发帖数: 459
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!
n*****k
发帖数: 123
2

~~~~~~~~~~~~
here is the compilation error
Because in the first example, there is no instance varible(or class variable)
nameed x exists other than the local varibale inside the method, so the scope
of the x is all over the method, and it can not be shadowed any other local
variable inside the method.
On the other hand, the second example has an instance variable x and also a
local block variable x, inside the if block, the local variable

【在 l***r 的大作中提到】
: 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 );

h******b
发帖数: 312
3
Nod, agree, very clear explanation!

variable)
scope

【在 n*****k 的大作中提到】
:
: ~~~~~~~~~~~~
: here is the compilation error
: Because in the first example, there is no instance varible(or class variable)
: nameed x exists other than the local varibale inside the method, so the scope
: of the x is all over the method, and it can not be shadowed any other local
: variable inside the method.
: On the other hand, the second example has an instance variable x and also a
: local block variable x, inside the if block, the local variable

1 (共1页)
进入Java版参与讨论
相关主题
Help with Tomcat for Eclipse v1.03
ant javac error in eclipse 3.0?
Problem on ANT,JAVA,JSP,JSPPrecompiler
How big is the penalty for compile with debugging mode on?
也问一个Eclipse的问题
QT is LGPL now
刚刚开始学习java,麻烦帮我看一下我哪里错了行吗?谢谢
其实JSP也不错
问一个 java generic问题
Java 求解2
相关话题的讨论汇总
话题: out话题: scope话题: int话题: testscope话题: variable