about | help
CodingBat code practice

Code Help and Videos >

 Java String Equals and Loops

String Equals

Use the equals() method to check if 2 strings are the same. The equals() method is case-sensitive, meaning that the string "HELLO" is considered to be different from the string "hello". The == operator does not work reliably with strings. Use == to compare primitive values such as int and char. Unfortunately, it's easy to accidentally use == to compare strings, but it will not work reliably. Remember: use equals() to compare strings. There is a variant of equals() called equalsIgnoreCase() that compares two strings, ignoring uppercase/lowercase differences.

String a = "hello";
String b = "there";

if (a.equals("hello")) {
  // Correct -- use .equals() to compare Strings
}

if (a == "hello") {
  // NO NO NO -- do not use == with Strings
}

// a.equals(b) -> false
// b.equals("there") -> true
// b.equals("There") -> false
// b.equalsIgnoreCase("THERE") -> true

String For Loop

for (int i = 0; i < str.length(); i++) {
  // do something at index i
}

CodingBat Practice> countXX

More practice problems

CodingBat.com code practice. Copyright 2012 Nick Parlante.