r/javahelp • • May 15 '20

how reference variables are passed as method arguments in Java

Hello, I am struggling to understand what this question is asking for, I know in C++ for pass by reference the address of the variable is passed and altered before returning unlike pass-by value(correct me if Im wrong) but in java I thought all values were automatically pass by reference? struggling to make sense of the question so any help at all will be greatly appreciated:)

Explain the difference between how pass-by-reference operates in C++ and how reference variables are passed as method arguments in Java. A good answer will include a simple example of each

16 Upvotes

30 comments sorted by

View all comments

3

u/iamsooldithurts May 15 '20

Java always passes parameters by value; the method receives a copy of the value given. The difference is whether what is being passed is a primitive or String, or an object.

Primitives hold the value assigned.

Int i = 1;
int j = 1;
i == j evaluates to true

Strings point to a static spot in memory where the string is stored.

String s = “hello”;
String t = “hello”;
s == t evaluates to true because the compiler creates the string in memory and assigns the address to both variables.

Objects hold an address in memory.

Integer i = new Integer(1);
Integer j = new Integer(1);
i == j evaluates to false because the addresses are different. However, if you do i = j then i == j will evaluate to true because they both reference the same address in memory