Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Passing Arguments

 
Chatura Dilan
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • 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 ]
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • 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
  • 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?
 
Shyam Prasad Murarka
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
What a nice artical

Thank you Shyam
and Ken too
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic