๐ WAYPOINT LESSON
== vs equals, and traversal
โญ beginnerโณ 12 min read๐ Lesson 26 of 256
Reference vs content comparison, compareTo ordering, three loop shapes.
The most exam-famous String trap:
String a = "cat";
String b = new String("cat");
System.out.println(a == b); // false! == compares references
System.out.println(a.equals(b)); // true โ content comparison
== asks "same object?"; .equals asks "same characters?". Always use
.equals for String content. (compareTo returns 0 exactly when equals
is true โ it also tells you ordering, which ==/equals cannot.)
Traversal patterns โ memorize all three, the exam cycles through them:
// 1. by index (when you need the position)
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
}
// 2. substring walk (when you need neighboring pieces)
for (int i = 0; i + 1 < s.length(); i++) {
String pair = s.substring(i, i + 2);
}
// 3. first-to-last scan with early exit
int pos = s.indexOf('x');
if (pos != -1) { /* found */ }
Concatenation builds new strings: "ab" + "cd", s + 42, 42 + s all work
โ numbers convert automatically.
โก Now practice
Ready to CodeString surgerySubstring math, traversal, reversal, property checks.
5 challenges ยท ยท ~50 min