Pass by Value vs Pass by Reference in Java

📘 Core Java – Day 9 Topic: Pass by Value & Pass by Reference Today I learned how data is passed to methods in Java. Understanding this concept helps avoid confusion while working with variables and objects. 🔹 Pass by Value 🔸 What is Pass by Value? The actual value stored in a variable is passed to a method. Java creates a copy of the value and sends it to the method. Any change made inside the method does not affect the original variable. This ensures data safety and avoids unintended changes. 🔸 Explanation When a primitive data type (like int, float, char, etc.) is passed to a method, Java passes only the value, not the memory address. So, the original variable remains unchanged. 🔸 Example: class PassByValueExample { static void change(int x) { x = 50; // changing copied value } public static void main(String[] args) { int a = 10; change(a); System.out.println(a); } } Output: 10 ✔ Even though x is changed to 50, the original variable a remains 10. 🔹 Pass by Reference (Object Reference) 🔸 What is Pass by Reference? The reference (memory address) of an object is passed to a method. Multiple references can point to the same object. Changes made inside the method affect the original object. This improves memory efficiency. 🔸 Explanation When an object is passed to a method, both the original reference and method parameter point to the same object in memory. So, changes reflect everywhere. 🔸 Example: class Student { int marks; } class PassByReferenceExample { static void update(Student s) { s.marks = 90; // modifying object } public static void main(String[] args) { Student obj = new Student(); obj.marks = 60; update(obj); System.out.println(obj.marks); } } Output: 90 ✔ The object value is updated because both references point to the same memory location. #CoreJava #JavaProgramming #LearningJava #PassByValue #PassByReference #Day9

To view or add a comment, sign in

Explore content categories