• 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

Passing Arguments

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class T5{

public static void main(String args[]){

T6 t6_1 = new T6();
T6 t6_2 = new T6();
T6 t6_3 = new T6();

t6_1.test1(t6_2);
t6_1.test2(t6_3.x);

System.out.println(t6_2.x);// prints 20
System.out.println(t6_3.x);// prints 10
}
}


class T6{

int x = 10;

public void test1(T6 tt){

tt.x = 20;
}

public void test2(int y){
y = 30;
}


}


I wonder why the second System.out.println statement does not print 30 like the first System.out.println does.
Can anyone explain it why?

[ April 25, 2006: Message edited by: Chatura Dilan ]
 
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Java passes everything by value. In the first example you modify the actual instance member of the T6 object, in the second example you simply modify a copy of the variable that was passed.
 
Chatura Dilan
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why doesn�t it pass the copy of the instance member of the T6 object, like the second example pass the copy of the variable?
 
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Reader,
I would suggest you to read this article from JavaRanch Campfire Story : Pass By Value Please. Its an excellent piece of article.
 
Chatura Dilan
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What a nice artical

Thank you Shyam
and Ken too
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic