• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Object reference....

 
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all
I have one doubt,when v pass object reference to a method then the change made in the method do reflect on the original value.

So i though the ouput will be
One more
a is One more
b is One more

public class mast
{
public static void main(String[]arf)
{
StringBuffer a = new StringBuffer("One");
StringBuffer b = new StringBuffer("Two");
mast.swap(a,b);
System.out.println("a is "+ a +"\nb is " + b);
}

static void swap (StringBuffer a, StringBuffer b) {
a.append(" more");
System.out.println(a);
b=a;

}
}
but the Output
One more
a is One more
b is two

Why the change made to 'b' is not see in the output.
Pls explain.
[ January 27, 2005: Message edited by: Ramya JP ]
 
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just remember: Java always pass by value.
When you sent b to the method, you passed a copy of the bits that reference the object referenced by b. When you did

You`re telling the vm to make the copy of the reference to b to start refering, from now on, the same as reference a.
When you come back to main, your the "copy" reference has been lost. You only have the "old" and first b reference, which still references the same value ("two). Got it now?
Being brief, just remember that swap doesn`t work for objects in Java, because the "pass by value" i just described.
[ January 27, 2005: Message edited by: Leandro Melo ]
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check this out.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic