Bird
Raised Fist0
DSA Javaprogramming~10 mins

String Traversal and Character Access in DSA Java - Execution Trace

Choose your learning style10 modes available
Concept Flow - String Traversal and Character Access
Start: i = 0
↓
Check: i < length
Yes↓
Access char at i
↓
Process char
↓
Increment i
Back to Check↓
End
↩Back to Check
Start from the first character index 0, check if index is less than string length, access character, process it, then move to next index until all characters are visited.
Execution Sample
DSA Java
String s = "code";
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    System.out.print(c + "-");
}
This code goes through each character in the string "code" and prints each character followed by a dash.
Execution Table
StepiCondition i < lengthcharAt(i)Output
100 < 4 = True'c'c-
211 < 4 = True'o'o-
322 < 4 = True'd'd-
433 < 4 = True'e'e-
544 < 4 = FalseN/ALoop ends
💡 i reaches 4, condition 4 < 4 is False, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
i012344
cN/A'c''o''d''e'N/A
Key Moments - 3 Insights
Why does the loop stop when i equals the string length?
Because the condition i < length becomes false at i = 4 (string length), so the loop exits as shown in execution_table row 5.
What happens if we try to access charAt(i) when i equals the string length?
It causes an error because valid indices are 0 to length-1. The code avoids this by stopping the loop before i reaches length, as seen in the condition check in execution_table.
Why do we start i from 0 instead of 1?
String indices start at 0 in Java, so the first character is at index 0. This is shown in execution_table where i=0 accesses the first character 'c'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what character is accessed at step 3?
A'e'
B'o'
C'd'
D'c'
💡 Hint
Check the 'charAt(i)' column at step 3 in the execution_table.
At which step does the loop condition become false?
AStep 5
BStep 4
CStep 3
DStep 2
💡 Hint
Look at the 'Condition i < length' column to find when it becomes false.
If the string was "cat" instead of "code", what would be the output at step 2?
A't-'
B'a-'
C'c-'
D'o-'
💡 Hint
Check the character at index 1 for the string "cat".
Concept Snapshot
String Traversal and Character Access:
- Use a loop from i = 0 to i < string.length()
- Access each character with string.charAt(i)
- Process or print each character
- Stop when i reaches string length
- Indexing starts at 0, not 1
Full Transcript
This lesson shows how to go through each character in a string using a loop. We start with i = 0 and check if i is less than the string's length. If yes, we get the character at position i using charAt(i), then do something with it like print. We then increase i by 1 and repeat. When i equals the string length, the loop stops. This prevents errors from accessing characters outside the string. The example uses the string "code" and prints each character followed by a dash. The output is c-o-d-e-. This method works for any string and is a basic way to read characters one by one.

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