How to pass values by reference in Java?

Asked

Viewed 944 times

4

Gentlemen, one of the methods of the class Array has the method sort.

The method sort works like this:

Arrays.sort(vetor);

The vector itself is changed, I searched in many places and from what I understand this is passage from value by reference.

In C we use pointers, but what about in Java? How it works?

1 answer

5


In Java, whenever you use a parameter of an object type (i.e., it is not primitive), what is passed is a reference to the object (i.e., it is not a copy).

With primitive types, the passage occurs by value (i.e., the parameter is copied).

Making an analogy with C, it’s as if any variable that is not of a primitive type is actually a pointer (and that’s exactly how it’s implemented by JVM).

  • But it would be possible to pass a primitive type value by reference in Java?

  • 2

    @cat Just you envelop him in a class. public class MeuInt { public int valor; } and then public void meuMetodo(MeuInt x) { x.valor = 5; } - However, you will hardly do something like this in a real code.

  • I think it makes sense for primitive type values not to be passed by reference. Since you could simply return a new value, however, if it is a class with a lot of data, returning new values would be more expensive for the machine.

  • A direct answer. Thank you, that explains a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.