Answer the question
In order to leave comments, you need to log in
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++;
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question