Demonstrating string comparison with Java

99封情书 提交于 2019-11-27 16:08:05

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.

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!

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!