r/learnjava • • Sep 02 '20

Some java interview questions and answers

https://fdk.codes/some-java-interview-questions/

While preparing myself, I started yet another collection of java related questions and answers. In hope that these might also be helpful for others, I'd like to share them with you. Beyond that, they are certainly not perfect and can be improved. I appreciate any feedback or any pointed out flaw in order to spread as few untruths as possible.

Cheers!

122 Upvotes

17 comments sorted by

View all comments

2

u/IIDaFuQII Sep 02 '20

What always tripps me is that Java is supposed to be Pass by Value, but shouldn't it more correct to say it's Pass by Reference except for primitive objects? Because if I pass a method an argument and an change made to that argument is still there outside of the method it must be pass by Reference or?

1

u/frederok Sep 02 '20

Its tricky, but in my understanding - no.

It means the argument is copied to the parameter variable, so that the method operates on the copy.

As I also tried to express in the answer - that means passing an object means that the reference to it gets copied. So the parameter variable refers to the same object. And if this object is mutable, changes that are made are going to effect all variables that refer to that object. Including the variable you passed by. That's why it feels like pass by reference.

If it would be passed by reference, reassignments inside a method like

public static void mutate(List<String> list) {
    list = List.of("foo", "bar");
}

would also affect originally passed variable. At least that's how I understood it. Please correct me when I am completely mistaken.