wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Prefrence to local ? 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 "Prefrence to local ?" Watch "Prefrence to local ?" New topic
Author

Prefrence to local ?

Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 298


class Shadow
{
int x=10;
void show()
{
int x=1; //Line 100
System.out.println(x);
}
public static void main(String args[])
{new Shadow().show();}
}

why it does not give compile time error at line 100 , as two variables with name x are in scope.
Now how does compiler will decide a reference to x refer to which definition ?


Oracle Java Programmer , Oracle SQL Expert , Oracle Java Web Component Developer
Saif Asif
Ranch Hand

Joined: Aug 11, 2011
Posts: 440

Hello ,

Well why would the compiler complain at all ? A member variable of the class and a local variable of the method are entirely different in all aspects . I dont think its a matter of preference , but the method show() can not see the variable 'x' directly like this. Non static Member variables have to be accessed via this.x .


Muhammad Saif Asif Mirza
OCJA(5/6) OCJP(6) OCJWCD(6)
Zhenyi Luo
Ranch Hand

Joined: Sep 03, 2012
Posts: 33
Mahtab Alam wrote:
class Shadow
{
int x=10;
void show()
{
int x=1; //Line 100
System.out.println(x);
}
public static void main(String args[])
{new Shadow().show();}
}

why it does not give compile time error at line 100 , as two variables with name x are in scope.
Now how does compiler will decide a reference to x refer to which definition ?


Because you are shadowing variable in Java
Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 298

Now compiler complaint a Local variable x and a block variable x


class R
{
public static void main(String args[])
{
show(10);
}
static void show(int x)
{
for(int x=1;x<2;x++)
System.out.println(x);
}
}


compiler say x is already defined in show(int)

When scope conflict occurs then there is problem.
So why there is no scope conflict in the first code
Zhenyi Luo
Ranch Hand

Joined: Sep 03, 2012
Posts: 33
Mahtab Alam wrote:Now compiler complaint a Local variable x and a block variable x


class R
{
public static void main(String args[])
{
show(10);
}
static void show(int x)
{
for(int x=1;x<2;x++)
System.out.println(x);
}
}


compiler say x is already defined in show(int)

When scope conflict occurs then there is problem.
So why there is no scope conflict in the first code

Shadowing happens when local variable "shadow" the instance variable temporarily using the same name, but local variable could not "shadow" another local variable. Refer to this discussion: http://stackoverflow.com/questions/4623334/question-about-variable-scope-and-shadowing-in-java
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Prefrence to local ?