由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Java版 - help on this scope question
相关主题
问一个java的面试题 (转载)java compilation question
It's a Java BugHelp with Tomcat for Eclipse v1.03
JAVA 求解ant javac error in eclipse 3.0?
help "java.lang.NoSuchMethodError"Problem on ANT,JAVA,JSP,JSPPrecompiler
anyone saw this on code?How big is the penalty for compile with debugging mode on?
interesting也问一个Eclipse的问题
about loop controlQT is LGPL now
eclipse how to remember a code location and jump back?刚刚开始学习java,麻烦帮我看一下我哪里错了行吗?谢谢
相关话题的讨论汇总
话题: 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版参与讨论
相关主题
刚刚开始学习java,麻烦帮我看一下我哪里错了行吗?谢谢anyone saw this on code?
其实JSP也不错interesting
问一个 java generic问题about loop control
Java 求解2eclipse how to remember a code location and jump back?
问一个java的面试题 (转载)java compilation question
It's a Java BugHelp with Tomcat for Eclipse v1.03
JAVA 求解ant javac error in eclipse 3.0?
help "java.lang.NoSuchMethodError"Problem on ANT,JAVA,JSP,JSPPrecompiler
相关话题的讨论汇总
话题: out话题: scope话题: int话题: testscope话题: variable