w3resource
Java Programming Exercies

Java String Exercises: Print after removing duplicates from a given string

Java String: Exercise-38 with Solution

Write a Java program to print after removing duplicates from a given string.

Pictorial Presentation:

Java String Exercises: Print after removing duplicates from a given string

Sample Solution:

Java Code:

import java.util.*;
public class Main {
 public static void main(String[] args) {
  String str1 = "w3resource";
  System.out.println("The given string is: " + str1);
  System.out.println("After removing duplicates characters the new string is: " + removeDuplicateChars(str1));
 }
 private static String removeDuplicateChars(String sourceStr) {
  char[] arr1 = sourceStr.toCharArray();
  String targetStr = "";
  for (char value: arr1) {
   if (targetStr.indexOf(value) == -1) {
    targetStr += value;
   }
  }
  return targetStr;
 }
}

Sample Output:

The given string is: w3resource
After removing duplicates characters the new string is: w3resouc

Flowchart:

Flowchart: Java String Exercises - Print after removing duplicates from a given string

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to find Length of the longest substring without repeating characters.
Next: Write a Java program to find first non repeating character in a string.

What is the difficulty level of this exercise?