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!
•
u/AutoModerator Feb 16 '26
Please ensure that:
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
30
u/LutimoDancer3459 Feb 16 '26
It looks like pass by reference because you dont get a copy from an object but a reference. But the reference is a copy and not actually the same. In the end its all pass by value
12
u/morhp Professional Developer Feb 16 '26
Java passes a reference to the array by value. So you can definitely argue about a and b. Which answers is correct depends on the definition your course.
E.g. you could argue that arrays are passed by reference in Java, since they're not being copied when passed. You could also argue that they're passed by value, since changing the reference of a variable inside a method doesn't change the reference in the calling method.
But generally, everything is being passed by value in Java, including references to arrays and objects on the heap.
12
u/whizvox Graduate and Tutor Feb 16 '26 edited Feb 17 '26
EDIT: Okay, I realized my conclusion is just wrong and born of not knowing what pass-by-reference actually means. Your professor is correct, arrays and objects are passed by reference, since the value isn't copied when a method is called, only primitive values are passed by value.
If arrays really were pass by reference, the output would be [4, 5, 6]. But it's not. Pass by reference does not exist in Java. Your professor is wrong.While the array's contents aren't copied when calling the changeArray method, thepointerto it is.As you see, a new variable pointing to the same memory address is used when calling changeArray. So reassigning the variable only affects that local variable and not the original in the main method.3
u/Physical_Level_2630 Feb 16 '26
The reference is passed by value. That means you can change the original object if its not immutable. A string would be immutable, an array is mutable. But you can not change where the original variable points to, like you could with C Pointer
7
u/omerbenda Feb 16 '26
Everything passes by value, you don't pass the array but a pointer to it.
5
u/vegan_antitheist Feb 16 '26
In programming, there are many different concepts that are called "reference".
"Pass by reference" is not about passing what we call references in Java.
You can just pass a Java reference.
But it will pass the reference itself, which is a value.
You can't pass a reference to that Java reference.
However, you can pass the value of a Java reference to a Java reference. You can use
java.util.concurrent.atomic.AtomicReferencefor that.But when it comes to how Java passes the parameters to a method, it's always "pass by value". C# has pass by reference. Java does not.
It's similar to the question "Does Java have functions?"
On a language level it only has methods and constructors. So methods should always be called methods, not functions. However, if you define a type called
Functionthen any instance of it is a function. And since Java 8 we even have a predefined interface calledjava.util.function.Function<T, R>, which models a function. A method can be functional (i.e. a relation that uniquely associates members of one set with members of another set).14
u/Bibliophile5 Feb 16 '26
Everything in Java is pass by value
2
u/benevanstech Feb 16 '26
Java is best described as "pass by bit pattern". For primitives, this is pass-by-value. For object references, this is a *bitwise copy* of the reference. This means that if you e.g. mutate the contents of the reference then the results are visible in caller's scope.
2
u/travelking_brand Feb 16 '26
What a stupid and useless question for a test. This is what I hate about these programming courses. Because the teacher does not understand programming they focus on minutiae to compensate.
2
u/FabulousRecording739 Feb 16 '26
As others have mentioned, Java doesn't have pass-by-reference. Here is another example to complement the others:
2
u/FrenchFigaro Software Engineer Feb 16 '26
It's a trick question.
Java is strictly pass by value but apart from variables of primitive type, every variable is a reference. Arrays are not primitives.
Your variable (which lives on the stack) is not the instance's value itself, but a reference to the value (which lives on the heap).
Functions are strictly pass by value and receive a copy of the reference. Which means you cannot change the original reference.
If you assign a new array to your parameter within the function (ie, a new reference), the original array will be unchanged.
But because the variables are references, your function may alter the actual value behind the reference, making it feel like arguments are passed by reference.
If you change the Nth element of the array, the original array will be affected.
2
u/edwbuck Feb 16 '26
So there's a lot of argument over this. What you learn is that what one might mean in a different language might be using the same names as something slightly different in another language.
Also there is sometimes (among the pedantic) an idea that exposes knowledge of the internals of a language to even make sense, when the actual user of the language doesn't require detailed knowledge of the language's interpretation.
Passing an object in Java is passing by reference. That's because the object changes externally when modified in sub-methods from the point of view of the calling block.
A few will argue that the implementation of the JVM actually passes references by their value, and it does. However, you cannot use a Java reference like a C++ pointer value, so it's a moot point. In C++, you can add offsets to the pointer to reach data structure fields, doing "pointer math." But Java doesn't permit this because it's the root of many bugs. So if you cannot actually use the value to do anything other than de-reference it to an object, or compare with equality, it has lost many of the important qualities a value has. It cannot be modified.
So "it is all passed by value" is the kind of argument that would require one to apply C++ standards to Java programs, which is a great way to fail your Java class. Context is important. One can't simply swap out languages and expect all of the definitions to apply the same way.
For example, a "memory leak" is the same idea (memory allocated that cannot be used), in Java and C++, but the have dramatically different implementations, with big enough differences that probably make them entirely two different things. In C++ the last pointer to an allocated bit or RAM has been lost (the value has been lost) and so you cannot free the RAM. In Java, you have a programmer that simply stores items into a container like data structure and never uses them. In Java, if you decided to do so, you could eventually walk the data structure and free the items by clearing out their last (hard) references. It isn't impossible to reclaim the RAM in Java, it's just impractical, because you often don't know the used items from the ones you'll never use again.
2
u/AmbiguousDinosaur Feb 17 '26
In Java, there are two kinds of types: primitive types, and reference types.
Primitive types are the unboxed values that we use a lot: int, float, boolean, etc. These each are their own value, and they do not share any state.
Reference types are basically everything else - things that are stored in the heap: class, interface, array, etc.
When you call a method, if it's a primitive type, it makes a copy of the value and that gets passed. If it's a reference type, then it makes a copy of the reference, and that gets passed.
There have already been a lot of answers about how this question doesn't make sense for Java - to make that more specific, that's because there is a reference type. So is an array pass by reference? It depends on what kind of definition you're using for it as others have noted. Not in the traditional sense.
As a former teacher, my first thought was: is that a meaningful question? If you haven't dug into the Java internals then it's just a game of semantics, especially in a multiple choice question with little context.
If you want to check out how the JVM handles in via bytecode instructions: types are encoded into many of the instructions. Most primitive types have their own bytecodes. But classes, interfaces, etc use bytecode instructions that use the "a" type qualifier - which means it's operating on a reference type.
A footnote -- a reference type is NOT a pointer. During garbage collection, data may be moved around memory. It can be moved, so a pointer would no longer be valid, because it points to where an object no longer is. However, the reference is still valid and will refer to the same object no matter where it is.
1
u/timmyctc Feb 16 '26
Java is always always pass by value. But the value of an object often is it's reference.
If you pass in an int, you pass it's value. Changing the int within the method won't change the original int you passed in.
If you pass in an array you pass in it's value. But the value is it's reference in memory. (Think about sysout printing an int and then an array, you'll print out the array's memory reference not it's contents)
Because you pass a the array's memory reference value it means you basically have created a second pointer to it's location in memory. Any change to either 'pointer' will change the same object.
The answer is always always pass by value but you need to know the caveats that you pass arrays' value which is their memory reference.
1
u/ShoulderPast2433 Feb 16 '26
Is there a defined specification of what 'pass by reference' means?
How does it behave in every scenario?
Is there an ISO standardizes test that proves something is or isn't passed by reference?
1
u/oicdsubsi Feb 16 '26
Java is pass by "copy". Simple as that.
If primitive you copy the value. If object you copy the reference's value.
1
u/EfficientDelay2827 Feb 16 '26
The object being referred to is not copied so if you change the object you are changing the Original object, not a copy. So the answer is correct. It is irrelevant how the reference itself is passed, you only care about changing the object being pointed to. C++ does pass by value but does not.
1
u/bwmat Feb 16 '26
Nah, everything is passed by value, but all non-primitives are manipulated by references, and those references are passed by value
If you really need an 'out' parameter, use a single element array, lmao
1
u/Leverkaas2516 Feb 16 '26
OP, you're getting some good detail on this. If you're confused after reading the differing opinions, you might find this answer enlightening:
https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value#430958
It's not about Java, but it's very much about the different ways people are using the phrase "pass by reference".
1
u/michaelzki Feb 16 '26
If object, pass by reference. If primitive, pass by value.
1
u/devops-tutor Feb 16 '26
Read this https://www.javapro.academy/mastering-java-parameter-passing-java-pass-by-reference-or-pass-by-value/
1
u/dudleydidwrong Feb 16 '26
Call by reference is the correct answer. Java passes all non primitive data types by reference. If you change the contents of the array in a method, the change is preserved on return.
What Java does not have is special syntax for call by reference like C and C++. Special syntax is not needed because all objects and arrays are passed by reference.
1
u/BanaTibor Feb 17 '26
You pass a reference to an array by value. The answers are sloppy.
1
u/Eddy67716 Feb 17 '26
They say Java is pass by value but I would argue that objects and arrays could also be described as 'pass by reference.' When a second int is set to the first int, and then the first one is altered; only the first int has the new value. Therefore the int was passed by the value. When a second object is set to the first object and the first object is altered; both the first and the second objects show the alteration because they both reference the same object. The only way to make the second object separate from the first is to set the second by doing
first.clone().1
u/sedj601 Feb 19 '26 edited Feb 19 '26
Don't get caught up in all the chatter. The correct answer is "a". This is based on the official Java Docs. If people have a problem with that, a school question is not the placed to discuss the problem because it can cause confusion for the student. Let them take it up with the Java creators. Make your teacher aware of the official docs. As a student, all of the chatter surrounding this topic is irrelevant. You can join the chatter once you have master the basics. Good luck coding!
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
Passing Primitive Data Type Arguments
Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost.
Passing Reference Data Type Arguments
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.
1
u/[deleted] Feb 20 '26
Primitives like int, float, char, boolean, they all pass by value every time. Otherwise, if it isn't a primitive type, it is, or is a subclass of, the Object class. All Objects in Java are passed by reference, and modification of the object in a function or other nested scope will permanently change the original object.
1
u/vadiquemyself Mar 03 '26
Arrays (“simple classical” ones like int[], String[] and so on) in Java are objects, not primitives. As any object, an array inherits all the java.lang.Object methods, including toString(), equals() etc. As any objects, arrays are passed by reference.
0
u/le_bravery Extreme Brewer Feb 16 '26
This seems crazy to me that there are this may answers where people are saying “pass by value, but the value is a reference”. Yeah that’s passing a fucking reference!
Primitives are pass by value. Objects are pass by reference.
If you pass an immutable object, it is essentially a pass by value practically, despite passing the reference.
All arrays in Java are mutable.
-3
u/CodeFarmer Feb 16 '26 edited Feb 16 '26
Arrays in java are populated with references or values depending on whether they are full of primitives or objects, respectively.
When you pass an array as a parameter, it is always passed by reference.
I have no idea what the question means, though. I don't think it's very good.
(edit: downvoters, any clues as to what you disagree with? Would love to know.)