Forums Register Login

static variable?

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Hey bok76er
As an example, try this:

Output should reflect call-by-value behavior.
HTH
+Pie Number of slices to send: Send
Now I got it! Thanks Dan and Six_of_Nine!
This guy is skipping without a rope. At least, that's what this tiny ad said:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 780 times.
Similar Threads
Flow Control
Question from Marcus Green
Marcus Exam1
Variable change
Moke Ex qstn
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 23:00:42.