-3

I have been learning C and now I want to compare it to Java

If I do this

void changeVal(int x){
    ++x;
}

in C that only changes the value of x stored in the stack frame. It changes the local copy of xonly.

So what does

int x = 5;
public void changeValJava(int x){
    ++x; 
}

do in Java?

Does it change the value of x or the value of an instance of x?

In C we would need to use a pointer to x to change the actual value, but what about in Java?

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
Amad27
  • 151
  • 1
  • 1
  • 8

4 Answers4

4

In Java, ++x; changes the argument x. The field x is shadowed. To modify the field, you would need something like

++this.x;

Note that the field x and the variable x are unrelated (apart from having the same name).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Here, It changes the input parameter value x from 5 to 10.

line 1 int x = 5;
line 2 public void changeValJava(int x){
line 3    ++x; 
       }

int is a primitive variable and at line 2 - its better to refer as Initialization than referring as instance. At line 2, x variable is initialised to 5, and at line 3 x variable is reinitialised to 6 - as in x = x + 1;

The variable x at line 1 can be referred or updated using instance variable of the class or using this keyword.

Srikanth Balaji
  • 2,638
  • 4
  • 18
  • 31
0

Like in C, Java also stores the local value of x. So when you take ++x, it increments that value of x that is passed to the function changeValJava. In Java, the 'actual' x is the instance variable whereas the x in changeValJava is just a local variable. These two xs are different.

Java doesn't support pointers, to change the 'actual' value, you need to associate the object containing x. Here that object is the self-object, referred by this keyword. So, you can write

++this.x
Amita
  • 944
  • 1
  • 8
  • 20
0

In java, there is a separate stack for each thread. All the method and its variables are stored in this stack.

Your questions seems to be little bit confusing to me.

If you are asking about pass by value and pass by reference (pointers in C).

Its very clear that Java supports only pass by value.

If you are asking, how java stores method variables and their objects, then "In java there is a separate stack for each thread, where it stores all the method, method variables and objects".

Anil Agrawal
  • 2,748
  • 1
  • 24
  • 31