1

I created this bit of code to try and better understand some concepts in Java.

class S {
    private String s;

    public S(String s) {
        this.s = s;
    }

    public S c(String s) {
        return new S(this.s + s);
    }

    public void b(S o) {
        if (this.s == o.s) {
            System.out.println("ok");
        }
    }
}

class M {
    public static void main(String[] args) {
        S s1 = new S("toto");
        S s2 = s1.c("");
        s1.b(s2); //1.
        s1.b(new S("toto")); //2.
    }
}

At //1 (Changing it so user can understand) it prints ok as I expected it to, but at //2 it doesn't print ok (nothing) but I don't understand why. Isn't the variable s in S2 the same as the variable s in S1?

2000mroliver
  • 135
  • 1
  • 9

0 Answers0