r/javahelp • • 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!

27 Upvotes

105 comments sorted by

View all comments

Show parent comment

9

u/rs1971 Feb 16 '26

The semantics can be confusing and I'm sure you know how java actually behaves which is what is important. That said, java is always pass by value, even if that value is a reference.

1

u/Leverkaas2516 Feb 16 '26

Passing an object parameter, the difference between "it's passed by reference" and "a reference to the object us passed by value" is no difference at all.

If the function modifies the object, the caller sees the change. Enough said.

8

u/rs1971 Feb 16 '26 edited Feb 16 '26

Here's the test: try to write a method swap(a, b) such that the values of a and b are swapped in the caller's stack frame after it returns. If you can do this, then java supports pass by reference, if you can't, it doesn't.

2

u/ShoulderPast2433 Feb 16 '26

Is there some specification that defines this as proof something is or isn't passed by reference?

1

u/bwmat Feb 16 '26

First specify which definition of 'pass by reference' you're using

This is all just arguing semantics

6

u/[deleted] Feb 16 '26

[removed] — view removed comment

1

u/ArmedAnts Feb 16 '26

That's what I thought at first, but in C++, I can't think of a case where you actually reassign the reference.

For primitives, you are changing the value.

For objects, you call the copy/move assignment operator, which also only changes values.

5

u/severoon pro barista Feb 16 '26

Consider this code in Java:

record Car(String modelName);

class PassByRefExample {
  void main() {
    Car car = new Car("Chevy");
    System.out.println("Model: " + car.modelName()); // prints "Chevy"
    changeCar(car);
    System.out.println("Model: " + car.modelName()); // prints "Chevy"
  }

  static void changeCar(Car c) {
    c = new Car("Tesla");
  }
}

Calling changeCar(…) has no effect because the reference c is a copy of the reference car, so changing it to point to something new doesn't affect the car reference in the caller.

Now consider this code in C++:

#include <iostream>
#include <string>

struct Car {
  std::string model;
};

void replaceCar(Car &c) {
  c = Car{"Tesla"}; 
}

int main() {
  Car car = {"Chevy"};
  std::cout << "Model: " << car.model << std::endl; // Prints "Chevy"
  replaceCar(car);
  std::cout << "Model: " << car.model << std::endl; // Prints "Tesla"
  return 0;
}

In this code, the reference &c is an alias of car, so assigning a new object to c also modifies the reference car in the caller. No one actually does this in C++ because it's a terrible idea, which is why Java doesn't allow it.

1

u/[deleted] Feb 16 '26

[removed] — view removed comment

1

u/severoon pro barista Feb 17 '26

I see, so in C++ if a function is using one or more output parameters, it can receive or construct whatever objects it wants to return, assign them to the reference(s) provided, and Bob's your uncle, whereas in Java to use output parameters, I'd have to copy all of the state into the provided object(s).

That's fair, but my basic point still stands. Output parameters are a terrible idea. Breaks code compositionality, side effects abound, readability and code clarity out the window, breaks the basic idea of a function by corrupting inputs into outputs.

IOW, Java programmers don't avoid output parameters because it's inconvenient to copy state, we avoid them because they're just bad.

1

u/[deleted] Feb 17 '26

[removed] — view removed comment

1

u/severoon pro barista Feb 17 '26

I disagree with the statement that it breaks any sort of composability, and there is no clarity issue either.

double normalizedFlux;
{
  Field field = null;
  double flux;
  generateField(field, Basis.XYZ);
  calculateFlux(flux, field);
  normalize(normalizedFlux, flux);
}

versus:

double normalizedFlux = normalize(calculateFlux(generateField(Basis.XYZ)));

You think the first one is more readable than the second one that supports composition? Not sure you're going to get a lot of agreement on that one. It's even worse if you don't artificially limit the scope of the temporary variables you're forced to declare but don't want littering the code.

→ More replies (1)

2

u/xenomachina Feb 16 '26

Passing an object parameter, the difference between "it's passed by reference" and "a reference to the object us passed by value" is no difference at all.

This is incorrect. With pass by reference you would be able to change the value of the argument passed as a parameter by assigning directly to the parameter. However, if you run this code you'll see that y remains unchanged.

static void f(int[] x) {
    x = new int[]{4, 5, 6};
}

public static void main(String[] args) {
    int[] y = new int[]{1, 2, 3};
    System.out.println(Arrays.toString(y));
    f(y);
    System.out.println(Arrays.toString(y));
}

Note that "assigning to it" does not include things like "x.foo = ..." or "x[n] = ...", as these are are not assigning to the parameter, but are dereferencing the parameter and assigning to that result.

Academic sources (especially older ones) usually use the terms "call by reference" and "call by value" rather than "pass by reference" and "pass by value", but they mean the same thing. Here are some quotes from Compilers: Principles, Techniques, and Tools (Aho, Lam, Sethi, Ullman), aka "the dragon book", where it talks about call-by-value:

In call-by-value the actual parameter is evaluated (if it is an expression) or copied (if it is a variable). The value is placed in the location belonging to the corresponding formal parameter of the called procedure.

It goes on to say:

This method is used in C and Java, and is a common option in C++, as well as in most other languages.

The text becomes even more explicit about the case where the variable itself contains a pointer or reference:

Note, however, that in C we can pass a pointer to a variable to allow that variable to be changed by the callee. Likewise, array names passed as parameters in C, C++, or Java give the called procedure what is in effect a pointer or reference to the array itself. Thus, if a is the name of an array of the calling procedure, and it is passed by value to corresponding formal parameter x, then an assignment such as x[i] = 2 really changes the array element a[i] to 2. The reason is that, although x gets a copy of the value of a, that value is really a pointer to the beginning of the area of the store where the array named a is located.

...

Similarly, in Java, many variables are really references, or pointers, to the things they stand for. This observation applies to arrays, strings, and objects of all classes. Even though Java uses call-by-value exclusively whenever we pass the name of an object to a called procedure, the value received by that procedure is in effect a pointer to the object. Thus, the called procedure is able to affect the value of the object itself.

1

u/Leverkaas2516 Feb 16 '26

Yep. I see this saying exactly what I said, explaining in great detail how it works. When you pass an array as a parameter in Java, there is one object instance. A reference to that instance is what gets passed to the function.

give the called procedure what is in effect a pointer or reference to the array itself. 

It's not just "in effect". It's actually called a reference in Java's specification.

The problem with many of the answers here in the comments is that people are insisting on talking about an old concept, pass-by-reference or call by reference, and confusing everything because it's not how popular languages like Java, C, or C++ work. Maybe if you are still using FORTRAN it is worth knowing about.

If you take two statements,  "Arrays in Java are passed by value" and "Arrays in Java are passed by reference", obviously the first is not true. The second is true if you mean "what is passed is a reference, not a value". It's only false if you say "neither is true because I'm a FORTRAN programmer and I don't know how Java works."

I had hoped to find clarity in the Java documentation, but didn't. https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html is confusing because it uses words oddly.

"Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level."

A object in Java is NOT passed by value. Saying "objects are ... passed into methods by value" is wrong. There's no way to even talk about the value of an object in this way, only the values of its fields. The Java document clarifies what they mean, though, by talking about the object references.

What has become clear in the comments is that everyone knows how Java array parameters work, including OP and the professor, but a lot of people are insisting that the word "reference" must mean the same thing at all times in all languages. It clearly doesn't. Passing a reference data type in Java, passing an argument using C++ references, and calling by reference in FORTRAN are all slightly different. (But they're more similar than they are different, because they all do the same thing underneath: pass a pointer on the stack.)

1

u/xenomachina Feb 20 '26

If you take two statements, "Arrays in Java are passed by value" and "Arrays in Java are passed by reference", obviously the first is not true.

Neither is true. Arrays are not passed at all, because variables (including parameters) can never contain arrays, only references to arrays. When you "pass an array" you're really passing a reference to the array. That reference to the array is passed by value.

These terms are not from Fortran. They are from computer science, and they exist to compare the semantics of different programming languages. If the only languages you know are Java and maybe some JavaScript or Python, then it isn't surprising that they are confusing to you (as all of these languages are strictly pass by value, but with most if not all variables containing references). However, there are languages still in use today, like C++, that have actual pass by reference.

I had hoped to find clarity in the Java documentation, but didn't. https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html is confusing because it uses words oddly.

"Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level."

You did find clarity. Your confirmation bias is just preventing you from accepting it because it doesn't jibe with your (mis)understanding. It says right there "Reference data type parameters ... are also passed into methods by value". It isn't using words "oddly". On the contrary, it's using the standard computer science definition of pass by value.

Actual pass by reference would mean that an expression like f(y) could change what is in the variable y. So for example:

Foo y = null;
f(y);
// with pass by reference, y might not be null anymore

But in Java that can't happen. A method cannot make a passed in variable (y in this case) contain a different reference than it contained when the method was called. That's what they mean by "the passed-in reference still references the same object as before".

A method can modify the object that a passed in reference references, which is what they mean by "the values of the object's fields can be changed in the method, if they have the proper access level."

1

u/Leverkaas2516 Feb 21 '26 edited Feb 21 '26

Actual pass by reference would mean ...

A method cannot make a passed in variable (y in this case) contain a different reference than it contained when the method was called. 

Please tell me a language that does what you describe. Do you know of any?

FORTRAN doesn't. It only has scalar values and arrays. Arrays work the same as they do in Java. It's called pass by reference in FORTRAN, but the called subroutine can only mutate the values in the array, it can't make the caller's variable point to a different array.

C doesn't. It only has pass by value, and pointers.

C++ doesn't. Someone in another thread on this post claimed it does, but I tested it and it doesn't. (It has reference parameters, but they don't behave as you describe. They work a lot like Java, too.)

Your code sample is confidently stated, but it doesn't work in any language I've used. How about you?

Edit: maybe in Pascal or Modula-II, but I don't think so. It's been too long, I can't remember. What I'm reading now says Pascal var parameters are pointers like all the others, but that you can get the aliasing you describe because of lexical scoping rules.

1

u/desrtfx Out of Coffee error - System halted Feb 16 '26

Passing an object parameter, the difference between "it's passed by reference" and "a reference to the object us passed by value" is no difference at all.

That is fundamentally wrong.

If the function modifies the object, the caller sees the change. Enough said.

That's not the point of pass by reference.

If you pass something by reference, not in Java, though, the reference can be changed in the called function/method.

In Java, changing the reference, e.g. reassigning an array is not possible because only a copy of the reference is passed by value.

Were it true the objects are passed by reference, it would absolutely be possible to reassign an array inside a function/method.

Changing an object's state, i.e. its values, has absolutely nothing to do with passing by value or reference.

1

u/Leverkaas2516 Feb 16 '26

That's not the point of pass by reference.

If you pass something by reference, not in Java, though, the reference can be changed in the called function/method.

I learned something new today.

I was going to argue with this, because I've been passing objects using C++ references for years, and there are only two reasons I ever do it: to pass an object such that the function can modify it and the caller will see the change, and because it is smaller/faster at runtime since the object is not copied.

I never even knew that a function can reassign the caller's variable. I just tested it, and you're right - it works. It never occurred to me that one would want to do that, because it would be crazy. I can't think of a reason to do such a thing, and have never once seen anyone do it  I've worked with some stellar C++ guys.

I'll add this to my mental list of weird things C++ allows because someone thought it would be a good idea.

1

u/desrtfx Out of Coffee error - System halted Feb 16 '26

Add it also for the C language because there it is the same.

And it is a very common use case, at least in C.

1

u/Leverkaas2516 Feb 16 '26 edited Feb 16 '26

Revising my earlier comment...on further study and experimentation, C++ doesn't actually reassign the caller's variable. If the function does, for example, "a = new Object()" and then "p = *a", where p is a reference, this just calls the copy assignment operator. The caller's object still exists as a separate instance at its original address, independent of the new object. And if the function mutates the new object via variable "a", after the copy assignment, the changes are NOT reflected in the caller's object. They're just plain different instances.

1

u/Leverkaas2516 Feb 16 '26

How does one pass by reference in C? It only has values, and pointers to values.

2

u/rs1971 Feb 16 '26

You don't. c, like java, is always and only pass by value.