Java method pass by value

Pass By Value and Pass By Reference in Java

Pass By Value and Pass By Reference in Java

In this article, I am going to discuss Pass By Value and Pass By Reference in Java with Examples. Please read our previous article, where we discussed Java User Input and Output with examples. At the end of this article, you will understand Pass By Value and Pass By Reference in the Java application.

One of the biggest confusion in Java programming language is whether java is Pass by Value or Pass by Reference. Many programming languages allow passing parameters by reference or by value. In Java, we can only pass parameters by value. First of all, we should understand what is meant by pass by value and pass by reference.

Pass By Value in Java:

Actual parameter expressions that are passed to a method are evaluated and value is derived. Then this value is stored in a small portion of the memory and a copy of each value is passed to the parameters of the called method which can then be used. This mechanism is called pass-by-value and Java uses it.

In the call by value, the modification done to the values passed does not reflect in the caller’s scope because when these values are used inside the method, we are actually using the copy of these values, not the original argument values which are unaffected by the operation inside the method.

Example to Understand Pass By Value Mechanism in Java:
package Demo; public class PassByValueDemo < public static void main (String[]args) < String animal1 = "Lion"; String animal2 = "Elephant"; System.out.println ("Before swapping, Animal1 = " + animal1 + " and Animal2 = " + animal2); // Invoke the swap method Swap(animal1, animal2); System.out.println("\n**Now, Before and After swapping values will be same here**:"); System.out.println ("After swapping, Animal1 = " + animal1 +" and Animal2 is " + animal2); >public static void Swap(String animal1, String animal2) < System.out.println ("Before swapping(Inside), Animal1 = " + animal1 +" | Animal2 = " + animal2); // Swap animal1 with animal2 String tempAnimal = animal1; animal1 = animal2; animal2 = tempAnimal; System.out.println ("After swapping(Inside), Animal1 = " + animal1 +" | Animal2 = " + animal2); >>
Output:

Example to Understand Pass By Value Mechanism in Java

Pass By Reference in Java:

Call by reference method copies the address of an argument into the formal parameter. In this method, the address is used to access the actual argument used in the method call. When we pass a variable of class type as an argument to a method, actually, a copy of a reference (address) to an object is passed by value to the method, not a copy of the object itself because Java does not copy the object into the memory.

Читайте также:  Css color invert background

Java uses only call by value while passing reference variables as well. Actually, it copies the reference of the object into the memory and passes the copy to the parameters of the called method. If we change the reference of the object then the original reference does not get changed because this reference is a copy.

Example to Understand Pass By Reference Mechanism in Java:
package Demo; public class PassByreferenceDemo < public static void main (String[]args) < Animal a = new Animal("Lion"); Animal b = new Animal("Elephant"); System.out.println ("Before swapping, a = " + a.a + " and b = " + b.a); // Invoke the swap method swapFunction (a, b); System.out.println("\n**Now, Before and After swapping values will be different here**:"); System.out.println ("After swapping, a = " + a.a + " and b is " + b.a); >public static void swapFunction (Animal a, Animal b) < System.out.println ("Before swapping(Inside), a = " + a.a + " | b = " +b.a); // Swap n1 with n2 Animal c = new Animal (a.a); a.a = b.a; b.a = c.a; System.out.println ("After swapping(Inside), a = " + a.a + " | b = " +b.a); >> class Animal < public String a; public Animal (String a) < this.a = a; >>
Output:

Example to Understand Pass By Reference Mechanism in Java

NOTE: Java passes the arguments both primitives and the copy of object reference by value. Java never passes the object itself.

Thus, by this tutorial, it is clear that Java uses the pass-by-value. There is no pass-by-reference in Java. “The reference is copied as a value” to a new variable and it is given as a formal parameter to the called method.

Just remember that variables are references and their copies are passed to the methods, so java is always pass-by-value.

Difference Between Pass By Value and Pass By Reference

Pass By Value

In the next article, I am going to discuss How to Pass Command Line Arguments in Java with examples. Here, in this article, I try to explain Pass By Value and Pass By Reference in Java with Examples and I hope you like this article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Источник

Java is Pass by Value, Not Pass by Reference

Java is Pass by Value, Not Pass by Reference

Many Java programmers question whether Java is pass by value or pass by reference. This article summarizes why Java is always pass by value.

First, what does pass by value and pass by reference mean?

  • Pass by value: The method parameter values are copied to another variable and then the copied object is passed to the method. The method uses the copy.
  • Pass by reference: An alias or reference to the actual parameter is passed to the method. The method accesses the actual parameter.

Often, the confusion around these terms is a result of the concept of the object reference in Java. Technically, Java is always pass by value, because even though a variable might hold a reference to an object, that object reference is a value that represents the object’s location in memory. Object references are therefore passed by value.

Читайте также:  Javascript объединить элемент массива

Both reference data types and primitive data types are passed by value. Learn more about data types in Java.

In addition to understanding data types, it’s also important to understand memory allocation in Java, because reference data types and primitive data types are stored differently.

Demonstrating pass by value

The following example demonstrates how values are passed in Java.

The example program uses the following class:

public class Balloon  private String color; public Balloon() > public Balloon(String c)  this.color = c; > public String getColor()  return color; > public void setColor(String color)  this.color = color; > > 

The following example program uses a generic method, swap() , that swaps two variables. Another method, changeValue() , attempts to change the variable values.

public class Test  public static void main(String[] args)  Balloon red = new Balloon("Red"); // memory reference = 50 Balloon blue = new Balloon("Blue"); // memory reference = 100 swap(red, blue); System.out.println("After the swap method executes:"); System.out.println("`red` color value = " + red.getColor()); System.out.println("`blue` color value = " + blue.getColor()); changeValue(blue); System.out.println("After the changeValue method executes:"); System.out.println("`blue` color value = " + blue.getColor()); > // Generic swap method public static void swap(Object o1, Object o2) Object temp = o1; o1 = o2; o2 = temp; > private static void changeValue(Balloon balloon)  // balloon = 100 balloon.setColor("Red"); // balloon = 100 balloon = new Balloon("Green"); // balloon = 200 balloon.setColor("Blue"); // balloon = 200 > > 

When you execute the example program, you get the following output:

Output
After the swap method executes: 'red' color value = Red 'blue' color value = Blue After the changeValue method executes: 'blue' color value = Red

The output shows that the swap() method didn’t swap the color values of the original objects. This helps to show that Java is pass by value, since the swap() method only acts upon copies of the original object reference values.

This swap() method test can be used with any programming language to check whether it’s pass by value or pass by reference.

The Example swap() Method Explained

When you use the new operator to create an instance of a class, the object is created and the variable contains the location in memory where the object is saved.

Balloon red = new Balloon("Red"); Balloon blue = new Balloon("Blue"); 

Here’s a step-by-step breakdown of what happens when the swap() method executes:

  • Assume that red is pointing to memory location 50 and blue is pointing to memory location 100, and that these are the memory locations of both Balloon objects.
  • When the class calls the swap() method with the red and blue variables as arguments, two new object variables, o1 and o2 , are created. o1 and o2 also point to memory locations 50 and 100 respectively.
  • The following code snippet explains what happens within the swap() method:
public static void swap(Object o1, Object o2)  // o1 = 50, o2 = 100 Object temp = o1; // assign the object reference value of o1 to temp: temp = 50, o1 = 50, o2 = 100 o1 = o2; // assign the object reference value of o2 to o1: temp = 50, o1 = 100, o2 = 100 o2 = temp; // assign the object reference value of temp to o2: temp = 50, o1 = 100, o2 = 50 > // method terminated 

Since the variables contain the reference to the objects, it’s a common mistake to assume that you’re passing the reference and Java is pass by reference. However, you’re passing a value which is a copy of the reference and therefore it’s pass by value.

The Example changeValue() Method Explained

The next method in the example program changes the color value of the object referenced by the blue variable:

private static void changeValue(Balloon balloon)  // balloon = 100 balloon.setColor("Red"); // balloon = 100 balloon = new Balloon("Green"); // balloon = 200 balloon.setColor("Blue"); // balloon = 200 > 

Here’s a step-by-step breakdown of what happens within the changeValue() method:

  • The class calls the changeValue() method on the blue variable that references memory location 100. The first line creates a reference that also points to memory location 100. The color value of the object at memory location 100 is changed to «Red» .
  • The second line creates a new object (with color value «Green» ). The new object is at memory location 200. Any further methods executed on the balloon variable act upon the object at memory location 200, and don’t affect the object at memory location 100. The new balloon variable overwrites the reference created in line 1 and the balloon reference from line 1 is no longer accessible within this method.
  • The third line changes the color value of the new Balloon object at memory location 200 to «Blue» , but does not affect the original object referenced by blue at memory location 100. This explains why the final line of the example program output prints blue color value = Red , which reflects the change from line 1.

Conclusion

In this article you learned about why Java is pass by value. Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью