0

I've got a doubt with the below code. any help will be appreciable.

class Test {

    static void test(List<Object> obj) {
        obj.add(5);
        obj = new ArrayList<>();
    }

    public static void main(String[] args) {

        List<Object> list = new LinkedList<>();
        list.add(10);
        System.out.println(list);
        test(list);
        System.out.println(list);
    }
}

what will be the content of list object after test method returned to main method?


Expected Output:

[10] [] //empty

since we are creating a new arraylist object in the same list reference which is passed to test method from main method.

Actual Output :

[10] [10, 5]

could please explain this?

  • The original list still exists, just that you overwrite the reference to it in your `test` method when you reassign `obj`. The `list` variable in the `main` method still has reference to the original list. – d.j.brown Apr 02 '18 at 11:15
  • https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – assylias Apr 02 '18 at 11:15
  • but other than primitive datatype java methods are pass-by-reference. right? – Ravi Ranjan Kumar Apr 02 '18 at 11:18
  • @RaviRanjanKumar Java is *always* pass-by-value. Really, please read https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – lexicore Apr 02 '18 at 11:25

0 Answers0