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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With