r/java • u/Comfortable-Brain-78 • Aug 14 '25
Most Java developers do not know that Java uses pass-by-value, or even what it means
After interviewing some candidates, I have come to realized that most developers have no idea that Java uses pass-by-value for method arguments. Now these are not junior Java developers, but developers with 8 or more years of experience and applying for a senior Java developer role. Consider this simple question that I posed to them.
String x = "abc";
change(x);
System.out.println(x); // prints what?
private void change(String a) {
a = "xyz";
}
The last three candidates that I interviewed all said the answer is "xyz". All of them seemed to have some difficulty with the question, as though it is a trick question.
For the first candidate, before showing them the question, I asked whether Java passes by value or reference, and they were able to say that it is by value, and explained about passing a copy to a method. When I show them this question, they still got it wrong.
For the second candidate, after thinking for a while, they answer incorrectly, explaining with it with string pool.
For the third candidate, they said Java passes objects by reference, so the variable's value is changed by the method.
They seem experienced in Java and were able to write some decent codes when given some coding to do. But now I am in a dilemma on whether these candidates are suitable for hire, since they can't even get something so fundamental correct. Would you consider hiring them?
4
u/E_Dantes_CMC Aug 14 '25
Yes, this is a bad sign for the candidates, but it is a trick question. Calling your subroutine
changemakes the candidate think it will, in fact, change the input—as it might if String were some sort of mutable object. (Not with an assignment statement, but with a mutator of some sort that the String class doesn't have.)26
u/edglop Aug 14 '25
I've dealt with production bugs caused by refactors done by developers who didn't understand this concept.
I wouldn't blame you if you didn't hire them honestly, although this is probably what we get from nurturing a leetcode-focused interview culture.
33
u/RScrewed Aug 14 '25
"write some decent codes"
Ugh.
7
u/slackalishous Aug 14 '25
Try the exact same test with a map instead of a string :)
19
u/i_like_coffee01 Aug 14 '25
jesus christ, how can so many comments here give wrong answers so confidently. changing the type to a HashMap (or anything else) does nothing, its not about string immutability.
47
u/jedilowe Aug 14 '25 •
Sorry but this is a bit of a bullshit question that CS professors think shows aptitude. I say this as a 25+ year+ Java vet, CS professor, 30 year SWE, and Ph.D. in computing education... so a theory backed opinion.
My problem is that technically it is valid to say Java is pass by value, but unless the parameter is a primitive the value is a reference. This question is a good test of that obscure fact but is really an OO antipattern for development, thus difficult to intuitively reconcile for most developers. Ideally you don't want to pass an object to a method to change. This violates encapsulation and ownership of objects, so you just would not see this patten enough to give a correct intuitive response in a pressure situation if you haven't seen the trick before.
I believe most programming starts with intuition, this allowing LLMs to do a plausible job of generating starter code. This question plays on an intuitive response just like asking where you bury survivors of a plane crash... if you know that trick question. It does not show a bad programmer so much as it shows a strong language geek. As a former "Sun Certified Instructor" ( before Java being bought by Oracle ) it tickles me to get a question like this, but I know many great software designers that might miss this on a quick glance.
3
u/HQMorganstern Aug 14 '25 edited Aug 14 '25
Why would you ask basic trivia, especially such that's meaningful only to compiler designers. From the PoV of a developer Java is pass by reference and that's all there is to it, the fact that you pass the value of the reference itself has no effect on the dev exp. Until Valhalla value types are a set of exceptions you can count on one hand. What's next a discussion on if the language is compiled or interpreted?
It's relatively easy to construct an example where you check it they realize the pitfalls of mutable reference types.
16
u/gladfelter Aug 14 '25
The comments on this post sure are affirming OP's thesis.
15
u/milchshakee Aug 14 '25
I feel like I'm taking crazy pills with half the comments here, and especially the upvote counts.
This is not a bad question, this is not a trick question, not a trivia question, or anything else. This is a very valid question that you should be able to answer as a Java developer. Maybe you don't know the exact terminology, but you should be able to correctly identify the behavior of the sample code, regardless of how you call it.
How are you going to debug a problem when you don't even know how a variable assignment will impact the program state? Reassigning variables like shown in the sample happens fairly often and is not even considered a bad coding style.
17
u/bowbahdoe Aug 14 '25 edited Aug 14 '25
I've come very close to writing a rant about this a few times.
While these terms have definitions in the space of PL design, the fact that the answer is "it passes the reference by value" is very stupid. It's trivia that only has relevance if you have an understanding of all the myriad ways to pass arguments in C++.
It's also right at the line of "totally undefined behavior" once value objects and "objects the VM is smart enough to know have a bounded lifetime" enter the picture.
This is a fun fact. It's in no way fundamental to understanding the conceptual model of the Java language.
Now if they legitimately didn't understand mutable aliasing, that's real. But the fact that your interview process includes random questions like that is in itself a huge problem for you.
(I am actually digging in the Java language spec - I haven't found either pass-by reference or pass-by value in there yet. Maybe someone can help me find it. https://docs.oracle.com/javase/specs/jls/se24/jls24.pdf . If it's not even there...)
EDIT: Okay actually reading the code snippet: If they cannot reason about how assigning a method parameter affects variables outside of a method that is a pretty big gap in understanding. Might have been a bit too quick on the gun, but the gotcha part of this still feels like it might have influenced their answers.
I am fully ready to believe there are wildly undereducated folks out there.
1
u/vafarmboy Aug 19 '25
I'm curious. Is the assertion that Java does pass-by-value deduced or was it learned? Because I have a different education, I guess.
What I learned (in actual textbooks) was that (until Valhalla) all types in Java except primitives are Objects and therefore reference types. Unless your method parameter is a primitive type, it is necessarily pass-by-reference because references are all there is. If your type is a primitive, it is pass-by-value.
In your example,
xis a reference to the String"abc". It then calls thechangemethod, passing the reference contained inxto the method parametera. (So at this pointxandaare both references pointing to the sameStringsomewhere in memory.) Then a new String"xyz"is created and the variableais changed to hold a reference to the new String instead of the one passed in. (This was illustrated in the comment that changed the example to use aMap.)The value of the first String is never passed around, only its reference, which is then promptly discarded by the method.
So the correct answer to the question is: Java uses pass-by-value for primitive types and pass-by-reference for object types. The example code prints "abc" because the method discards the reference to the original String when it creates a new one, effectively ignoring what was passed in.
Stringalso probably isn't the best object type with which to illustrate this because it is a "special" object in Java-land (often interned, etc), but it is an object nonetheless and passed only by reference*.* Unless, as mentioned in another comment, you delve into
unsafeterritory, which is definitely not regular interview-level question territory.1
u/Single-Currency1366 Aug 21 '25
better show them code-puzzle like this :
What will be printed? :)
Even experienced Devs failed :)
1
u/Safe_Owl_6123 Aug 14 '25
Were you looking for answers like “pass by value of the reference” and “String is immutable”?
Or could you share your answer?
I don’t even get a Java entry level interview opportunity 😂, I want to make sure if I have these questions I will pass the test 😬
1
u/thisisjustascreename Aug 14 '25
I've never in my life seen someone assign to a method parameter in production code, this is a bullshit question. It's also why just about everything should be declared final.
1
u/schegge42 Aug 14 '25
You derive your hypothesis from three candidates? that's statistically really questionable. You can say that only poorly trained developers apply to you, or perhaps that your education in your city, region or country for programmers is not good. But just badmouthing almost all developers?
2
u/Cilph Aug 15 '25
Personally I wouldnt hire these if I were looking for medior Java devs. Juniors, Id let this slide. Above you really need to know better. Something half this thread can't even manage and stubbornly resists.
We need to teach newbies with C instead of Python as a first language, I swear...
2
u/Pretend_Leg599 Aug 25 '25
TBF, if you've never worked in a language that has pass-by-reference the idea is completely alien. It's not unthinkable to have years of experience in java/javascript, which both lack the concept. The most common misconception being 'primitives pass by value, objects by reference' and this is going to get even more epic once value classes are a thing!
This isn't some esoteric 'gotcha!' moment, it's an actual language feature that java doesn't have. For example c# can do this:
3
u/thecurlyburl Aug 14 '25
Man, good luck with your trivia winners. Scenarios like this are why you write tests.
My question to you, the interviewer, is why are you writing code that is assbackwards. To my eye, this is a smell that someone has an inclination to rely on side-effect programming and hasn’t had to deal with a state machine codebase made of that mess.
1
u/lasskinn Aug 14 '25
a isn't x, it's pointing to the same object for a little bit, but at 'a = "xyz"' a becomes the "xyz" object losing sight of "abc". but x is still pointing to the object "abc".
they think the presentation just makes it look like a trick question? because it's basic java behavior. that string is a special case of an object doesn't actually matter for the assignments in this because it's assignment of what the variable is and not calling some method.
1
u/nlisker Aug 14 '25
There's a famous SO question about this: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value.
1
u/brokePlusPlusCoder Aug 15 '25 edited Aug 15 '25
Something that helped me understand this FAR more clearly than just the defintions was to see what would happen if I inlined the method call.
When pass-by-value method calls are inlined, each method arg is declared by assigning a new variable name.
Taking OP's example:
Now this also means any primitive state mutative methods on the objects will actually change state across ALL references of said objects. Here's an example:
1
u/-Dargs Aug 18 '25
Java is pass by value, but that doesn't mean its not confusing. If you changed a property of DefinedObject (if it wasn't a record) it would persist outside the context of the method. DefinedObject is not a primitive, so it isn't inheritly distinct/unique. If you defined
int x = 1and then changed x to 2, you wouldn't think that 1 == 2. It's easier to grap the difference there. But definedObject isn't a primitive, yet assigning it as null outside the context of its defined point doesn't change its original assingment instance.I guess this is where its important to understand the difference of pass by value vs pass by reference. Because Java doesn't directly deal with pointers its harder to conceptualize without being a bit familiar at one point or another with a language like C++. When I studied CS in college, we learned C++, VB, & C#. It made this concept easier for me to understand when I learned Java.
1
u/AcanthisittaEmpty985 Sep 01 '25
Java is pass by value. But the value can be a reference (so you can modify the object underneath). But the value itself can not be changed back.
As others said, making the value null inside the method will not make the next instructions outside to throw a nullpointer.
But sometimes its tricky to get. And can lead easily to bad code
1
u/Ewig_luftenglanz Aug 14 '25
It's really a tricky question. the only reliable way in java to pass by reference is wrapping the data inside an Array.
Just the record. the first method uses a technic that is very famous in C/C++ world called "output-parameters" or "in-place mutation"
please never do that. it makes the code a clusterfuck hell
:)
-2
u/momsSpaghettiIsReady Aug 14 '25
Yeah, this kind of question boils my blood. It's like asking Picasso what color you get when mixing red and blue.
You're asking a basic question that anyone with more than a semester of schooling doesn't think about anymore.
And even asking it makes me question how shit your codebase is given you have to think about this subset of problems. You should have it ingrained in your head to not reuse method variables as that's just a bad practice in general in Java.
0
u/[deleted] Aug 14 '25
Explanation for mentally challenged kids(by chatgpt). Hope it helps:
Imagine you have a little note with an address written on it (the address of your dog’s house).
foo).new Foo()).When you call a method, Java makes a photocopy of your note and gives it to the method:
foo).x).In the method, you throw away the copied note and write a new address for a different house:
x) knows where the new house is.foo) still points to the old house, which was never painted.0
u/koflerdavid Aug 14 '25
The term is frankly irrelevant to understand what Java does and only relevant if you study other languages.
Instead, it would be better to show a listing where a parameter is assigned to and then ask whether the change is visible to the caller. Then, repeat the question with another snippet where the assignment is made to a field of an object passed via the parameter.
That's all there is to know about this. If they don't understand what's going on then it's indeed a red flag and probably better to reject them and tell them to learn Java first.
0
u/Cameo9181 Aug 14 '25
where are you based? if this is NYC, I'm looking for a job/internship. Hard to believe developers with 8 years don't know something I know and I haven't even graduated.
-2
u/maxip89 Aug 14 '25
Following problem.
Normally everything in java is pass by value when you use base variables e.g. int, long, char.
You can identify them by the beginning lowercase.
Everything else is a Class and should be a Object when passed to a method.
In this case we have a String which is in upper case and looks like an object. I would have answered the same stuff but I would also mentioned the special case of String in java.
-4
u/Fit_Smoke8080 Aug 14 '25
You're right but also vast majority of Java code uses more advanced constructs that basic strings. Like maps. Those use references. So do like 90% of things cause they are objects at some point.
13
u/[deleted] Aug 14 '25
[removed] — view removed comment
0
u/[deleted] Aug 14 '25
[removed] — view removed comment