By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,898 Members | 2,022 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,898 IT Pros & Developers. It's quick & easy.

scope concept on java?????

dmjpro
100+
P: 2,476
i have code like this .. see carefully

void test
{
int i;
{
int i;
}
}
why does not java support this .... as C and C++ supports this

plz help me out .... thanxxxxx
Mar 13 '07 #1
Share this Question
Share on Google+
5 Replies


10K+
P: 13,264
i have code like this .. see carefully



why does not java support this .... as C and C++ supports this

plz help me out .... thanxxxxx
They are indistinguishable
What then would be the output of calling

Expand|Select|Wrap|Line Numbers
  1.  
  2. void test {
  3.  int i = 5;
  4.  {
  5.  int i = 10;
  6.  System.out.println(i + i);
  7.  }
  8. }
  9.  
?
Mar 13 '07 #2

dmjpro
100+
P: 2,476
i know it is not possible .....

in C and C++ there is a way to access the outer varibale using ::(scope resultion operator)

why this is stopped in java?????

thanxxxxxx
Mar 13 '07 #3

10K+
P: 13,264
i know it is not possible .....

in C and C++ there is a way to access the outer varibale using ::(scope resultion operator)

why this is stopped in java?????

thanxxxxxx
Even in c++ that wont work dj. You use the scope resolution operator when you have the context.

in
Expand|Select|Wrap|Line Numbers
  1.  void test { 
  2.  int i;
  3. }
  4.  
the context of i is the function test.
in
Expand|Select|Wrap|Line Numbers
  1.  void test{ 
  2.  int i;
  3. {
  4. int y;
  5. }
  6. }
  7.  
The contect of y is still the function test. The {} cannot be named and so you cannot use :: with it. The scope of y is still the function test.
so having
Expand|Select|Wrap|Line Numbers
  1.  void test{ 
  2.  int i;
  3. {
  4. int i;
  5. }
  6. }
  7.  
wont work because both have the same context i.e the function test and so you have a duplicate variable name
Mar 13 '07 #4

dmjpro
100+
P: 2,476
can't i access in C++ using TC++-3.0


void test()
{
int i;
{
printf("%d",::i); //outer i
printf("%d",i); //inner i
}
}

m i right ..... ??????

thanx
Mar 13 '07 #5

10K+
P: 13,264
can't i access in C++ using TC++-3.0


void test()
{
int i;
{
printf("%d",::i); //outer i
printf("%d",i); //inner i
}
}

m i right ..... ??????

thanx
I thought :: was for global namespace. Anyway that does not compile on my VS6.0 and you missed the declaration for the inner i that you had earlier.



P.S maybe I should copy this to the C++ forum.
Mar 13 '07 #6

Post your reply

Sign in to post your reply or Sign up for a free account.