OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 9 : Passing Arguments by Value and by Reference in Java

 

Unit - 2

Topic - 9 : Passing Arguments by Value and by Reference in Java

When a method is called in a programming language, the way the arguments are passed determines how changes inside the method affect the original variables.


1. Call by Value

  • In call by value, a copy of the variable's value is passed to the method.

  • Changes made inside the method do not affect the original variable.

In Java:

  • All primitive data types (int, float, char, etc.) are passed by value.


Example: Call by Value

// Simple types are passed by value class Test { void meth(int i, int j) { i *= 2; j /= 2; } } public class CallByValue { public static void main(String[] args) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b); } }

Output:

a and b before call: 15 20 a and b after call: 15 20

💡 Explanation:
Inside meth(), the changes are applied to copies of a and b, not the originals.


2. Call by Reference

  • In call by reference, the actual reference (address) of the variable is passed to the method.

  • Changes made inside the method affect the original object.

In Java:

  • Objects are passed by value of reference (also called “pass-by-value, where the value is a reference”).

  • This means a copy of the reference is passed, allowing modification of the object’s data.


Example: Call by Reference Behavior in Java

class Test { int x, y; Test(int i, int j) { x = i; y = j; } void change(Test obj) { obj.x *= 2; obj.y /= 2; } } public class CallByReference { public static void main(String[] args) { Test ob = new Test(15, 20); System.out.println("ob.x and ob.y before call: " + ob.x + " " + ob.y); ob.change(ob); System.out.println("ob.x and ob.y after call: " + ob.x + " " + ob.y); } }

Output:

ob.x and ob.y before call: 15 20 ob.x and ob.y after call: 30 10

💡 Explanation:
Here, the reference to ob is copied, but both the original and the copy point to the same object.
Thus, modifying obj.x and obj.y changes the original ob.


Key Points

  • Java is always pass-by-value.

  • For primitives → value of the variable is copied → no change in original.

  • For objects → value of the reference is copied → changes affect the same object.

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies