Junior — Middle
Is it possible to change the value of a primitive type passed inside the calling function?
sobes.tech AI
Answer from AI
In Java, primitive types are passed to methods by value, meaning the actual value is copied, not the reference to it. Therefore, it is not possible to change the value of a primitive inside a called function in a way that this change reflects on the calling variable.
Example:
public void changeValue(int x) {
x = 10; // change to local copy
}
int a = 5;
changeValue(a);
System.out.println(a); // will print 5, not 10
If you need to change the value and get the result, you can return the new value from the method or use wrappers (like AtomicInteger) or arrays, where you can modify the contents of the object.