David Veloso David Veloso - 5 months ago 9x
Java Question

How to manipulate a Variable from another class using a method call from that other class?

public class Main{
Class class = new Class();

public class Class{
Int variableFromAnotherClass=0;

method(int var){



Im dealing with a situation similar to the one above except with more variables in my version of "Class". My issue is that the method within "Class" does nothing to the variable being passed through. Why does this happen? Is it because the variable being passed through already belongs to the class? Any suggestions on What should I do to solve this problem?


The problem you are facing has to do with Java passing variables by reference, instead of by value. when variableFromAnotherClass is passed into class.method(int var), the int var variable is created from a copy of variableFromAnotherClass. so when var=1 is called, it updates the copy of variableFromAnotherClass, and not variableFromAnotherClass itself.

If you want to be able to change variableFromAnotherClass from Main, you can write class.variableFromAnotherClass=1; instead of calling method.

Another, more professional way of updating variables is using getters and setters:

public class Class {

    int variableFromAnotherClass;

    public void getVar() {
        return variableFromAnotherClass;

    public int setVar(int var) {
        this.variableFromAnotherClass = var;