Q:

Java program to compare two strings using String.compareTo() method

belongs to collection: Java String Programs

0

String.CompareTo()

This is a predefined (build-in) method of string class in Java, it returns 0 if both strings are same otherwise it will return difference of first dissimilar characters.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

Given two strings (Input strings) and we have to compare them using String.compareTo() method.

import java.util.*;

class CompareStrings
{
	public static void main(String args[])
	{
		//declaring two string objects
		String str1,str2;
		//declaring input stream object 
		Scanner in = new Scanner(System.in);

		//input strings
		System.out.print("Enter first string: ");
		str1 = in.nextLine();
		System.out.print("Enter second string: ");
		str2 = in.nextLine();

		//comparing strings 
		if(str1.compareTo(str2)==0)
			System.out.println("Strings are equal.");
		else
			System.out.println("Strings are not equal.");
	}
}

Output

Complie: javac CompareStrings.java
Run: java CompareStrings

Output

Enter first string: Hello World!
Enter second string: Hello World!
Strings are equal. 

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to input a string from user and rever... >>
<< Java program to convert any type of value to strin...