Frequently Asked Java Programs 31 – Java Program to Find Common Characters in Two Given Strings

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program Find Common Characters in Two Given Strings.

Problem Statement:-

String s1= “ABCDEF”

String s2= “DEFXYZ”

Output: DEF

Solution:-

This problem can be solved with or without using collection concepts in Java. I will explain both solutions here because in interview, you could be asked in any ways.

Without Collection Concept:-

  1. We need to iterate char by char a given string with smaller length.
  2. Take the first char of a string say S1 and check if String say S2 contains that char. If yes, store in another resultant String. Repeat the same process for each char of S1.
  3. After completion of iteration, resultant string will have common characters in both Strings.

Java Program:

Output:-

Please enter the first string
ABC
Please enter the second string
ABCDEF
String to be iterated: ABC
String to be checked: ABCDEF
Output is :ABC
======================================================

Please enter the first string
selenium
Please enter the second string
winium
String to be iterated: winium
String to be checked: selenium
Output is :inium

With Collection Concept:-

  1. Create a Collection List of given Strings.
  2. Find the intersection of both the lists. Intersection will be common characters.

Java Program:

Output:

Please enter the first string
abcdef
Please enter the second string
abc
Output is :abc

You can run above program for multiple inputs and if it fails for any condition, let me know.

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.
%d bloggers like this: