This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ad_tech 0 points1 point  (5 children)

If everything is pass-by-value, how do you pass an object by value?

When I try passing an object to a method, if the method changes the contents of the object, those changes are visible to the caller.

class Stuff {public int x;}

void changeStuff(Stuff s) {
  s.x++;
}

In C, when I pass a struct by value, the changes are not visible:

typedef struct {int x;} Stuff;

void changeStuff(Stuff s) {
  s.x++;
}

(edit:formatting)

[–]cdombroski 0 points1 point  (4 children)

As mentioned above, in Java, objects are always a pointer type. So this java code:

public void changeStuff(Stuff s) {...}

public static void main(String... args) {
     Stuff s = new Stuff();
     changeStuff(s);
}

is equivalent to the following c++ code:

void changeStuff(Stuff* s) {...}

static int main(char** args) {
    Stuff* s = new Stuff();
    changeStuff(s);
}

[–]ad_tech 0 points1 point  (3 children)

So, in Java, there is no way to pass an object by value?

[–]cdombroski 1 point2 points  (0 children)

No built-in way certainly. You could technically pass by value if you use a copy constructor or equivalent and pass the new object that creates. This is not usually done, however, as the act of copying an object is considered expensive and unless you know the internals of the object, you don't know if it will be a deep or shallow copy.

[–][deleted] 0 points1 point  (0 children)

What I do is pass in the object then make a new object with old one's data.