File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "scope " Watch "scope " New topic



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.
Li Yang

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
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.
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 Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Bob Kerfoot
Ranch Hand

Joined: Oct 01, 2000
Posts: 47
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:
subject: scope
It's not a secret anymore!