Forum Stats

  • 3,875,456 Users
  • 2,266,916 Discussions
  • 7,912,219 Comments

Discussions

Question related to local and instnace variabla

class X
{
String name="sanjay";
public String getName()
{
return name;
}
public void setName(String name)
{
name = name;
}
public static void main(String ar[])
{
X ob=new X();
ob.setName("nitesh");
System.out.println(ob.getName());
}
}


Output is sanjay
Question:- Why it's output is not nitesh

Answers

  • 796440
    796440 Member Posts: 19,179 Gold Trophy
    You seem to be under the impression that when you write
    name = name;
    the compiler is able to read your mind and know that for the left-hand "name" you mean the member variable, and for the right-hand name you mean the local variable. This is not the case. When you have a local variable called "name", then if you write just "name", it always means the local variable. If you want to refer to a member variable with the same name as a local, you have to qualify it with "this":
    this.name = name;
This discussion has been closed.