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;
}
Thats becouse primitive types in java pass to methods by value. Only one way to do what you want is reassign variable, like :
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++;
}
}
I know, Eran's answer is what you all need. But just to show another way, 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 AddSomething
class..
public class AddSomething
{
public static void addOne(){ Main.a++ };
}
AddSomething
must be in same package as Main
class, as int a
has default access modifier.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.