File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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();
public void amethod(int x){
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
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="" 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.
Owee Nicolas
Ranch Hand

Joined: Jun 16, 2002
Posts: 49
Now I got it! Thanks Dan and Six_of_Nine!
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: static variable?