aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes scope Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "scope " Watch "scope " New topic
Author

scope

sriranch
Greenhorn

Joined: Oct 03, 2000
Posts: 1
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

Joined: Sep 28, 2000
Posts: 7
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

Joined: Sep 23, 2000
Posts: 149
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

Joined: Aug 30, 2000
Posts: 3141
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


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Bob Kerfoot
Ranch Hand

Joined: Oct 01, 2000
Posts: 47
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
 
subject: scope
 
Similar Threads
Doubt on order of execution
Why this Output?
scope of local variables
Wrong Output?
A mock question