Demonstrating string comparison with Java

前端 未结 3 1571
长发绾君心
长发绾君心 2020-12-04 02:07

I want to demonstrate with a few line of code that in Java, that to compare two strings (String), you have to use equals() instead of the operator

相关标签:
3条回答
  • Well, how can I demonstrate the problem using the == operator when comparing Strings (or Objects) in Java ?

    Here a way:

    String s = "ab";
    String t = new String("ab");
    System.out.println(s == t); // false
    

    Also be careful when comparing primitive wrappers and using auto-boxing: Integer (and Long) for instance caches (and re-uses!) the values -128..127. So:

    Integer s = -128;
    Integer t = -128;
    System.out.println(s == t);
    

    will print true, while:

    Integer s = -129;
    Integer t = -129;
    System.out.println(s == t);
    

    prints false!

    0 讨论(0)
  • 2020-12-04 02:32

    JAVA maintains a String Pool in the heap space, where it tries to have multiple references for same values if possible.

    Had you written :

       String s1 = new String ("Hello");
       String s2 = new String ("Hello");
    

    it would have given you the output : "different strings".'new' keyword creates a new object reference while not giving new will first check the string pool for its existence.

    0 讨论(0)
  • 2020-12-04 02:39

    The compiler does some optimizations in your case so that s1 and s2 are really the same object. You can work around that by using

    String s1 = new String( "Hello" );
    String s2 = new String( "Hello" );
    

    Then you have two distinct objects with the same text content.

    0 讨论(0)
提交回复
热议问题