Pass by value or Pass by reference in Java?

The confusion is probably due to the fact that a variable can’t contain an object in the first place. A variable can only contain a reference to an object. (In other words, objects aren’t passed at all, not by reference, not by value.)

Once you realize this, it is quite clear that nothing is pass-by-reference in Java. A variable refering to an object stores a reference, and this reference is passed by value.


1. What is Pass By Value means…

Answer: Its just passing the numbers or value stored in the variable to a function. Am i right or wrong.

That’s right. The value contained in the variable is passed, and not the variable itself.

1. How do you say Java is Pass By Value?

Java is pass by value because primitives are passed by value, and references are passed by value. (Objects are never passed.)

You can’t implement a swap method in Java for instance. I.e., you can’t do

String str1 = "hello";
String str2 = "world";
swap(str1, str2);
// str1 can't refer to anything but "hello"
// str2 can't refer to anything but "world"

2. Why is Java is Pass By Value and not by reference?

As explained above, even references are passed by value.

Leave a Comment