Find Common Characters Between Two Strings in Java — Logic, Examples and Program

Learn how to find common characters between two strings in Java using simple logic, nested loops, and without using advanced data structures.

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:

Example 1

Input: str1 = "java", str2 = "javascript"

Output: j a v

Example 2

Input: str1 = "abcd", str2 = "xyz"

Output: No common characters

Logic Explanation

  1. Use two nested loops.
  2. Pick one character from the first string.
  3. Compare it with every character of the second string.
  4. 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

Practice Challenges

  1. Remove duplicate common characters.
  2. Ignore case sensitivity.
  3. Use HashSet to optimize the solution.

This problem strengthens your understanding of nested loops and character comparison in Java strings.