• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain me the output in detail

 
srinivas saitala
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MWC205 {

public void m1(StringBuffer s1) {
s1.append("B");
System.out.println("One :"+s1);
}

public void m2(StringBuffer s1) {
s1 = new StringBuffer("C");
System.out.println("Two : "+s1);
}

public void m3(StringBuffer s1) {
System.out.println("min One "+s1);
}


public static void main(String[] s) {
StringBuffer s1 = new StringBuffer("A");
new MWC205().m1(s1);

new MWC205().m2(s1);

new MWC205().m3(s1);
System.out.print("Three "+s1);
}
}

Could anyone please explain me in detail, why the output of "Three" is AB instead of C.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by srinivas saitala:
class MWC205 {

public void m1(StringBuffer s1) {
s1.append("B");
System.out.println("One :"+s1);
}

public void m2(StringBuffer s1) {
s1 = new StringBuffer("C");
System.out.println("Two : "+s1);
}

public void m3(StringBuffer s1) {
System.out.println("min One "+s1);
}


public static void main(String[] s) {
StringBuffer s1 = new StringBuffer("A");
new MWC205().m1(s1);

new MWC205().m2(s1);

new MWC205().m3(s1);
System.out.print("Three "+s1);
}
}

Could anyone please explain me in detail, why the output of "Three" is AB instead of C.


The reason is that when a reference is passed as a parameter to a method, only a copy of the reference is sent. In the first line of m2, s1, the formal parameter, is set to point to a different object. Since this is just a copy of the original reference, it doesn't change the original reference.
 
dharmendra Rathor
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First thing to know is java uses pass by value methodology for passing argument to method.
S1 is a reference object. When you call [ new MWC205().m1(s1); ] method m1 you are passing reference of s1 by value i.e.
A copy of original reference to s1 is passed to method m1 . Now at this point original reference and a copy reference both are pointing to same
object , so inside method m1 " S1.append("B") " will change the original object and it will hold value "AB" .
On call to method m2 " new MWC205().m2(s1); " a copy of original reference to s1 is passed to m2 . Inside method m2 a new object of same
name s1 is created and displayed as output [ note here this new object s1 has nothing to do with original reference of s1 , this is a complete new
object ] .
At step " new MWC205().m3(s1); " no change is done to reference object s1 , only the value is displayed .
Hence the final value which object s1 is holding is " AB " .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic