• 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

method parameters (reference vs primitives)

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi. Please,why is this happening?

prints "Method", but

prints "Hi Original". Notice the different assignments in change_i.
Any explanations?
Thanks!!!
Francisco.
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Francisco, In both the examples, you are passing a copy of reference to the array i. In example 1, the change_i method uses the passed reference, to change the value of the first element (i[0]) in the array. hence the change is visible in the calling method Compare.
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i added some print statements to the method change_i like this:
public static void change_i(String i[])
{
String j[] = {"Method"};
i = j;
System.out.println("i.toString() = " + i.toString() );
System.out.println("j.toString() = " + j.toString() );
System.out.println("method: j[0] = " + j[0]);
System.out.println("method: i[0] = " + i[0]);

}
here is the result:
i.toString() = [Ljava.lang.String;@7e74a5e3
j.toString() = [Ljava.lang.String;@7e74a5e3
method: j[0] = Method
method: i[0] = Method
class: i[0] = hi original
so based on these results here is what i see going on:
- method "change_i" gets a copy of the reference that is contained in "i"
- "i" is then assigned the reference to j, but only in the method "change_i".
- the original reference that "i" contains in "main" is unchanged

[This message has been edited by keith barron (edited April 06, 2001).]
[This message has been edited by keith barron (edited April 06, 2001).]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic