Comparing strings with == which are declared final in Java

后端 未结 6 620
醉酒成梦
醉酒成梦 2020-11-22 14:46

I have a simple question about strings in Java. The following segment of simple code just concatenates two strings and then compares them with ==.



        
6条回答
  •  误落风尘
    2020-11-22 15:34

    As per my research, all the final String are interned in Java. From one of the blog post:

    So, if you really need to compare two String using == or != make sure you call String.intern() method before making comparison. Otherwise, always prefer String.equals(String) for String comparison.

    So it means if you call String.intern() you can compare two strings using == operator. But here String.intern() is not necessary because in Java final String are internally interned.

    You can find more information String comparision using == operator and Javadoc for String.intern() method.

    Also refer this Stackoverflow post for more information.

提交回复
热议问题