How to change a variable from another class in Java?

How to change a variable from another class in Java?

I am trying to change a variable from another class and use it in the first class.

I make a variable in the First class and give it a value of 1. Then I try to change the value of the same variable to 2 in the Second class, but it returns to 1 when I use it in the First class.

I am new to Java and still do not know very much, so if you could try to keep simple answers, that would be great :)


First grade:

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

}
}


Second class:
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 am I trying to get:

1
2
2


Ive tried to find the answers to this, but all the answers that I could find made no sense to me, since they are very new to Java and programming.
+3
4

Second.test(var); 

. , , .

(an int ... ), , , . , , .

int test(int var){
   var = 2;
   System.out.println(var); //Prints out 2
   return  var;
}

Second.test(var); 

var = Second.test(var);

.

var = Second.test();

...

int test(){
   int var = 2;
   System.out.println(var); //Prints out 2
   return  var;
}

, . , Java stackoverflow!

+3

Java - pass-by-value, , var. , test() int

int test(int var){
    ...
    var = 2;
    System.out.println(var); //Prints out 2
    return var;
}  

(, test()), var:

var = second.test(var);
System.out.println(var); //Prints out 2

:

Second Second = new Second();

. sintead:

Second Second = new Second();
+2

var test second , . , var First.

, var , :

public class First {

    public int var = 1; 

    public static void main(String args[]){

    Second Second = new Second();

    System.out.println(var);

    Second.test(); 

    System.out.println(var);

}
}

public class Second {

    void test(){
    /*
     * 
     * I try to change var to 2, and it works in this class
     * but when it doesn't change in the class "First"
     * 
     */
    First.var = 2;
    }
}
0

, , . , , . , , .

First grade:

public class First {

    public static void main(String args[]){


        int var = 1;

        Second Second = new Second();

        System.out.println(var); //Prints out 1

        var = Second.test(var); 

        System.out.println(var); //Prints out 2

    }
}

Second class:

public class Second {

    int test(int var){

        var = 2;

        System.out.println(var); //Prints out 2

        return var;

    }
}
0
source

All Articles