wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt from the question! 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 "doubt from the question!" Watch "doubt from the question!" New topic
Author

doubt from the question!

fengqiao cao
Ranch Hand

Joined: Oct 26, 2001
Posts: 71
hi, there
the output of following code is 10 and 40(i compiled and ran). i know why 10 got printed out, but i don't know why 40 got printed out(i thougt 20 would be the output). could some one explain to me??
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;
}
}
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
j is 20
2 * 20 is 40
Note that j has a class scope while the scope of i is within the method main !
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4474
    
    6

It prints out 40 because the j referenced in amethod() is the j declared as static int in the class, so whatever you do to it in amethod() will be visible in main(). i is not affected, of course, because x is local to amethod() and any changes to it are not visible in main().


------------------
Junilu Lacar
Sun Certified Programmer for the Java� 2 Platform


Junilu - [How to Ask Questions] [How to Answer Questions]
fengqiao cao
Ranch Hand

Joined: Oct 26, 2001
Posts: 71
hi,
thanks both of you! i got it.
 
GeeCON Prague 2014
 
subject: doubt from the question!