How to update a variable in one class from another class

I understand that this is probably really the main question, but I cannot understand.

Say I have this main class

public class Main{ public static void main(String[] args){ int a = 0; AddSomething.addOne(a); System.out.println("Value of a is: "+String.valueOf(a)); } } 

Here is the AddSomething class and addOne() method

 public class AddSomething{ public static void addOne(int a){ a++; } } 

addOne method addOne not add anything

 System.out.println("Value of a is: "+String.valueOf(a)); // Prints 0 not 1 

How can I make the Add update variable of class a in class Main ?

+5
source share
3 answers

addOne gets a copy of a , so it cannot change the variable a your main method.

The only way to change this variable is to return the value from the method and assign it back to a :

 a = Add.addOne(a); ... public int addOne(int a){ return ++a; } 
+5
source

This means that primitive types in java pass to methods by value. Only one way to do what you need is to reassign the variable, for example:

 public class Main{ public static void main(String[] args){ int a = 0; a = Add.addOne(a); System.out.println("Value of a is: "+String.valueOf(a)); } } 

and

 public class AddSomething{ public static int addOne(int a){ return a++; } } 
+2
source

I know Eran’s answer is what you need. But just to show a different way by posting this answer.

 public class Main { static int a = 0; public static void main(String[] args) { AddSomething.addOne(); System.out.println("Value of a is: "+a); } } 

And in the AddSomething class ..

 public class AddSomething { public static void addOne(){ Main.a++ }; } 

AddSomething should be in the same package as the Main class, since int a has a default access modifier.

0
source

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


All Articles