String is a special class in Java, so is String comparison. When I say comparing String variables, it can be either to compare two String object to check if they are same, i.e. contains same characters or compare them alphabetically to check which comes first or second. In this article, we are going to talk about the right way of comparing String variables, but what is the wrong way? The wrong way is to compare String using
== operator. It is one area in which almost every Java programmer has made mistakes sometime by comparing two String variable using == operator. Many Java developers are exposed to string comparison very early in their Java journey, It's often required in their first few programming assignments e.g. write a program to print hello if user enters
"John". When you first start with String in Java, you create object using
String literal syntax e.g.
name = "John" and then compare using == operator, you will get right answer, but if you take same String as user input, you will not get correct answer. Why? because equality operator compare references i.e. if two reference variable points to same object in heap then it returns true, otherwise it returns false.