• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

how it is happening

 
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class X {
void s(String a) {
a="second";
System.out.println("in method() "+a);//second
}
public static void main(String args[]) {
String a="first";
X x1=new X();
x1.s(a);
System.out.println("in main() "+a);//first
}
}
in above code how it is giving a as first
it was already updated in s() naaaa

plz help me
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you send an object reference to a method, you are sending a copy of the reference. If you point the copy of the reference to a different object in the method, that won't have any effect on the original object.
 
kotha vijaybabu
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
then what about this

class X {
String a;
void s(String a) {
this.a="second";
System.out.println("in method() "+a);
}

public static void main(String args[]) {
String a="first";
X x1=new X();
x1.s(a);
System.out.println("in main() "+a);
}
}
 
Keith Lynn
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by kotha vijaybabu:
then what about this

class X {
String a;
void s(String a) {
this.a="second";
System.out.println("in method() "+a);
}

public static void main(String args[]) {
String a="first";
X x1=new X();
x1.s(a);
System.out.println("in main() "+a);
}
}



Each time you create an instance of a class definition, space is reserved for each instance variable. In the method, you are setting the instance's copy of s to "second". However, because you have a local variable named s, it shadows the instance variable s. So that is why the method prints "first".
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic