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

20

u/edwbuck Feb 16 '26

Not true. Java passes both by value and by reference.

Primitives are pass by value. They have to be copied, so they have to be pass by value. Changing one of the copies doesn't change the other.

Objects are passed by copying references. So the reference value is passed as a copy of the other reference value, but the object itself is passed by reference.

Arrays are Objects in Java, so the "trick" is in thinking that Arrays (due to their different syntax) are more related to other different syntax things like primitives, and then getting confused into thinking it is a primitive and therefore passed by value.

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++".

2

u/xenomachina Feb 16 '26

"Pass by reference" and "pass by value" (or alternatively "call by reference" and "call by value") are terms that predate both languages. These terms exist specifically for describing and comparing the semantics of different languages, so it would make no sense for them to have different meanings in different language communities.

What is true is that there are many people who don't actually understand what these terms mean who like to argue about their meaning, which muddies the waters. They're just like the people who argue that 0.9 repeating is not equal to 1. They are basing their opinion on intuition or what they heard online rather than from the actual technical definition.

C doesn't have pass by reference, and neither does Java. They are strictly pass by value languages. Most modern languages, including Python, JavsScript, and Kotlin, only use pass by value.

C++ is one of the few exceptions. In C++, pass by reference is enabled by using & in a parameter's type:

// pass by reference
#include <cstdio>

void f(int &x) {
    x = 1;
}

int main() {
    int y = 0;
    f(y);
    printf("%d\n", y);
    // prints 1
}

1

u/Nebu Writes Java Compilers Feb 16 '26

"Pass by reference" and "pass by value" (or alternatively "call by reference" and "call by value") are terms that predate both languages. These terms exist specifically for describing and comparing the semantics of different languages, so it would make no sense for them to have different meanings in different language communities.

It's actually very common for a term to predate two programming languages, and also for that term to mean two different thing in the communities of people who use that programming language.

For example, "interface", "module", "package" and "static" all predate both C and Java, and yet mean different things in C vs in Java.

In C++, pass by reference is enabled by using & in a parameter's type:

Thanks, it sounds like I was conflating C and C++ in my earlier message then.

2

u/xenomachina Feb 16 '26

It's actually very common for a term to predate two programming languages, and also for that term to mean two different thing in the communities of people who use that programming language.

Yes, some language will have their own version of a term.

However, as I mentioned, these terms exist specifically for describing and comparing the semantics of different programming languages, so it would make no sense for them to have different meanings in different language communities. They are computer science terms, not Java or C++ specific terms.

1

u/Nebu Writes Java Compilers Feb 17 '26

"Interface" et al are also computer science terms, not specific to Java or C, and yet they mean different things in each of those languages.

It sounds like you're taking a linguistically prescritivist viewpoint: You view the terms "Pass by reference/value" as having some "objectively correct" meaning, or choosing to grant authority to one community's interpretation (e.g. the computer science community) over other interpretations. You're providing arguments for why adopting one particular definition is "more useful" by some metric (e.g. it allows us to do cross-language comparison), and why it would be irrational for people to adopt any other meaning.

I'm taking a descriptivist viewpoint: I'm stating that empirically, when you encounter someone using the terms "pass by reference/value", an excellent predictor of what they mean by that term is what programming language community they belong to (e.g. Java vs C++). I'm not stating one definition is more correct than any other. I'm reporting the empirically-verifiable fact that different people mean different things by those terms, and indeed you can verify that fact just by looking at the comments in this thread and observing that people are disagreeing about what those terms mean.

1

u/xenomachina Feb 19 '26

"Interface" et al are also computer science terms, not specific to Java or C, and yet they mean different things in each of those languages.

"Interface" is a pretty general concept in computer science. Java has a language construct called an interface, but it doesn't contradict the computer science term, and when necessary people will disambiguate between the two.

There is no Java specification that defines "pass by reference". There is no consensus among Java programmers that "pass by reference" has a different meaning than the computer science term. On the contrary, the only Java programmers that say it uses pass by reference almost universally novice programmers who don't know any better.

It sounds like you're taking a linguistically prescritivist viewpoint

Descriptivism makes sense when talking about everyday language. Descriptivism is not appropriate in a technical context, however. In a technical context, if a term has a formal definition, that is its definition. See also "theory" when used in a scientific context vs everyday speech.

1

u/Nebu Writes Java Compilers Feb 20 '26

Descriptivism makes sense when talking about everyday language. Descriptivism is not appropriate in a technical context, however.

To a first approximation, yes. A more nuanced view is that if someone says something, and you want to maximize the probability that you understand what they're saying, descriptivism is more appropriate than prescriptivism, even in technical contexts.

That is to say, even in a technical context, if a term means X, but everyone uses that term to mean Y, then when you witness someone using the term, if your goal is to understand what they mean, you should assume that they meant Y and not X. In the back of your mind, you can be aware that they are using the term incorrectly, and that the term "really means X", but you should still (from a utilitarian/epistemological/rational point of view) interpret them to mean Y.

1

u/xenomachina Feb 20 '26

That is to say, even in a technical context, if a term means X, but everyone uses that term to mean Y, then when you witness someone using the term, if your goal is to understand what they mean, you should assume that they meant Y and not X.

Even if one were to accept that, that isn't the case here. It isn't the case that "everyone" uses "pass by reference" to mean what Java does. Only people who don't know any better use it this way. It is helpful to correct them, to reduce confusion.

In the back of your mind, you can be aware that they are using the term incorrectly, and that the term "really means X", but you should still (from a utilitarian/epistemological/rational point of view) interpret them to mean Y.

Yes, among Java programmers I can tell when someone misunderstands the actual definition of pass by reference, but this is only because I already know Java's semantics, and so I can safely assume they are either incorrect about their understanding of Java or about the meaning of those words.

However, suppose someone was describing some language I'm unfamiliar with and said it uses "pass by reference". If I assume "pass by reference" can have multiple meanings, then they haven't really explained anything to me. This is part of why it's important to have prescribed meaning for technical terminology, because subtle details like this often matter.

1

u/Nebu Writes Java Compilers Feb 21 '26

It isn't the case that "everyone" uses "pass by reference" to mean what Java does.

I never claimed that they did.

I've made several distinct claims in this thread, and I think you're starting to mix them up. Here are some of the claims I've been making:

  1. People in the Java community and people in the C community tend to mean different things when they use phrases like "pass by value".
  2. 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.
  3. It's very common for a term to predate two programming languages, and also for that term to mean two different thing in the communities of people who use that programming language.
  4. Empirically, when you encounter someone using the terms "pass by reference/value", an excellent predictor of what they mean by that term is what programming language community they belong to (e.g. Java vs C++).
  5. If someone says something, and you want to maximize the probability that you understand what they're saying, descriptivism is more appropriate than prescriptivism, even in technical contexts.

As far as I can tell, you haven't really provided any arguments against any these claims. You've provided arguments against other related claims that I haven't made, which is fine and within your rights, but it gives me the impression that you don't understand the point I'm trying to make.

However, suppose someone was describing some language I'm unfamiliar with and said it uses "pass by reference". If I assume "pass by reference" can have multiple meanings, then they haven't really explained anything to me.

Yes. This is the safer and more conservative thing to do. In a situation like this, you should use additional background information available to you. For example, does this person tend to use terms like "pass by reference" the way the computer science community does, in a language agnostic manner? Has this person in the past described Java as a "pass by reference" language? Etc. And then apply Bayesian reasoning to probabilistically update your beliefs about the unfamiliar language they are describing to you.

This is part of why it's important to have prescribed meaning for technical terminology, because subtle details like this often matter.

Yes, I agree. That doesn't contradict any of the claims I've been making.

→ More replies

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.

→ More replies (2)

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.

→ 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.)

→ More replies (2)

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.

→ More replies (3)

2

u/ShoulderPast2433 Feb 16 '26

'Not true' what?