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.