Java Equality

Java Equality


Java Equality: Strings play a very important role in programming in every language. In Java, the string manipulation is simplified, by the Designers, by adding more methods in String class. One such method is equals().

Strings can be compared in Java in two ways using equals() method and logical ==. Let us see their difference of usage and which is preferable and safe.

Example on Java Equality


Java Equality
Output screenshot on Java Equality

In the above code, str1, str2 and str3, all prints hello but they differ in how they are stored in memory by Java. str1 and str2 values hello are stored in string pool and str3 outside. That is, str1 and str2 refer the same hello location but not str3. For this reason str1 and str3 with equals() returns true but with ==, prints false. This is a big trap in Java coding. My advise is use always equals() to compare two strings but not == and do not bother much about locations.

For more details on Equality of two strings and the programming traps: Introduction – Immutable Nature – Comparison

Leave a Reply

Your email address will not be published. Required fields are marked *