It's not a secret anymore!
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Help pl!" Watch "Help pl!" New topic

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

fethi makhlouf
Ranch Hand

Joined: Feb 16, 2004
Posts: 50
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();
public void amethod(int x){

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.
[ 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:
subject: Help pl!
It's not a secret anymore!