• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

static method.

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Test {
public static void main(String args[]) {
StringBuffer a = new StringBuffer("One");
StringBuffer b = new StringBuffer("Two");
Test.swap(a,b);
System.out.println("a is "+ a +"\nb is " + b);
}
static void swap (StringBuffer a, StringBuffer b) {
a.append(" more");
b=a;
}
}
What will be the output?
Answer:
a. a is One
b is Two
b. a is One
b is One
c. a is One more
b is One more
d. a is One more
b is Two
e. a is One more
b is Two more
asnwer is d
i thougth answer is c
a.append(" more"); // now a is "One more"
b=a; // now b = a means b is also "One more"
Correct me where i am wrong ???
 
Ranch Hand
Posts: 1467
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
append(" more"); // now a is "One more"
b=a; // now b = a means b is also "One more"
Correct me where i am wrong ???

YES (Inside the method )
NO (after returning from swap method execution)

For method calls Java passes the copy of the object's reference . This means when you change the value of the reference (a or b in this case) it does not change the original value of the object ref before this method is called.But if somehow you change the object's contents via these references inside the method IT CHANGES THE CONTENTS and the effect is there after retrning from the method. This explains why in this case the value of String a is changed to One more (because of the append method) and b's value is not changed (we just change the value of the copy of the reference).
regds
maha anna
[This message has been edited by maha anna (edited February 25, 2000).]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic