Tutorial Playlist
One of the center ideas of writing computer programs is passing values to strategies and capabilities. Passing values in Java might be finished in one of two ways: by value or by reference. It's fundamental to grasp the distinctions between these two methods to compose successful and blunder-free code. In this post, we will examine pass by value and call by reference in Java, using examples, screenshots, and graphics to aid comprehension.
Pass by value and call by reference are different strategies for passing arguments to methods. A reference to the original variable is supplied during a call by reference, but during a pass by value, a copy of the value is sent to the function. By default, Java utilizes a pass by value, which implies that the method receives a copy of the data.
We should begin by looking at an illustration of pass by value in Java. Consider about the accompanying code scrap:
java
public class PassByValueExample {Â
  public static void main(String[] args) {Â
    int number = 10;Â
    System.out.println("Before calling the method: " number);Â
    increment(number);Â
    System.out.println("After calling the method: " number);Â
  }Â
  Â
  public static void increment(int num) {Â
    num ;Â
    System.out.println("Inside the method: " num);Â
  }Â
} Â
In the above example, the increment method adds one to the value of the integer input num. The output is as follows when the increment method is used with the number variable as an argument:
SQL
Before calling method: 10Â
Inside the method: 11Â
After calling method: 10 Â
We can observe from the result that the method call has not affected the number's value. This exemplifies Java's usage of pass by value, which involves passing the method a copy of the value.
Pass by value alludes to the most common way of reordering the contention's worth to the technique. The technique's underlying variable is unaffected by any progressions made to the contention. Let's examine another example to illustrate pass by value in Java:
java
public class PassByValueExample {Â
  public static void main(String[] args) {Â
    int number = 10;Â
    System.out.println("Before calling the method: " number);Â
    changeValue(number);Â
    System.out.println("After calling the method: " number);Â
  }Â
  Â
  public static void changeValue(int num) {Â
    num = 20;Â
    System.out.println("Inside the method: " num);Â
  }Â
} Â
In this outline, the function changeValue acknowledges the number boundary num and gives it another worth. The result of running the code is as per the following:
SQL
Before calling method: 10Â
Inside the method: 20Â
After calling method: 10 Â
Once again, we can see that the original variable number remains unchanged after the method call. This behavior confirms that Java uses pass by value.
As opposed to a few other programming languages, for example, C, Java doesn't unequivocally give pass by references. At the point when a technique utilizes pass by reference, it gets a reference to the first factor, empowering changes performed inside the strategy to affect the first factor. Java, however, treats references another way.
Java manages references through pass by value despite the fact that it doesn't unequivocally permit pass by reference. This infers that an item reference is duplicated and provided as a parameter at whatever point an object reference is passed to a technique. Thus, changes made to the reference inside a technique affect the first reference.
Think about the following instance:
java
public class PassByValueExample {Â
  public static void main(String[] args) {Â
    StringBuilder sb = new StringBuilder("Hello");Â
    System.out.println("Before calling the method: " sb);Â
    appendText(sb);Â
    System.out.println("After calling the method: " sb);Â
  }Â
  Â
  public static void appendText(StringBuilder text) {Â
    text.append(" World!");Â
    System.out.println("Inside the method: " text);Â
  }Â
} Â
The function appendText in this example appends " World!" to a StringBuilder object that it receives as an argument. Running this code produces the following results:
SQL
Before calling the method: HelloÂ
Inside the method: Hello World!Â
After calling the method: Hello World! Â
The result demonstrates how the appendText method's modifications to the text reference have an impact on the original object. It's crucial to remember that the reference was supplied by value, though.
Pass by value is simple to use when working with primitive data types in Java, such as int, float, or boolean. The primitive variable's value is copied and sent to the method. The method's initial variable is unaffected by any changes made to the argument.
Let's consider an example with primitive data types:
java
public class PassByValueExample {Â
  public static void main(String[] args) {Â
    int num = 5;Â
    System.out.println("Before calling the method: " num);Â
    multiplyByTwo(num);Â
    System.out.println("After calling the method: " num);Â
  }Â
  Â
  public static void multiplyByTwo(int number) {Â
    number *= 2;Â
    System.out.println("Inside the method: " number);Â
  }Â
} Â
The output of running this code is as follows:
SQL
Before calling method: 5Â
Inside the method: 10Â
After calling method: 5 Â
As expected, the original variable num remains unchanged after the method call.
To further illustrate pass by value with primitive types, let's examine another example:
java
public class PassByValueExample {Â
  public static void main(String[] args) {Â
    int a = 10;Â
    int b = 20;Â
    System.out.println("Before calling the method: a = " a ", b = " b);Â
    swap(a, b);Â
    System.out.println("After calling the method: a = " a ", b = " b);Â
  }Â
  Â
  public static void swap(int x, int y) {Â
    int temp = x;Â
    x = y;Â
    y = temp;Â
    System.out.println("Inside the method: x = " x ", y = " y);Â
  }Â
} Â
The output of running this code is as follows:
less
Before calling the method: a = 10, b = 20Â
Inside the method: x = 20, y = 10Â
After calling the method: a = 10, b = 20 Â
Again, we can observe that the original variables a and b remain unchanged after the method call. This demonstrates that Java uses pass by value even with primitive types.
When it comes to objects in Java, pass by value works slightly differently. A duplicate of the item reference is provided to the technique instead of the total item itself. This suggests that changes to the item's properties finished inside the technique will affect the first article.
java
public class PassByValueExample {Â
  public static void main(String[] args) {Â
    Person person = new Person("John");Â
    System.out.println("Before calling the method: " person.getName());Â
    changeName(person);Â
    System.out.println("After calling the method: " person.getName());Â
  }Â
  Â
  public static void changeName(Person p) {Â
    p.setName("Jane");Â
    System.out.println("Inside the method: " p.getName());Â
  }Â
}Â
Â
class Person {Â
  private String name;Â
  Â
  public Person(String name) {Â
    this.name = name;Â
  }Â
  Â
  public String getName() {Â
    return name;Â
  }Â
  Â
  public void setName(String name) {Â
    this.name = name;Â
  }Â
} Â
In this illustration, a Person class with a name attribute is present. A Person object is sent to the changeName function, which changes the name to "Jane." Running this code produces the following results:
SQL
Before calling the method: JohnÂ
Inside the method: JaneÂ
After calling the method: Jane Â
As we can see, the changes made to the name property within the change name method affect the original Person object.
While relegating another object reference inside the technique affects the first reference, changes to the item's properties are reflected in the first object.
Think about the following instance:
java
public class PassByValueExample {Â
  public static void main(String[] args) {Â
    StringBuilder sb = new StringBuilder("Hello");Â
    System.out.println("Before calling the method: " sb);Â
    assignNewObject(sb);Â
    System.out.println("After calling the method: " sb);Â
  }Â
  Â
  public static void assignNewObject(StringBuilder text) {Â
    text = new StringBuilder("Hi");Â
    System.out.println("Inside the method: " text);Â
  }Â
} Â
The output of running this code is as follows:
SQL
Before calling the method: HelloÂ
Inside the method: HiÂ
After calling the method: Hello Â
From the output, we can see that although the text reference within the assignNewObject method points to a new StringBuilder object, the original reference sb remains unchanged.
Understanding pass by value and call by reference in Java is crucial for writing effective and reliable code. Copy values are sent to methods by default in Java's pass by value technique. Although Java does not natively enable pass by references, it uses pass by values to manage object references. While assigning a new object reference has no effect on the original reference, changes made to an object's properties within a method do.
By grasping the concepts of pass by value and call by reference, developers can design their code more accurately and avoid potential pitfalls.
1: Can Java pass variables by reference?
A: No, Java does not support pass by reference directly. It uses pass by value, even when dealing with objects. However, changes made to object properties within a method will affect the original object.
2: Why does Java use pass by value?
A: Java uses pass by value to ensure predictable behavior and avoid unintended side effects. By passing copies of values to methods, it maintains encapsulation and helps prevent modifications to variables outside the intended scope.
3: Can I modify an object passed to a method in Java?
A: Yes, you can modify an object's properties within a method in Java. However, assigning a new object reference within the method does not affect the original reference.
4: What are the benefits of pass by value in Java?
A: Pass by value promotes encapsulation, prevents unintended modifications to variables, and improves code clarity and predictability. It ensures that modifications made within a method do not affect the original variables outside the method's scope.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...