Comparing strings with == which are declared final in Java

后端 未结 6 621
醉酒成梦
醉酒成梦 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:31

    Though, when you create using String literal notation of Java, it automatically call intern() method to put that object into String pool, provided it was not present in the pool already.

    Why does final make a difference?

    Compiler knows the final variable never gonna change, when we add these final variables the output goes to String Pool because of str1 + str2 expression output also never gonna change, So finally compiler calls inter method after output of the above two final variables. In case of non-final variable compiler do not call intern method.

提交回复
热议问题