4.4 String Search and Comparison
Strings are objects, so compare their contents with methods. Do not use == to decide whether two user-facing strings have the same text.
String a = new String("java");
String b = new String("java");
System.out.println(a == b); // false: different objects
System.out.println(a.equals(b)); // true: same textequals(other)
equals(other) returns true when two strings contain exactly the same characters in the same order.
"Java".equals("Java"); // true
"Java".equals("java"); // falseThis is the normal method for checking passwords, commands, menu choices, and exact labels.
equalsIgnoreCase(other)
equalsIgnoreCase(other) compares text while ignoring uppercase/lowercase differences.
"YES".equalsIgnoreCase("yes"); // trueThis is useful when accepting commands such as yes, YES, or Yes.
compareTo(other)
compareTo(other) compares two strings in dictionary-like order.
"apple".compareTo("banana"); // negative
"cat".compareTo("cat"); // 0
"dog".compareTo("cat"); // positiveThe exact positive or negative number is less important than its sign:
- Negative: the left string comes before the right string.
- Zero: the two strings are equal.
- Positive: the left string comes after the right string.
contains(part)
contains(part) checks whether a substring appears anywhere inside the string.
"error: timeout".contains("error"); // trueIt returns a boolean, not the position.
startsWith(prefix) and endsWith(suffix)
startsWith(prefix) checks the beginning of a string. endsWith(suffix) checks the end.
"Report.java".endsWith(".java"); // true
"Report.java".startsWith("Test"); // falseThese methods are helpful for file extensions, command prefixes, and simple validation.
indexOf(part) and lastIndexOf(part)
indexOf(part) returns the first position where a substring appears. If it does not appear, the result is -1.
String line = "error warning error";
System.out.println(line.indexOf("error")); // 0
System.out.println(line.lastIndexOf("error")); // 14
System.out.println(line.indexOf("debug")); // -1Use contains() when you only need yes/no. Use indexOf() when the position matters.