How to change the value of the external variable, which is input to the method?

I know in Java to change the external variable you need to pass the input parameter value by reference. Well, with objects it seems to work (although not always). But how to change the value of the external variable if it is primitive type? I tried to use the wrapper Integer - to no avail.
public class Application
{
 public static void main(String args[]) {
 Integer x = new Integer(5);
System.out.println(x);
change(x);
System.out.println(x);
}

 public static void change(Integer x) {
x++;
}
}


Outputs:
5
5
How to make so that in the second case, it put 6 instead of 5?
July 2nd 19 at 17:42
2 answers
July 2nd 19 at 17:44
Solution
No, Java passes parameters only by value. Integer class is immutable, i.e. its objects cannot change their state.
There are two ways to overcome this limitation.
1. Use an array
public class Application {
 public static void main(String args[]) {
 int[] x = new int[]{5};
System.out.println(x[0]);
change(x);
System.out.println(x[0]);
}

 public static void change(int[] x) {
x[0]++;
}
}
2. Use own wrapper
class MyInt {
 private int value;
 public MyInt(int initializer) { value = initializer; }
 public int getValue() { return value; }
 public void addAssign(int delta) { value += delta; }
 public String toString() { return Integer.toString(value); }
}

public class Application {
 public static void main(String args[]) {
 MyInt x = new MyInt(5);
System.out.println(x);
change(x);
System.out.println(x);
}

 public static void change(MyInt x) {
x.addAssign(1);
}
}
Thank you for your answer! - mathias.Mayert commented on July 2nd 19 at 17:47
July 2nd 19 at 17:46
In Java, primitive types (int, long, char,...) and objects immutable classes (Integer, Long, String...) and you have to change will not work.

will work here

public static void main(String args[]) {
 Integer x = new Integer(5);
System.out.println(x);
 x = change(x);
System.out.println(x);
 }


public static void change(Integer x) {
 x ++;
 return x;
 }
But it's impossible to cause a return if the function has type void - mathias.Mayert commented on July 2nd 19 at 17:49
: It's a typo. Integer instead of void - mathias.Mayert commented on July 2nd 19 at 17:52

Find more questions by tags Java