AnswerBun.com

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));

2 Answers

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

Add your own answers!

Related Questions

Animation to play once per session

0  Asked on January 15, 2021 by alejandro-vargas

       

postgres random text in jsonb column

2  Asked on January 15, 2021 by ed1t

         

How to make TestNG print detail message about the failure

2  Asked on January 15, 2021 by gelin-luo

 

Strange igraph behaviour, generating duplicate vertices

1  Asked on January 15, 2021 by simon-mills

   

C++ printing float as nan

1  Asked on January 14, 2021 by acarter

     

Webclient isn’t dowloading everything from URL c#

1  Asked on January 14, 2021 by shynex

       

How to change the entire div content on button click

2  Asked on January 14, 2021 by liel-barouch

   

Sorting and paging nested documents

2  Asked on January 14, 2021 by taras-kohut

 

How to adjust for loop so that it prints list only once?

1  Asked on January 14, 2021 by benito-cano

         

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir