This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help pl! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Help pl!" Watch "Help pl!" New topic
Author

Help pl!

Sridhar Srinivasan
Ranch Hand

Joined: Nov 07, 2003
Posts: 117
Can anybody explain the following with the correct answer as "10 and 40".Thanks


Software_guy
fethi makhlouf
Ranch Hand

Joined: Feb 16, 2004
Posts: 50
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;
}
}


SCJP 1.4
Vineela Devi
Ranch Hand

Joined: Dec 20, 2003
Posts: 191
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

Joined: Nov 07, 2003
Posts: 117
Thanks a lot!I got it!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help pl!
 
Similar Threads
Flow Control
static variable?
Expanations os scjp code
Re: Constructors
Moke Ex qstn