Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a variable in one class from another class

Tags:

java

I realize this is probably a really basic question, but I can't figure it out.

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 AddSomething class and addOne() method

public class AddSomething{

    public static void addOne(int a){

        a++;

    }
}

The addOne method is not adding anything

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

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

like image 506
the_prole Avatar asked Nov 27 '15 07:11

the_prole


1 Answers

addOne receives a copy of a, so it can't change the a variable of your main method.

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

a = Add.addOne(a);

...

public int addOne(int a){
    return ++a;
}
like image 122
Eran Avatar answered Oct 13 '22 01:10

Eran