Java passes everything by value, so if you use the assignment operator in a class method, you are not going to modify the original object.
For instance:
public class Main { public static void main(String[] args) { Integer i = new Integer(2); setToThree(i); System.out.println(i); } public static void setToThree(Integer i) { i = new Integer(3); } }
going to print 2.
Having said that, if the object you pass in the link is mutable, you can make changes to it the way you think.
For instance:
public class Main { public static void main(String[] args) { MyMutableInt i = new MyMutableInt(2); setToThree(i); System.out.println(i); } public static void setToThree(MyMutableInt i) { i.set(3); } }
This will print 3 (assuming MyMutableInt has the correct toString () method).
Of course, Java integers are immutable and therefore cannot be changed this way. So, you have 2 options:
Note: this does not work with primitives of any type. To do this, you will have to go back on your return. If you have multiple values ββfor mutation, you will have to wrap them in an object to return them, so you can also use this method.
source share