Is Java Pass by Reference or Pass by Value?

The Java Spec says that everything in Java is pass-by-value. There is no such thing as “pass-by-reference” in Java. The difficult thing can be to understand that Java passes “objects as references” passed by value.

In Java, the argument passing mechanism is often a source of confusion. Java is always “pass-by-value,” but it’s essential to understand how this works.

When you pass a primitive data type (e.g., int, float, char) to a method in Java, you are passing the actual value of the variable. Any changes made to the parameter inside the method do not affect the original variable outside the method.

However, when you pass an object to a method, you are passing the value of the reference to the object, not the actual object. This reference points to the same object in memory. If the object is mutable, changes made to the object’s state inside the method will affect the original object outside the method because both the original reference and the method parameter reference point to the same object.

So, while Java is pass-by-value, it can give the appearance of pass-by-reference when dealing with objects due to the passing of references. This is sometimes referred to as “pass-by-value of the reference.” It’s important to distinguish between the two concepts to understand how Java’s argument passing works.