Comparing Strings in Java
Swipe to show menu
Comparison is where Java starts to behave a bit more "low-level" than expected. It feels obvious that strings could be compared the same way as numbers — using ==. After all, if two strings look identical, why wouldn't they be equal?
The Problem with ==
If you use == with string literals, it seems to work fine at first:
Main.java
1234567891011package com.example; public class Main { public static void main(String[] args) { String order1 = "Latte"; String order2 = "Latte"; System.out.println(order1 == order2); } }
Both variables point to the same object in Java's internal string pool — when the same literal appears again, Java reuses the existing one. So == returns true.
But now let's slightly change how the strings are created:
Main.java
1234567891011package com.example; public class Main { public static void main(String[] args) { String order1 = new String("Latte"); String order2 = new String("Latte"); System.out.println(order1 == order2); } }
Using new String() tells Java to create a completely separate object each time — even if the content is identical. Since == compares memory addresses, not text, it returns false.
The key rule: == does not look at the text inside the string — it checks whether both variables point to the exact same object in memory.
equals() — Compare Actual Content
If you need to compare the actual text inside two strings, use .equals(). It ignores memory completely and focuses only on the characters:
Main.java
1234567891011package com.example; public class Main { public static void main(String[] args) { String order1 = new String("Latte"); String order2 = new String("Latte"); System.out.println(order1.equals(order2)); } }
Even though order1 and order2 are separate objects in memory, .equals() compares their content and returns true.
Case Sensitivity with equals()
Java is case-sensitive, so even one letter difference in casing makes strings unequal:
Main.java
1234567891011package com.example; public class Main { public static void main(String[] args) { String order1 = "Latte"; String order2 = "latte"; System.out.println(order1.equals(order2)); } }
"Latte" and "latte" are treated as different strings, so the result is false.
equalsIgnoreCase() — Compare Without Caring About Case
If you need to compare strings but want to ignore uppercase/lowercase differences, use .equalsIgnoreCase():
Main.java
12345678910package com.example; public class Main { public static void main(String[] args) { String order = "Latte"; System.out.println(order.equalsIgnoreCase("LATTE")); } }
.equalsIgnoreCase() treats "Latte" and "LATTE" as identical and returns true.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat