-2

Pass-by-reference is giving me a bit of a headache, so I'd like to see how confusing the rest of the community would find this question. Please feel free to say if you think it's a stupid question.

What would you say is the output of the following program?

class Demo {
    public static void main(String[] args) {
        ArrayList<Container> list = new ArrayList<Container>();
        Container c1 = new Container();
        Container c2 = new Container();
        c1.setSt("c1");
        c2.setSt("c2");
        list.add(c1);
        list.add(c2);

        Container c3 = new Container();
        c3.setSt("c3");
        modify(list, c3);

        for (Container st : list) {
            System.out.println(st.getSt());
        }
        System.out.println("c3.st: " + c3.getSt());
    }

    private static void modify(ArrayList<Container> list, Container container) {
        list.get(1).setSt("modified");
        container.setSt("modified c3");
        container = new Container();
        container.setSt("new container");
    }
}

class Container {
    private String st;

    public String getSt() {
        return st;
    }

    public void setSt(String st) {
        this.st = st;
    }
}
Zombo
  • 1
  • 62
  • 391
  • 407
Luis Sep
  • 2,384
  • 5
  • 27
  • 33
  • 1
    Come up with your answer and ask why it differs from your understanding. Current question is off-topic. – mtk Feb 18 '13 at 17:56
  • Is StackOverflow supposed to replace your trusty Java compiler and JVM? Voting to close. – Hovercraft Full Of Eels Feb 18 '13 at 17:56
  • 1
    Unfortunately this is not a good question for SO. It sounds like you have a real question regarding references; it is your job to properly formulate this question instead of asking something roundabout like this. – djechlin Feb 18 '13 at 17:56
  • possible duplicate of [Is Java "pass-by-reference"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference) – A--C Feb 18 '13 at 18:00
  • No, I do have the answer and the explanation. As I said, I just want to know how stupid the question is. I think -4 is a pretty clear answer. – Luis Sep Feb 18 '13 at 18:00
  • 1
    @LuisSep: Whilst this question is not suitable for SO, you could check out this fantastic post, which explains how Java passes everything by value quite clearly: http://stackoverflow.com/questions/40480/is-java-pass-by-reference – Andrew Martin Feb 18 '13 at 18:59

1 Answers1

0

It is

c1
modified
c3.st: modified c3

What do I win?

user000001
  • 32,226
  • 12
  • 81
  • 108
  • A bit of my self steem. I find a bit disturbing the reference swap. – Luis Sep Feb 18 '13 at 17:56
  • @LuisSep I don't understand why you find it surprising... Would you expect `container.setSt("new container");` to replace the other `container` (different object) that is passed as a parameter? Or would you expect `container = new Container();` to do nothing? – user000001 Feb 18 '13 at 18:12