+7 votes
2 views
in Java by (1.4k points)

Earlier I used to think that Java is Pass by Reference, but During my latest research iI came to the conclusion that it is Pass by value. I am confused right now on which one is true.

So, if you could explain Is Java pass by value or reference? and why is it  

2 Answers

+13 votes
by (13.2k points)
edited by

Java is pass by value only. There is a misconception that for passing objects we use pass by reference in Java, but it is nothing but only a myth.

Now what is pass by value & pass by reference?

As you might be knowing, programming works by creating new address blocks for parameters and storing them at different locations, when we have to use that stored variable later we may pass that variable without defining it again, so for this purpose we may use pass by value and pass by reference.

In pass by value, the ‘passed’ variable gets copied to a different location and therefore if we make changes in it, those changes get modified in the newly copied variable only and not in the older one that was stored previously. So we can access that old variable by calling the older address and the new (or modified) parameter at the new address. While, in case of pass by reference, the original variable gets replaced after getting modified and the older value is not accessible as it gets overwritten by the new one.

Hope this helps you.

0 votes
by (40.4k points)
edited by

In Java, its always “pass by value” not “pass by reference”.  We’ll understand this via an example.

Let’s understand what is “pass-by-value” and “pass-by-reference”.

Want to learn Java from scratch! Here's the right video for you on Java:

Pass by Value: In this function parameter values are copied to another variable and then copied object is passed. Therefore, it’s called pass by value. 

Pass by Reference: In this actual parameter’s reference is passed to the method so it’s known as pass by reference.

Example:

public class Car {

Private String model;

public Car () {} //default constructor

Public Car (String m) {

this.model=m;

}      // parameterize constructor

public String getModel(){

return model;

}

public void setModel()

{

this.model=model;

}

}

public static void main (String[] args)

{

Car c1= new car(“Skoda”);

Car c2=c1;

//Now pass this object to foo method

foo(c1);

//c1 variable is still pointing to the “Skoda” Car

c1.getModel().equals(“Skoda”); //true

c1.getModel().equals(“Honda”); //false

c1=c2;

}

Public static void foo (Car c)

{

c.getName().equals(“Skoda”); //true

c=new Car(“Honda”);

c.getName().equals(“Honda”); }

In the above example, within main function will return “Skoda” . The value of c1 is not changed with the car’s model as “Honda” as Java is strictly Pass by Value.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...