Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variable?

 
Owee Nicolas
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey bok76er
As an example, try this:

Output should reflect call-by-value behavior.
HTH
 
Owee Nicolas
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I got it! Thanks Dan and Six_of_Nine!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic