Pass by reference or pass by value in java

Pass by reference or pass by value in java

Variables give you the comfort that you do not have to know where your data is stored in your computers memory. You define a variable, make your calculations and pass the variable from one function to another, and your operating system automatically deals with where your data is physically located.
However, sometimes it is very useful to know what happens behind variables. Especially in lower-level languages (for example Assembler, or C in some circumstances), it is sometimes even necessary to know where a value is stored in memory. This article will explain how variables are passed around between functions, and specifically explains how it works in Java. In Java, there is a slight but important difference of passing by value and passing by reference.

This article will use a simplified syntax in the code examples, since the theory of passing values is applicable to most programming languages.

Passing a variable

The term “passing a variable” is used when a function is called with a variable you defined previously. Let’s look at the following example:

The variable myAge is “passed” to the function calculateBirthYear. The function can then use that variable, for example:

There are two possibilities how you could have passed the variable myAge to the function. The terms “pass by value” and “pass by reference” are used to describe how variables are passed on. To make it short: pass by value means the actual value is passed on. Pass by reference means a number (called an address) is passed on which defines where the value is stored.

How memory works

A basic knowledge of how memory works and how your variables are stored in memory will help to better understand this topic. Since an actual physical memory is hard to draw and different memory types look different (a hard disc vs. RAM for example), it is useful to have an abstract and simple way to imagine how memory looks like.

This article uses a simple and easily understandable approach to explain how values are stored in memory. For most uses (especially for programming beginners), it is enough to understand the concepts. However, once one gets experienced in programming, it is very useful to know more about different memory types and memory regions (harddrives, RAM, heap, stack, etc.).

How memory works

To make it simple, lets think of memory as many blocks which are next to each other. Each block has a number (the memory address). If you define a variable in your code, the value of the variable will be stored somewhere in the memory (your operating system will automatically decide where the best storage place is). The illustration on the right shows a part of some memory. The gray numbers on top of each block show the address of the block in memory, the colored numbers at the bottom show values which are stored in memory.

Taking the previous examples again, the variables myAge and month are defined in your code, and they will be stored in memory as shown in the illustration on the right. As example, the value of myAge is stored at the address 106 and the value of month is stored at the address 113.

Pass by value

Passing by value means that the value of the function parameter is copied into another location of your memory, and when accessing or modifying the variable within your function, only the copy is accessed/modified and the original value is left untouched. Passing by value is how your values are passed on most of the time.
The following example shows a variable passed by value:

Читайте также:  Html o 288 вилка

Источник

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.

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.

Источник

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