N
N
NameOf Var2016-11-10 22:23:18
Java
NameOf Var, 2016-11-10 22:23:18

How to change the value of an external variable that is supplied as input to a method?

I know that in Java, to change an external variable, you need to pass the value of the parameter by reference to the input. Well, with objects it seems to work (although not always). But how to change the value of an external variable if it has a primitive type? I've tried using the Integer wrapper - to no avail.

public class Application
{
    public static void main(String args[]) {
        Integer x = new Integer(5);
        System.out.println(x);
        change(x);
        System.out.println(x);
    }

    public static void change(Integer x) {
        x++;
    }
}

Outputs:
5
5
How can I make it output 6 instead of 5 in the second case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evhen, 2016-11-10
@EugeneP2

In Java, primitive types (int, long, char...) and objects of immutable classes (Integer, Long, String...) cannot be changed in this way.
it will work like this

public static void main(String args[]) {
        Integer x = new Integer(5);
        System.out.println(x);
        x = change(x);
        System.out.println(x);
    }

public static void change(Integer x) {
        x ++;
        return x;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question