Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help pl!

 
Sridhar Srinivasan
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody explain the following with the correct answer as "10 and 40".Thanks
 
fethi makhlouf
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
firsly, would you please, print you code in better way, 'cause it's hardly readable
About the result that's why you see 10 40:
Primitive i= 10, the amethod call will not affect its value, 'cause it's just a call argument,and it's not a reference! then it will get back its initial value just after the amthod call finishes!
wheras j is an instance variable, when it changes, it keeps the change!
and that's why u have 10 40 !

public class Pass{
static int j=20;
public static void main(String argv[]){
int i=10;
Pass p = new Pass();
p.amethod(i);
System.out.println(i);
System.out.println(j);
}
public void amethod(int x){
x=x*2;j=j*2;
}
}
 
Vineela Devi
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Sridhar,
ans is 10 and 40.
Let me make this clear to u.
The thumb rule is tht in java , always variables are passed by value.

at line 6, u r invoking the method amethod() by passing i as argument to amethod().
as already pointed out, since variables r passed by value, any changes made to i inside amethod() will never effect the actual value of i, since only a copy of i is passed as argument to amethod() but not i.
so, value of iat line 7 is 10 only.
in amethod() u r modifying value of j.Notice tht j is not passed to the method. so, any changes made to j inside amethod() will effect the actual value of j.
So, value of j at line 8 will be 40.
Hope u got it.
Vineela
[ February 22, 2004: Message edited by: Vineela Devi Jakka ]
 
Sridhar Srinivasan
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot!I got it!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic