aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static variable? 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 "static variable?" Watch "static variable?" New topic
Author

static variable?

Owee Nicolas
Ranch Hand

Joined: Jun 16, 2002
Posts: 49
Given this class:
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;
}
}
The output is said to be 10 and 40. My question is if Java is a call-by-value, how come the static variable j was modified in the amethod?


Owee<br />SCJP 1.4
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
Owee,
Java does indeed pass primitives to methods by value; however, the member variable y was not passed to the method named amethod. Instead, y refers directly to the static member variable. As a result, changes made to the member variable y are seen by any method that accesses y.
The change to x inside of amethod has no impact on the local variable i of the main method since only the value of i is passed to amethod.


Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
Hey bok76er
As an example, try this:

Output should reflect call-by-value behavior.
HTH
Owee Nicolas
Ranch Hand

Joined: Jun 16, 2002
Posts: 49
Now I got it! Thanks Dan and Six_of_Nine!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static variable?
 
Similar Threads
Flow Control
Question from Marcus Green
Marcus Exam1
Variable change
Moke Ex qstn