How do I change a variable from a different class in Java?

class, java, variables

Solution

The problem is

Second.test(var); 

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

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

And then instead of

Second.test(var); 

use

var = Second.test(var);

There is actually no point in the parameter at all. It is equivalent to

var = Second.test();

...

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

I hope this helps. Good luck, welcome to Java, and welcome to stackoverflow!

Problem

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.

Original source

Related problems