Removing duplicate characters from a Java string while preserving original order requires scanning each character left to right and checking whether it already exists in an initially empty result string. Using result.indexOf(ch) == -1, only unseen characters get appended to result, while repeats are skipped automatically. This single-pass approach handles letters, digits, and symbols cleanly without sorting away the original sequence—exactly as ICSE board questions expect.
- 1. How indexOf() Tracks Seen Characters Without Extra Arrays
- 2. Step-by-Step Trace on Input "PROGRAMMING"
- 3. Comparing indexOf(), Boolean Seen Array, and Nested Loops
- 4. RemoveDuplicateChars.java (BlueJ / ICSE Section B)
- 5. CISCE Variable Description Table (VDT) & Dry Run
- 6. Common Mistakes & Top Scorer Tips
- 7. Interactive Concept Check Quiz
- 8. Frequently Asked Questions
1. How indexOf() Tracks Seen Characters Without Extra Arrays
In Java, String.indexOf(char ch) searches a string from index 0 and returns the position of the first match, or -1 when the character is absent. By initializing an empty accumulator String result = "", every character ch = input.charAt(i) can be tested with if (result.indexOf(ch) == -1). When -1 is returned, ch has never appeared before, so result += ch appends it at the end, naturally keeping the first-occurrence sequence intact. Unlike a nested loop that compares every pair of indices, indexOf() hides the inner scan in one clean, readable board-friendly expression. Spaces are preserved once or skipped altogether depending on whether you add a ch != ' ' condition.
- Initialize result to "" (empty string) rather than " ", or a stray leading space will corrupt the check.
- Remember that indexOf() is case-sensitive: 'A' and 'a' have distinct ASCII values (65 vs 97).
- For case-insensitive deduplication, convert the input using toLowerCase() or toUpperCase() beforehand.
2. Step-by-Step Trace on Input "PROGRAMMING"
Walking through "PROGRAMMING" (length 11) shows exactly why indexOf() never drops an original letter. At i = 0, ch is 'P'; "".indexOf('P') returns -1, so result becomes "P". Indices 1, 2, and 3 append 'R', 'O', and 'G', bringing result to "PROG". At i = 4, ch is 'R', and "PROG".indexOf('R') returns 1 (not -1), so the second 'R' is skipped. Indices 5 and 6 add 'A' and 'M', yielding "PROGAM". Then at i = 7, 'M' returns 5 and gets skipped. Indices 8, 9, and 10 append 'I', 'N', and ignore the duplicate 'G'. The loop finishes cleanly with "PROGAMIN".
- Every skipped letter satisfies result.indexOf(ch) >= 0, never altering result.
- Notice that result grows only when unique characters appear, at most 26 times for uppercase letters.
- If the prompt asks to remove ONLY consecutive duplicates (like "AAABBC" -> "ABC"), compare ch != result.charAt(result.length() - 1) instead.
3. Comparing indexOf(), Boolean Seen Array, and Nested Loops
Students sometimes ask which deduplication technique earns highest marks in ICSE exams. All three standard methods—indexOf(), a boolean[256] frequency flag array, and a nested loop scanning 0 to i - 1—produce the exact same output when coded accurately. The indexOf() pattern shines in Section B because it needs zero extra array indices, stays under ten lines inside main(), and never risks ArrayIndexOutOfBoundsException on Unicode symbols. A boolean[] lookup array runs faster on huge strings by mapping (int) ch directly to true after first sight, though it assumes ASCII characters below 256. Avoid sorting characters first unless the question specifically discards original ordering.
- Never confuse removing ALL duplicates ("PROGRAMMING" -> "PROGAMIN") with removing ONLY adjacent repeats.
- Check whether spaces should be kept or stripped if the user enters a multi-word phrase.
- Always echo both original string and final unique string clearly in the output.
4. RemoveDuplicateChars.java (BlueJ / ICSE Section B)
import java.util.*;
public class RemoveDuplicateChars {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word or string: ");
String input = sc.nextLine();
String result = "";
int len = input.length();
for (int i = 0; i < len; i++) {
char ch = input.charAt(i);
// Append character only if it has not appeared earlier in result
if (result.indexOf(ch) == -1) {
result = result + ch;
}
}
System.out.println("Original String : " + input);
System.out.println("Without Duplicates: " + result);
sc.close();
}
}
Verified Console / Dry-Run Output:
Enter a word or string: PROGRAMMING
Original String : PROGRAMMING
Without Duplicates: PROGAMIN
5. CISCE Variable Description Table (VDT) & Dry Run
| Variable | Data Type | Exam Purpose & Sample Value |
|---|---|---|
| sc | Scanner | Reads input string from standard input (System.in) |
| input | String | Original user string to deduplicate, e.g. "PROGRAMMING" |
| result | String | Builds unique-character string left to right, ending as "PROGAMIN" |
| len | int | Stores input.length() to bound the loop, e.g. 11 |
| i | int | Loop index traversing characters from 0 to len - 1 (0..10) |
| ch | char | Current character input.charAt(i) checked via result.indexOf(ch), e.g. 'R' |
Sharpen String Index Logic with 1-on-1 ICSE Java Coaching
Get personalized BlueJ walkthroughs on indexOf(), character frequencies, and Section B VDT tables so string manipulation programs never cost you silly marks.
6. Common Mistakes & Top Scorer Tips
- Avoid Mistake: Checking input.indexOf(ch) == i without realizing ch gets dropped or misordered if you mistakenly overwrite input mid-loop.
- Avoid Mistake: Writing if (result.indexOf(ch) == 0) instead of == -1, which keeps duplicates of every letter except the very first character.
- Avoid Mistake: Using sc.next() when the exam test case contains spaces, silently discarding everything after the first word.
- Examiner / Mentor Tip: In Section A MCQs, remember "MISSISSIPPI".indexOf('S') returns 2 (first occurrence), whereas lastIndexOf('S') returns 6.
- Examiner / Mentor Tip: Mention explicitly in a comment that indexOf(ch) == -1 checks whether ch is absent from result.
- Examiner / Mentor Tip: If a question specifies case-insensitivity ('A' and 'a' treated as duplicates), test result.toLowerCase().indexOf(Character.toLowerCase(ch)) == -1.
7. Interactive Concept Check Quiz
Question: If input is "BANANA", what is the value of result after completing if (result.indexOf(ch) == -1) result += ch;?
8. Frequently Asked Questions
How do you keep spaces untouched while removing duplicate letters in Java?
What is the difference between removing duplicate characters and removing consecutive duplicates?
Can StringBuilder replace String concatenation inside the duplicate-removal loop?
Explore Related Lessons & Free Interactive Tools
- All 110 Guides in ICSE Java BlueJ Library
- Reverse Each Word in a Sentence in Java (Without Reversing Word Order)
- Count Double Letter Sequences in Java (ICSE RABBIT / SHEEP Problem)
- Check Magic String in Java (Consecutive Alphabetical Letters Like AB)
- Interactive Tool: ICSE Class 10 Java BlueJ Output Quiz
- Interactive Tool: ICSE Variable Description Table (VDT) Auto-Formatter
