• 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

Help pl!

 
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anybody explain the following with the correct answer as "10 and 40".Thanks
 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;
}
}
 
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot!I got it!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic