ADVERTISEMENT
ADVERTISEMENT

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.

ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.