File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

scope

 
sriranch
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any one explain why the following is not allowed in Java
int x; // outer scope
{
int x; // inner scope
}
One would assume that this should work.
Thanks
SRA
 
Li Yang
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The outer scope variable x is accessible inside the inner scope, hence you have a name conflict when you define the inner variable x.
 
Prasad Ballari
Ranch Hand
Posts: 149
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sriranch,
Can u pls give me little more detailed code.coz,u can have a class variable and instance variable of same name but with different scope.
Prasad
------------------
 
Jane Griscti
Ranch Hand
Posts: 3141
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi sriranch,
Well, it does work, to a point. It depends on the context. For example, it works fine in this code:

However, it won't work in the following context:

The answer is in JLS §14.4.2

The name of a local variable v may not be redeclared as a local variable of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time
error occurs.

Hope that helps.
Jane
 
Bob Kerfoot
Ranch Hand
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sriranch,
This probably will not help much but the JLS(Second Edition) simply states on page 281 that "if a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs".
Also, the only reason provided on page 282 is that "this restriction helps to detect some otherwise very obscure bugs".
Hope this helps.
Bob Kerfoot - SCJP
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic