Comparing strings in java

前端 未结 7 1475
别那么骄傲
别那么骄傲 2020-12-22 05:58
String string1 = \"Hi there\";
String string2 = \"Hi\";
String string3 = \"Hi\";

System.out.println(string1.substring(0, string2.length()) == string2); //1
System.o         


        
相关标签:
7条回答
  • 2020-12-22 07:01

    Several things going on there.

    When you declare two strings to be equal "Hi", java optimizes it to refer to the same string object (so it doesn't have to store the same string twice).

    "==" compares references. When in line 1 you use substring, the created string object has a different reference than string2.

    In line 6, I imagine substring(0) has an optimization where it knows it can just return the original string, thus those references are equal.

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