# What happens when compose String with difference sequence?

Stack Overflow Asked by shiwee on August 9, 2020

I am confused by below two segments of codes, what makes the difference?

    String s1 = new String("1") + new String("2");
s1.intern();
String s0 = "12";
Assert.assertTrue(s1 != s0);
Assert.assertTrue(s1.equals(s0));

String s20 = new String("2") + new String("1");
s20.intern();
String s21 = "21";
Assert.assertTrue(s21 == s20);
Assert.assertTrue(s21.equals(s20));


let me explain my question, the above codes pass the test without assert exception, that means "s1 != s0" is true, "s21 == s20" is true as well! "s1 != s0" should be false in my understanding!
if i am not clear, below codes may explain well than my words:

    String s20 = new String("2") + new String("1");  // "21"
s20.intern();
String s21 = "21";  // "21"
Assert.assertTrue(s21 == s20);  // equal reference
Assert.assertTrue(s21.equals(s20));

s20 = new String("1") + new String("2");  // "12"
s20.intern();
s21 = "12";  // "12"
Assert.assertTrue(s21 != s20);  // NOT equal, why??
Assert.assertTrue(s21.equals(s20));


String is an object, not primitif, == or != compare reference and .equals the value. But you use .intern() but intern() return an String but you can't not assign.

Answered by Anthony Deseille on August 9, 2020

Not completely sure what you want but at least you have different comparisons in the assertions:

Assert.assertTrue(s1 != s0);
// VS.
Assert.assertTrue(s21 == s20);


Answered by drodil on August 9, 2020