In the below program, we have two strings style and style2 both containing the same world Bold.
However, we’ve used String
constructor to create the strings. To compare these strings in Java, we need to use the equals()
method of the string.
You should not use ==
(equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not.
On the other hand, equals()
method compares whether the value of the strings are equal, and not the object itself.
If you instead change the program to use equality operator, you’ll get Not Equal as shown in the program below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class CompareStrings { public static void main(String[] args) { String style = new String("Bold"); String style2 = new String("Bold"); if(style.equals(style2)) System.out.println("Equal"); else System.out.println("Not Equal"); } } |
Output:
1 2 3 | Equal |