Bird
Raised Fist0
DSA Javaprogramming

String Traversal and Character Access in DSA Java

Choose your learning style10 modes available
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
 ↑
Dry Run Walkthrough
Input: string: "Hello", print each character in order
Goal: Print each character one by one from the string
Step 1: Access character at index 0
"H" -> "e" -> "l" -> "l" -> "o" -> null
 ↑
Why: Start from the first character to begin traversal
Step 2: Print character 'H'
"H" -> "e" -> "l" -> "l" -> "o" -> null
   ↑
Why: Output the current character before moving on
Step 3: Move to index 1 and access character
"H" -> "e" -> "l" -> "l" -> "o" -> null
     ↑
Why: Advance to next character to continue traversal
Step 4: Print character 'e'
"H" -> "e" -> "l" -> "l" -> "o" -> null
       ↑
Why: Output the current character
Step 5: Repeat for indices 2, 3, 4 printing 'l', 'l', 'o'
"H" -> "e" -> "l" -> "l" -> "o" -> null
             ↑
Why: Continue until all characters are printed
Result:
Printed characters: H
e
l
l
o
Final string traversal complete
Annotated Code
DSA Java
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 i
access character at current index to process it
System.out.println(currentChar); // print current character
output the character to show traversal progress
for (int i = 0; i < input.length(); i++) {
loop through each character index from start to end
OutputSuccess
H e l l o Final string traversal complete
Complexity Analysis
Time: O(n) because we visit each character once where n is string length
Space: O(1) because we only store one character at a time during traversal
vs Alternative: Compared to copying the string or using extra data structures, this direct access is more efficient in space and time
Edge Cases
empty string ""
loop does not run, no characters printed, just final message
DSA Java
for (int i = 0; i < input.length(); i++) {
string with one character "A"
prints single character then final message
DSA Java
for (int i = 0; i < input.length(); i++) {
When to Use This Pattern
When you need to process or examine each character in a string one by one, use string traversal with character access.
Common Mistakes
Mistake: Using index out of bounds by looping beyond string length
Fix: Ensure loop condition uses input.length() as upper bound, not greater
Mistake: Trying to modify characters directly in string (strings are immutable)
Fix: Use a new string or character array if modification is needed
Summary
It goes through each character in a string one by one.
Use it when you want to read or process every letter in a word or sentence.
Remember strings are like a row of boxes you open one at a time from left to right.

Practice

(1/5)
1. What does the charAt() method do when used on a Java String?
easy
A. Returns the character at a specified index in the string
B. Returns the length of the string
C. Converts the string to uppercase
D. Splits the string into an array of substrings

Solution

  1. Step 1: Understand the purpose of charAt()

    The charAt() method is designed to access a single character at a given index in a string.
  2. Step 2: Compare with other string methods

    Methods like length() return the string length, toUpperCase() changes case, and split() divides the string. These are different from charAt().
  3. Final Answer:

    Returns the character at a specified index in the string -> Option A
  4. Quick Check:

    charAt() = character access [OK]
Hint: Remember: charAt gets one character by index [OK]
Common Mistakes:
  • Confusing charAt() with length()
  • Thinking charAt() splits the string
  • Assuming charAt() changes string case
2. Which of the following is the correct way to loop through each character of a string str in Java?
easy
A. for (int i = 1; i < str.length(); i++) { char c = str.charAt(i); }
B. for (int i = 0; i <= str.length(); i++) { char c = str.charAt(i); }
C. for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); }
D. for (int i = 1; i <= str.length(); i++) { char c = str.charAt(i); }

Solution

  1. Step 1: Understand string indexing in Java

    String indices start at 0 and go up to length - 1. So loop must run from 0 to less than length.
  2. Step 2: Check loop conditions

    for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); } uses 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.
  3. Final Answer:

    for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); } -> Option C
  4. Quick Check:

    Loop from 0 to length-1 [OK]
Hint: Loop from 0 to length-1 for string indices [OK]
Common Mistakes:
  • Using <= instead of < causing index error
  • Starting loop at 1 skipping first char
  • Confusing string length with last index
3. What is the output of the following Java code?
String s = "hello";
for (int i = 0; i < s.length(); i++) {
  if (i % 2 == 0) {
    System.out.print(s.charAt(i));
  }
}
medium
A. hello
B. hlo
C. el
D. heo

Solution

  1. Step 1: Identify loop and condition

    The loop runs from i=0 to 4 (length 5). It prints characters only when i is even (0,2,4).
  2. Step 2: Find characters at even indices

    Index 0: 'h', Index 2: 'l', Index 4: 'o'. These characters are printed in order.
  3. Final Answer:

    hlo -> Option B
  4. Quick Check:

    Even indices chars = hlo [OK]
Hint: Print chars at even indices only [OK]
Common Mistakes:
  • Printing all characters ignoring condition
  • Confusing even and odd indices
  • Off-by-one errors in loop
4. Consider this Java code snippet:
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?
medium
A. StringIndexOutOfBoundsException
B. ArrayIndexOutOfBoundsException
C. NullPointerException
D. No error, prints 'abc'

Solution

  1. Step 1: Analyze loop bounds

    The loop runs from i=0 to i=3 (because of <= and length=3). Valid indices are 0,1,2 only.
  2. Step 2: Identify error cause

    At i=3, charAt(3) is called, which is out of string bounds, causing StringIndexOutOfBoundsException.
  3. Final Answer:

    StringIndexOutOfBoundsException -> Option A
  4. Quick Check:

    charAt index out of range causes StringIndexOutOfBoundsException [OK]
Hint: Loop must use < length, not <= length [OK]
Common Mistakes:
  • Confusing StringIndexOutOfBoundsException with ArrayIndexOutOfBoundsException
  • Assuming no error occurs
  • Thinking NullPointerException will happen
5. Given the string input = "a1b2c3d4", which code snippet correctly extracts and prints only the digits in order?
hard
A. for (int i = 0; i < input.length(); i++) { if (Character.isLetter(input.charAt(i))) System.out.print(input.charAt(i)); }
B. for (int i = 0; i < input.length(); i++) { if (input.charAt(i) >= 'a' && input.charAt(i) <= 'z') System.out.print(input.charAt(i)); }
C. for (int i = 0; i < input.length(); i++) { System.out.print(input.charAt(i)); }
D. for (int i = 0; i < input.length(); i++) { if (input.charAt(i) >= '0' && input.charAt(i) <= '9') System.out.print(input.charAt(i)); }

Solution

  1. Step 1: Understand the goal

    We want to print only digits from the string, ignoring letters.
  2. Step 2: Check each option's condition

    for (int i = 0; i < input.length(); i++) { if (Character.isLetter(input.charAt(i))) System.out.print(input.charAt(i)); } uses 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.
  3. Final Answer:

    for (int i = 0; i < input.length(); i++) { if (input.charAt(i) >= '0' && input.charAt(i) <= '9') System.out.print(input.charAt(i)); } -> Option D
  4. Quick Check:

    Check char between '0' and '9' to find digits [OK]
Hint: Check if char is between '0' and '9' for digits [OK]
Common Mistakes:
  • Printing letters instead of digits
  • Printing all characters without filtering
  • Using wrong character range for digits
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard