Does Java change the value of a variable by a method?

Hello, I was wondering how I can send a variable as a parameter to a method and change it with a method. for instance

public class Main { public static void main(String[] args) { int i = 2; doThis(i); System.out.println(i); } public static void doThis(int i) { i = 3; } } 

I would like it to print 3 instead of 2. Thank you.

+6
source share
5 answers

Java cannot do this. However, you can return the value from the method ...

 public static int doThis(int i) { return 3; } 

And reassign it ...

 int i = 2; i = doThis(i); 
+4
source

I would like it to print 3 instead of 2

Change method to return value

 int i = 2; i = doThis(i); public static int doThis(int i) { i = 3; return i; } 

it copies the primitive value from the caller to the argument

+3
source

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.

+2
source

Java is passed by value for primitive data types or objects.
Reference data type parameters, such as objects, are also passed to methods by value.

+1
source

java is passing values. therefore it will not change the way you wanted. Read more here

however you follow these steps to resolve this issue

 i = doThis(i); public static int doThis(int i) { i = 3; return i; } 
0
source

Source: https://habr.com/ru/post/944801/


All Articles