How do I change a variable from a different class in Java?
I'm trying to change a variable from another class, and use it back in the first class.
I make a variable in class First, and give it a value of 1. Then I try to change the value of the same variable to 2 in class Second, but it changes back to 1 when I use it in class First.
I'm new to Java and don't know very much yet, so if you could try and keep the answers simple, that would be great :)
Class First:
public class First {
public static void main(String args[]){
int var = 1; //Variable i'm trying to change from class "Second"
Second Second = new Second();
System.out.println(var); //Prints out 1
Second.test(var);
System.out.println(var); // Prints out 1 again, even though I changed it
}
}
Class Second:
public class Second {
void test(int var){
/*
*
* I try to change var to 2, and it works in this class
* but when it doesn't change in the class "First"
*
*/
var = 2;
System.out.println(var); //Prints out 2
}
}
What the output looks like:
1
2
1
What i'm trying to get:
1
2
2
Ive tried to find answers to this, but all of the answers that I could find didnt make any sense to me, as im very new to Java and programming.
Java is pass-by-value, it means that you are passign a copy of
var
. What you can do is to make methodtest()
to return aint
and then assign its result (the value the method
test()
returns) tovar
:Note:
In
you shouldn't use the name of a class as a name of a variable. Do this sintead:
The problem is
It's not a bug. It's just not doing what you think its doing.
A primitive (an
int
is called a primitive...it's not an object) passed to a function may be changed in that function, but in a copy. As soon as the function is done, the original value is the same, because it was never altered to begin with.What you want is
And then instead of
use
There is actually no point in the parameter at all. It is equivalent to
I hope this helps. Good luck, welcome to Java, and welcome to stackoverflow!
The
var
parameter intest
method of classsecond
is a copy, not a reference or pointer. So you can not change the value ofvar
in classFirst
.To achieve your goal, you could declare
var
as a global variable, like this:Well you've changed it in second class, but you did not return it back to the first class. First class can't possibly know you've changed it in the other class if you don't return it. You can do it this way, hope it helps.
First class:
Second class: