Link to home
Start Free TrialLog in
Avatar of ssackett
ssackett

asked on

Java: Scopping rules

This is a question about scopping rules.   In the code sample I have purposfully done somthing goofy to as a test.  I expected that line 3, {int b = 3; int c = 4;} ,would result in redefinition of b and c and shadow the variables with the same names in line 2.  Instead it results in the compiler errors shown below.  My question is why is it that the inner scope of line 3 does not allow the variables in line 2 to be redefined?
------------------------------
src\Initializer.java:5: b is already defined in main(java.lang.String[])
                { int b = 3; int c = 4;}
                      ^
src\Initializer.java:5: c is already defined in main(java.lang.String[])
                { int b = 3; int c = 4;}
----------------------------
                                 ^
class Initializer{
 
	public static void main(String [] args){
		int b = 1, c = 2;
		{ int b = 3; int c = 4;}
		System.out.println("Initializer: " + b + " " + c);
	
	}
}

Open in new window

Avatar of emce
emce

the {...} by itself doesn't produce a new visibility scope
emce is right.

For what you want to do you'd have to do something like this:
class Initializer{
        static int b = 1;
        static int c = 2;
 
        public static void main(String [] args){
                int b = 3;
                int c = 4;
                System.out.println("Initializer: " + b + " " + c);
        
        }
}

Open in new window

Avatar of ssackett

ASKER

emce & Zwei,

Why does the attached code fail to compile?  It seems that the b and c declared inside the initializer can't be seen outside the block (what I would expect) but that the block doesn't behave like a nested scope in other ways.
...
  {int b = 2;}
  b = 1
...

Open in new window

The point of a custom block decaration { }, is so that variables declared inside can be garbage collected and deleted outside of the block
The variables are both local variables and are both on the same memory stack within a single method. When you create a new scope, you move on top of the original stack, which is why you can't create a new variable with the same name:
int a = 2;
{int a = 3;} <-- illegal, a is still on the stack.

But when you create a variable within a new scope, when you leave that scope the variable dies which is why this works:

{int b = 2;} <-- b dies here
int  b = 1;
ASKER CERTIFIED SOLUTION
Avatar of Thomas4019
Thomas4019
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the help guys.  Yet another reason why it's dangerous to mix C and Java.