package myintergertest;
/**
*
* @author Engineering
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void
You are looking for something similar to C++'s reference or to C#' out parameter. Java (and many other languages) does not support this.
This type of behavior is typically achieved by changing the method from void to (in this case) int: public static int increment(int n) { return ++n; }
If the method is already returning something then you can create a new class that has two fields (can even be public): the original return value and the new value of n.
Alternatively, you can also wrap the integer inside a generic Cell class. You only need to write this Cell class once:
public class Cell {
public Cell(T t) { value = t; }
public void set(T t) { value = t; }
public T get() { return value; }
}
You can then use it in all situations where you want to a method to change a primitive:
public static void increment(Cell n) {
n.set(n.get()++);
}
Cell n = new Cell(0);
increment(n);
increment(n);
increment(n);
System.out.println(n.get()); // Output: 3