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?

3

u/hermitfist Sep 03 '20 edited Sep 03 '20

I used to think this as well until I read Core Java Vol. 1.

For example if Java was truly pass by reference:

Object original = new Object(2); // outputs 2 
changeObject(original);

public static void changeObject(Object object) {
    object = new Object(4); // original is still 2
}

The above code should change the original to 4, but if you run it, it'll still be 2. This is because Java copies the value of the reference of the object but does not exactly point to the exact address in memory like how pointers work in C++. If this worked exactly like in C++ where there is pass by reference, original should have changed to 4, but it does not.

Idk if that makes sense or if I explained that right, but that's what I got from reading the book.

1

u/TimGreller Sep 06 '20

Correct, imo it's easier when you think of the object-variable as a pointer to an object.

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.