Java Program to Compare Two Strings Character by Character Full Example Project For Beginners

 

Welcome folks today in this blog post we will be comparing two strings character by character in java. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to make an app.py file and copy paste the following code

 

 

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.");
        }
        
    }
}

Leave a Reply