Find Common Characters Between Two Strings in Java
Two strings may share some characters in common. Finding these common characters is a frequently asked Java string interview question.
In this program, we will compare two strings and print all characters that appear in both strings.
Understanding the Problem
Given two strings:
- Traverse characters of the first string.
- Compare each character with characters of the second string.
- If a character matches, it is a common character.
Example 1
Input: str1 = "java", str2 = "javascript"
Output: j a v
Example 2
Input: str1 = "abcd", str2 = "xyz"
Output: No common characters
Logic Explanation
- Use two nested loops.
- Pick one character from the first string.
- Compare it with every character of the second string.
- If both characters are equal, print it.
Java Program to Find Common Characters
import java.util.Scanner;
public class CommonCharacters {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = sc.nextLine();
System.out.print("Enter second string: ");
String str2 = sc.nextLine();
boolean found = false;
System.out.print("Common characters: ");
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
System.out.print(str1.charAt(i) + " ");
found = true;
break;
}
}
}
if (!found) {
System.out.print("None");
}
}
}
Sample Output
Enter first string: java
Enter second string: javascript
Common characters: j a v
Important Notes
- Comparison is case-sensitive.
- Duplicate common characters may be printed.
- Time complexity is O(n × m).
Practice Challenges
- Remove duplicate common characters.
- Ignore case sensitivity.
- Use HashSet to optimize the solution.
This problem strengthens your understanding of nested loops and character comparison in Java strings.