In Java, it is possible to declare a parameter of a primitive type (int, double ...) and change its value within the method. When the method is exited, is the value of the variable updated?
Asked
Active
Viewed 7,374 times
1

Steve Chambers
- 37,270
- 24
- 156
- 208

bbariotti
- 41
- 1
- 5
-
Assuming you want `int x = 1; makeItTwo(x); //now x is 2` then it is impossible since Java is always pass by value. Your best chance is `x=makeItTwo(x);` where `makeItTwo` *returns* new value. – Pshemo Oct 02 '15 at 14:16
-
1See this for reference: http://stackoverflow.com/questions/4319537/how-do-i-pass-a-primitive-data-type-by-reference – javatutorial Oct 02 '15 at 14:17
-
You can cheat and make your parameter an `int[]` with length 1. – Andy Turner Oct 02 '15 at 14:18
-
The simple answer to the question is no. A primitive parameter variable can indeed be manipulated within a method but since it is pass-by-value, the changes won't take effect outside the method. See the output of this example code: https://rextester.com/GYTK35410 – Steve Chambers Oct 26 '19 at 16:55
1 Answers
2
This is not simple, due to the way java handles parameters. Primitives (like int
or long
) are handed by value, Objects
by reference. This means only Objects
can be manipulated inside of methods and the changes will be visible outside of the method. If you want to get this behaviour, you'll have to use wrapper-classes:
class Wrapper<class T>{
private T val;
public Wrapper(T v){
val = v;
}
public void setVal(T v){ val = v; }
public T getVal(){ return val; }
}
-
Might be worth noting that primitives can't be used as generic types so even if this approach is taken wrapper types would have to be used. new Wrapper
(1L); – wheeleruniverse Jul 06 '18 at 19:01