How Java "pointers" work?

java, pointers

Solution

In Java, instead of pointers you have references to objects. You cannot pass a primitive type by reference, but you can wrap a primitive type inside an object and then pass a reference to that object.

Java provides the type `Integer` which wraps `int`, however this type is immutable so you cannot change its value after construction. You could however use `MutableInt` from Apache Commons:

void change(MutableInt x) {
    x.increment();
}

The change to x will be visible to the caller.

Specifically, I want to point to a Vector object

When you write `Vector v = ...;` you are assigning a reference to a vector to the variable `v`. A reference in Java is very similar to a pointer. References are in fact implemented internally using pointers.

Java uses pass by value. When you pass a vector to a method, you are actually copying a reference to that vector. It does not clone the vector itself. So passing a reference in Java is very similar to passing a pointer in C++.

Problem

Lets say this is the C++ code: ``` void change(int& x){ x++; } ``` or ``` void change2(int* a){ *a++; } ``` Both will change the global x, right? So how can I do something like that in java? Specifically, I want to point to a Vector object But since Java has no pointers, I'm not sure what to do. From searching the internet I saw people saying that Java does that in some other way, but I haven't found any real example. Thanks for help!

Original source

Related problems