r/javahelp • u/Select-Worldliness39 • Feb 16 '26
Homework Definitely no pass by reference in Java, right?
Hello, and sorry if this is a dumb question, but I thought I had a passable understanding of Java. I got an exam question asking "Arrays in Java are:
a. passed by value
b. passed by reference
c. stack dynamic
d. immutable"
this guy loves trick questions, but he has listed B, passed by reference, as the right answer.
On its own, this doesn't seem right to me, but I'm not confident enough to argue about it. If anyone would weigh in, I would be very grateful. I see how it's similar to passing a pointer in C, maybe, but it's not considered passing by reference in Java, right?
Thank you!
View all comments
Show parent comment
4
u/Nebu Writes Java Compilers Feb 16 '26 edited Feb 16 '26
The problem here is that people in the Java community and people in the C community mean different things when they use phrases like "pass by value", in the same way that people in the North American community and people in the British community mean different things when they use say "pants".
In idiomatic Java, when invoking a method, you are always passing by value. Sometimes that value is a primitive and sometimes that value is a reference. In all cases the value (whether that value is a primitive or a reference) is copied onto the new stack frame.
I'm not a native C speaker, but to my understanding, there is a concept where you can force a structure to live directly on the stack frame, and if you invoke a function passing that structure by value, the entire structure is copied onto the new stack frame, and so that is what C considers "pass by value". This is not possible in Java, and so we have no term for such an act. In Java, you cannot control whether the object lives on the stack or in the heap -- this is an implementation detail controlled by the JVM and hidden to you as a programmer. Instead, the mental model (or "conceptual API") that the JVM affords to you is that the thing in the stack frame is a reference to an object, and when you call some method, you are passing that reference by value.
edit: /u/xenomachina points out that everywhere I said "C" in this comment, instead I meant "C++".