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

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

String.CompareTo() method – Here, you will learn how to compare two strings in java using String.CompareTo() method, which is a built-in method of String class.

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.

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. 

Java String Programs »

ADVERTISEMENT

ADVERTISEMENT