Java Program to Compare Two Strings Character by Character

You are currently viewing Java Program to Compare Two Strings Character by Character

In this article, I’m going to share the details about “Java Program to Compare Two Strings Character by Character”. Below, We can see the possibilities to perform this task successfully.

Java Program to Compare Two Strings Character by Character

app.java

//Java - Comparing two strings in Java character by character 
//(without using library method)

import java.util.Scanner;
 
class CompareStrings
{
    public static void main(String args[])
    {
        String str1=null;
        String str2=null;
        
        Scanner SC=new Scanner(System.in);
        
        System.out.print("Enter string1: ");
        str1=SC.nextLine();

        System.out.print("Enter string2: ");
        str2=SC.nextLine();     
        
        //compare strings
        if(str1.length()!=str2.length()){
            System.out.println("Strings are not same, lengths are different!!!");
            return;
        }
        
        boolean flg=true;
        for(int loop=0; loop<str1.length();loop++){
            if(str1.charAt(loop)!=str2.charAt(loop)){
                flg=false;
                break;
            }
        }
        
        if(flg){
            System.out.println("Strings are same.");
        }
        else{
            System.out.println("Strings are not same.");
        }
        
    }
}

Final Words

I hope this article helps you to learn “Java Program to Compare Two Strings Character by Character”. If you face any issues please let me know via the comment section. Share this article with other java program developers via social networks. Thank You!

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply