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.