Mental Model
A string is a sequence of characters you can look at one by one from start to end.
Analogy: Imagine reading a sentence letter by letter from left to right to understand or find something.
"H" -> "e" -> "l" -> "l" -> "o" -> null ↑
"H" -> "e" -> "l" -> "l" -> "o" -> null ↑
"H" -> "e" -> "l" -> "l" -> "o" -> null ↑
"H" -> "e" -> "l" -> "l" -> "o" -> null ↑
"H" -> "e" -> "l" -> "l" -> "o" -> null
↑"H" -> "e" -> "l" -> "l" -> "o" -> null
↑"H" -> "e" -> "l" -> "l" -> "o" -> null
↑Printed characters: H e l l o Final string traversal complete
public class StringTraversal { public static void traverseString(String input) { for (int i = 0; i < input.length(); i++) { char currentChar = input.charAt(i); // access character at index i System.out.println(currentChar); // print current character } System.out.println("Final string traversal complete"); } public static void main(String[] args) { String testString = "Hello"; traverseString(testString); } }
char currentChar = input.charAt(i); // access character at index iSystem.out.println(currentChar); // print current characterfor (int i = 0; i < input.length(); i++) {for (int i = 0; i < input.length(); i++) {
for (int i = 0; i < input.length(); i++) {
charAt() method do when used on a Java String?charAt()charAt() method is designed to access a single character at a given index in a string.length() return the string length, toUpperCase() changes case, and split() divides the string. These are different from charAt().charAt() = character access [OK]str in Java?i < str.length(), which correctly stops before index equals length. Options B and D use <= which causes out-of-bounds error. Options C and D start at 1, skipping first character.String s = "hello";
for (int i = 0; i < s.length(); i++) {
if (i % 2 == 0) {
System.out.print(s.charAt(i));
}
}String text = "abc";
for (int i = 0; i <= text.length(); i++) {
System.out.print(text.charAt(i));
}
What error will occur when running this code?charAt(3) is called, which is out of string bounds, causing StringIndexOutOfBoundsException.input = "a1b2c3d4", which code snippet correctly extracts and prints only the digits in order?Character.isLetter(), prints letters. for (int i = 0; i < input.length(); i++) { if (input.charAt(i) >= 'a' && input.charAt(i) <= 'z') System.out.print(input.charAt(i)); } checks lowercase letters range, prints letters. for (int i = 0; i < input.length(); i++) { System.out.print(input.charAt(i)); } prints all characters. for (int i = 0; i < input.length(); i++) { if (input.charAt(i) >= '0' && input.charAt(i) <= '9') System.out.print(input.charAt(i)); } checks if char between '0' and '9', prints "1234" correctly.Pass the test and this pattern moves unknown