2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

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

can anybody explain Java pass-by-reference or pass-by-value.
userimage
Java is always pass-by-value. For example

public static void main( String[] args ){
    Test aTest = new Test("TestCheckData");
    foo(aTest);

    if (aTest.getName().equals("TestCheckData")) {
        System.out.println( "Java passes by value." );

    } else if (aTest.getName().equals("ReturnTestCheckData")) {
        System.out.println( "Java passes by reference." );
    }
}

public static void foo(Test d) {
    d.getName().equals("TestCheckData"); // true

    d = new Test("ReturnTestCheckData");
    d.getName().equals("ReturnTestCheckData"); // true
}


In this example aTest.getName() will still return "TestCheckData".
The value aTest within main is not overwritten in the function foo with the Test "ReturnTestCheckData" as the object reference is passed by value.
If it were passed by reference, then the aTest.getName() in main would return "ReturnTestCheckData" after the call to foo.

Likewise:

Test aTest = new Test("TestCheckData");
foo(aTest);
aTest.getName().equals("ReturnTestCheckData"); // true

public void foo(Test d) {
    d.getName().equals("TestCheckData"); // true
    d.setName("ReturnTestCheckData");
}
Answer is