DEV Community

Cover image for Is Java "pass-by-reference" or "pass-by-value" ?
Rakesh KR
Rakesh KR

Posted on

2

Is Java "pass-by-reference" or "pass-by-value" ?

Java is a "pass-by-value" language, which means that when an argument is passed to a method, the value of the argument is copied and passed to the method, rather than a reference to the original object. This means that any changes made to the argument within the method have no effect on the original object outside of the method.

In contrast, a "pass-by-reference" language would pass a reference to the original object, rather than a copy of the value, so any changes made to the object within the method would be reflected in the original object outside of the method.

The "pass-by-value" behavior of Java can be counterintuitive at times, especially for programmers who are accustomed to languages that use "pass-by-reference." However, it is a fundamental aspect of the language and is important to understand in order to write correct and effective Java code.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (2)

Collapse
 
prsaya profile image
Prasad Saya • Edited

Java is a "pass-by-value" language, which means that when an argument is passed to a method, the value of the argument is copied and passed to the method, rather than a reference to the original object. This means that any changes made to the argument within the method have no effect on the original object outside of the method.

Yes, Java is "pass-by-value" language.

But the value of the argument can be a reference to an object (the argument can be a variable defined for a primitive or an object). And, the argument can be used to modify the original referenced object.

Collapse
 
prsaya profile image
Prasad Saya

For example:

class X {
    private String s;
    public X(String s) {
        this.s = s;
    }
    String getX() {
        return s;
    }
    void setX(String s) {
        this.s = s;
    }
    public String toString() { 
        return "Value of x: " + s;
    }
}
public class TestJava {
    public static void main(String [] args) {
        X x1 = new X("one");
        System.out.println(x1);    // "one"
        method(x1);
        System.out.println(x1);    // "ten"
    }

    private static void method(X x) {
        x.setX("ten");
    }
Enter fullscreen mode Exit fullscreen mode

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs