Remove Duplicate Characters From a String in Java (BlueJ)

⚡ Direct Answer & Key Takeaway

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

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

VariableData TypeExam Purpose & Sample Value
scScannerReads input string from standard input (System.in)
inputStringOriginal user string to deduplicate, e.g. "PROGRAMMING"
resultStringBuilds unique-character string left to right, ending as "PROGAMIN"
lenintStores input.length() to bound the loop, e.g. 11
iintLoop index traversing characters from 0 to len - 1 (0..10)
chcharCurrent character input.charAt(i) checked via result.indexOf(ch), e.g. 'R'
🎯 1-on-1 Live Mentorship & Free Study Kit

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.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

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?
Add an extra check inside the loop: if (ch == ' ' || result.indexOf(ch) == -1) { result = result + ch; }. Whenever ch is a blank space, the left side of || evaluates to true and appends the space immediately without rejecting subsequent spaces between words, while all repeated letters are still filtered out cleanly.
What is the difference between removing duplicate characters and removing consecutive duplicates?
Removing all duplicate characters deletes repeats anywhere in the string, turning "BALLOON" into "BALON". Removing consecutive duplicates only collapses adjacent identical letters, turning "BALLOON" into "BALON" too, but keeping "PROGRAMMING" as "PROGRAMING" because the two 'R' and 'G' characters are separated. Always verify which exact variant your ICSE question paper asks.
Can StringBuilder replace String concatenation inside the duplicate-removal loop?
Yes, StringBuilder sb = new StringBuilder() avoids creating temporary String objects on each append, which improves efficiency on long inputs. You can check sb.indexOf(String.valueOf(ch)) == -1 and call sb.append(ch). In ICSE Class 10 exams, however, String result = "" with result.indexOf(ch) is simpler to dry-run, write, and fully accepted.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class