Thursday, June 29, 2017

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

Java is strictly pass-by-value. 

Then the next question is how it is pass-by-value ?
   
 Here the explanation from SCJP.


"Java is actually pass-by-value for all variables running within a single VM. Pass-by-value means pass-by-variable-value. And that means, pass-by-copy-ofthe-variable,which means pass-by-copy-of-the-bits-in-the-variable"


Here we have example for passing variable and passing reference.


package com.test.java;

/**
 * @author palrajb
 *
 */
public class Test {

    private String name;
    private int age;
    private int marks;

    public Test() {
    }

    public Test(String name, int age, int marks) {
        this.name = name;
        this.age = age;
        this.marks = marks;
    }

    public void setMarks(int marks) {
        this.marks = marks;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        Test l_objTest = new Test("A", 1, 12);
        int l_iIntValue = 1;
        System.out.println("Mark Before invoke : " + l_objTest.marks + " IntValue :" + l_iIntValue);
      
  //Output:Mark Before invoke : 12 IntValue :1
        doTest(l_objTest, l_iIntValue);
//Here we are passing reference and variable as parameter.
        System.out.println("Mark After invoke : " + l_objTest.marks    + " IntValue :" + l_iIntValue);
       
//Output:Mark After invoke : 14 IntValue :1
    }





Here we got the copy of calling method reference variable. We change the p_iIntValue +1, but the called method can't change the caller's variable.So when we print this from main method its still 1. For p_objTest.setMarks(14) will change the caller l_objTest object marks to 14,because the called method can change the object the variable referred.

     static void doTest(Test p_objTest, int p_iIntValue)
    {
        p_iIntValue = p_iIntValue + 1;
//Using same reference but in different address.So increment happens only on newly created address not on old one.The called method can't change the caller's variable
        p_objTest.setMarks(14);
//called method can change the object the variable referred.
        p_objTest = new Test("B", 2, 13);
//we using same reference but in different address. So the caller reference not going to change anyway.
        p_objTest.setMarks(15);//
change the mark value in newly referenced object.
    }

}

No comments:

Post a Comment