Here is a small exercise that combines .length() and .charAt(). Write a program that counts how many times the letter a appears in a given string.
String text = "banana";
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == 'a') {
count++;
}
}
System.out.println(count);
This prints . The loop visits each index from to text.length() - 1. At each position, it checks whether the character is a and increments the counter if so.
Notice that you compare characters with ==, not .equals(). A char is a primitive type, so == works correctly here. Try modifying this to count a different character, or to accept user input for the target character.