In JAVA string can be allocated in two ways depending on how string is created. For example if string with String s1="cat"; JVM will put this string in string pool area. And if you again create String s2="cat"; so it will check that already a cat s1 exist with same value so it will not create another cat rather it will link the address of s1 to s2 in the string pool area, so for this condition only "==" operator works but it's not recommended to use.
But if you create another String s3=new String("cat"); it will get stored in the heap area and in this case if you will use "==" operator to compare s1 and s3 it will give wrong answer because s1 and s3 are stored in different parts of the memory so it will not be able to compare.
As "==" operator checks the value of LHS and RHS, as both are stored in different parts of memory so it will not be able to compare so it is recommended to use s1.equals(s3); function because it compares each characters in the string so it will give correct output in every case.
Top comments (0)