Junior — Middle
How can an argument be passed by reference so that changes inside the function reflect on the original variable?
sobes.tech AI
Answer from AI
In Java, all arguments are passed by value, including references to objects. This means that you cannot directly pass a primitive type by reference to modify its value inside a function. However, if you pass an object, you can change its internal state, and these changes will be visible outside the function.
If you need to modify a primitive value, you can use wrappers, such as AtomicInteger, or create your own wrapper class.
Example of modifying an object inside a method:
class Counter {
public int count;
public Counter(int count) {
this.count = count;
}
}
public class Main {
public static void increment(Counter c) {
c.count++;
}
public static void main(String[] args) {
Counter counter = new Counter(0);
increment(counter);
System.out.println(counter.count); // Will output 1
}
}
Thus, changes inside the function affect the original object, but you cannot change the reference itself to point to another object.