1. Reference vs content comparison
In Java, strings are objects, not primitives. When you write variables a and b, they can point to the same string in the string pool. But c, created via a constructor, is a different object. The == operator compares references, not text.
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b); // true (most likely an interned string)
System.out.println(a == c); // false (different objects)
Demonstration of the mistake
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2); // false
Although the strings look the same, they are different objects in memory.
2. equals(): comparing string contents
To compare the actual contents, use the equals() method — it compares strings character by character (case-sensitive).
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1.equals(s2)); // true
Example: password comparison
String inputPassword = "Secret123";
String realPassword = "Secret123";
if (inputPassword.equals(realPassword))
{
System.out.println("Access granted!");
}
else
{
System.out.println("Incorrect password.");
}
Important!
If at least one object is null, calling equals() will result in a NullPointerException. Safe idiom:
if ("something".equals(someString)) { ... }
3. equalsIgnoreCase(): case-insensitive comparison
When you need to ignore case (for example, user input), use equalsIgnoreCase().
String name1 = "Ivan";
String name2 = "ivan";
System.out.println(name1.equalsIgnoreCase(name2)); // true
Example: comparing email addresses
String email1 = "User@Example.com";
String email2 = "user@example.com";
if (email1.equalsIgnoreCase(email2))
{
System.out.println("Emails match!");
}
In short: equals vs equalsIgnoreCase
| Method | Case-sensitive? | Example "Java" vs "java" |
|---|---|---|
|
Yes | |
|
No | |
4. compareTo(): lexicographic string comparison
The compareTo() method performs lexicographic (dictionary) comparison. It returns a negative number if the first string is “less”, 0 if equal, and a positive number if “greater”.
System.out.println("apple".compareTo("banana")); // < 0
System.out.println("apple".compareTo("apple")); // 0
System.out.println("banana".compareTo("apple")); // > 0
a.compareTo(b) →
< 0 — if a comes before b
0 — if equal
> 0 — if a comes after b
compareTo()
How does it work?
- Comparison goes left to right by Unicode code points of characters.
- At the first difference, it returns the difference of the character codes.
- If one string is a prefix of the other, the shorter one is “less”.
System.out.println("cat".compareTo("catalog")); // < 0 ("cat" is shorter)
System.out.println("catalog".compareTo("cat")); // > 0
Example: sorting an array of strings
String[] fruits = {"banana", "apple", "pear"};
Arrays.sort(fruits); // compareTo() is used internally
System.out.println(Arrays.toString(fruits)); // [apple, banana, pear]
compareToIgnoreCase()
System.out.println("Java".compareToIgnoreCase("java")); // 0
5. The startsWith() and endsWith() methods
The startsWith() and endsWith() methods check the beginning and end of a string, returning true/false.
String fileName = "document.pdf";
String url = "https://www.google.com";
System.out.println(fileName.startsWith("doc")); // true
System.out.println(fileName.endsWith(".txt")); // false
System.out.println(url.startsWith("https://")); // true
Why this is useful: validating formats (file names, URLs) and filtering by prefixes/suffixes (e.g., all ".jpg").
6. contains(): searching for a substring
contains(CharSequence s) is a simple way to check for a substring. It is case-sensitive.
String text = "Welcome to the world of Java!";
System.out.println(text.contains("world")); // true
System.out.println(text.contains("C++")); // false
To ignore case, convert both strings to the same case: toLowerCase()/toUpperCase().
7. The toLowerCase() and toUpperCase() methods
They return a new string converted to lower or upper case. Useful for case-insensitive comparison and formatting.
String title = "Java Programming";
String lower = title.toLowerCase();
String upper = title.toUpperCase();
System.out.println(lower); // java programming
System.out.println(upper); // JAVA PROGRAMMING
8. split(): splitting a string into parts
split(String regex) splits a string by a delimiter (regular expression) and returns a String[] array.
Example 1: by commas
String names = "Alex,Maria,Ivan,Elena";
String[] nameArray = names.split(",");
for (String name : nameArray)
{
System.out.println(name.trim()); // trim() removes possible spaces
}
// Output:
// Alex
// Maria
// Ivan
// Elena
Example 2: by spaces
String sentence = "I study Java";
String[] words = sentence.split(" ");
for (String word : words)
{
System.out.println(word);
}
// Output:
// I
// study
// Java
Details:
- The delimiter is a regex. You must escape special characters (for example, dot: "\\.").
- The method always returns an array, even if there is only one element.
9. Practice: comparing strings in a real application
String registeredEmail = "user@example.com";
String registeredPassword = "Secret123";
Scanner console = new Scanner(System.in);
System.out.print("Enter email: ");
String email = console.nextLine();
System.out.print("Enter password: ");
String password = console.nextLine();
// Compare email case-insensitively, but password case-sensitively
if (email.equalsIgnoreCase(registeredEmail) && password.equals(registeredPassword))
{
System.out.println("Welcome!");
}
else
{
System.out.println("Invalid email or password.");
}
Notes: use equalsIgnoreCase() for email and strict equals() for password. Do not use == for strings — it compares references.
10. Common mistakes when comparing strings
Mistake #1: Comparing strings with == instead of equals()
The == operator compares references, not content, so the result may be unexpected.
Mistake #2: Calling equals() on an object that may be null
Call the method on a known non-null object or use Objects.equals(a, b).
Mistake #3: Ignoring case when it matters
For example, passwords must be compared case-sensitively. Clarify the requirements.
Mistake #4: Comparing strings with objects of other types
"123" and 123 are not the same. equals() does not coerce types automatically.
Mistake #5: Sorting strings with mixed case
Uppercase letters come before lowercase. For case-insensitive sorting, use Arrays.sort(array, String.CASE_INSENSITIVE_ORDER).
GO TO FULL VERSION