Difference between object oriented object based programming language

What is meant by pass by reference and pass by value in Java ?

Answer : In java there is nothing call pass by reference, it’s always pass-by-value. Here difficult thing could be to understand is that that when we see java passes objects as references but indeed those references are passed by value and our confusion starts. Let’s see example below how java is pass-by-value:

public class PassByValueTest {

    public static void main(String[] args) {

	PassByValueTest pValueTest = new PassByValueTest();
	// person variable created initially its value assign is null
	Person person;
	// Person object created in memory heap and
	// variable person got the reference of it which is 
	// on the stack actually variable person is holding 
	// the address of the Person object
	// for example : address of person is 308abc4
	person = new Person();
	// here we are passing address of person 308abc4
	// means its pass by value
	pValueTest.testPerson(person);

    }

    // Very important below : variable samePerson created
    // person reference will be copied to samePerson
    // no new instatnce will be created 
    // now both person and samePerson will point to same address 
    // on the heap that is : 308abc4
    private void testPerson(Person samePerson) {

	samePerson.setName("Java HOnk");
	System.out.println("Name: "+samePerson.getName());

    }

}

class Person {
    String name;

    public String getName() {
	return name;
    }

    public void setName(String name) {
	this.name = name;
    }

}

 

Output:

What is meant by pass by reference and pass by value in Java

Leave a Reply

Your email address will not be published. Required fields are marked *