Home » Java solved programs

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

This an example of Java string programs, In this code snippet/program we will learn how to compare two string character by character without using any string library method?

In this program, we will read two strings using Scanner class and compare them character by character without using any String library method in java.

Java Code - Compare Two Strings Character by Character

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

    First Run:
    Enter string1: Hello World
    Enter string2: Hello World
    Strings are same.

    Second Run:
    Enter string1: Hello World
    Enter string2: Hello
    Strings are not same, lengths are different!!!

    Third Run:
    Enter string1: Hello World
    Enter string2: HELLO WORLD
    Strings are not same.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.