Java always passes by value and global variables do not exist, as in the sense of C ++. Therefore, if you want to do the same as in C ++, you need to return a new value.
Thusly:
public int change(int x) { return ++x;
To check this:
int x = 2; change(x); System.out.println(x); // returns 2 x = change(x); System.out.println(x); // returns 3
Thus, it does not make sense to allow the method to be called change
; it is more intelligent along the lines of calculateThisInt
.
Java does pass objects by value. But since Mark Byers mentions that the Integer class is immutable, and you can use the MutableInt
from the Apache Commons library. To describe how this works, you can implement it yourself for your example:
public class MyInt() { public int i; public void setInt(int i) { this.i = i; } public int getInt() { return this.i; } public int increment() { this.i++; } }
You need to change your change
function so that the MyInt
object is specified as an MyInt
:
public void change(MyInt i) { i.increment(); }
Using:
MyInt x = new MyInt(); x.setInt(2); change(x); System.out.println(x.getInt);
In your case, you want to change the Vector object ...
public void changeVector(Vector v) {
Hope this all makes sense.
source share