• 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

doubt regarding object reference passed in a method in this particular program

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class StackEx {

public static void main(String args[])
{
Stack s1 = new Stack ();
Stack s2 = new Stack ();
processStacks (s1,s2);
System.out.println (s1 + " "+ s2);
}
public static void processStacks(Stack x1, Stack x2)
{
x1.push (new Integer ("100"));
x2 = x1;
}

}
why does it print [100] [] and not [100][100] ?
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All parameter passing in Java is by value. When you send a reference as a parameter, a copy of the reference is sent. So if you assign the formal parameter in the method to point to another object inside the method, it has no effect on the reference you send.
 
Ranch Hand
Posts: 893
Tomcat Server Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because you are sending reference types to the method processtacks.

So in the method processstacks x1 refers to the same object as s1 and x2 refers to the same object as s2.

In these method you push an Integer which pushes this to the same object than s1 refers to. Next you are refering x2 to the same object as x1 and this is s1. After the method processstacks x1 and x2 are lost.

So you still have s1 and s2 refering to different objects. In which s1 has an Integer("100"). Changing refering x2 to x1 to s1 doesn't change the reference of s2, because x2 is a copy of s2 which is only active in the method processstacks
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic