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

Learn how to find common characters between two strings in Java using simple logic and character comparison without using advanced collections.

Find Common Characters Between Two Strings in Java

Finding common characters between two strings means identifying characters that appear in both strings.

This problem is frequently asked in interviews and helps strengthen string traversal, nested loops, and logical filtering.

Understanding the Problem

Given two strings:

Example 1

Input:

Output: g m i n

Example 2

Input:

Output: l o

Logic Explanation

  1. Traverse the first string character by character.
  2. For each character, check if it exists in the second string.
  3. Ensure the character has not already been printed.
  4. Print only unique common characters.

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();

        System.out.print("Common characters: ");

        for (int i = 0; i < str1.length(); i++) {
            char ch = str1.charAt(i);

            // Skip already processed characters
            if (str1.indexOf(ch) != i) {
                continue;
            }

            for (int j = 0; j < str2.length(); j++) {
                if (ch == str2.charAt(j)) {
                    System.out.print(ch + " ");
                    break;
                }
            }
        }
    }
}

Sample Output


Enter first string: programming
Enter second string: gaming
Common characters: g m i n

Important Notes

Practice Challenges

  1. Print common characters ignoring case.
  2. Count the number of common characters.
  3. Find common characters using frequency arrays.

This problem improves understanding of nested loops and string comparison logic in Java.