Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
90 views
in JAVA by (176k points)
Explain Java String compareTo() Method

Please log in or register to answer this question.

1 Answer

0 votes
by (176k points)

Java String compareTo() method compares two strings lexicographically. It compares the characters of two strings one by one, starting from the first character. If the first character of the first string is less than the first character of the second string, then compareTo() method returns a negative integer. If the first character of the first string is greater than the first character of the second string, then compareTo() method returns a positive integer. If the first characters of both strings are equal, then compareTo() method moves to the next characters and continues the comparison until it reaches the end of one of the strings.

The syntax of the compareTo() method is as follows:

public int compareTo(String str)
 

Here, str is the string to be compared with the current string.

The compareTo() method returns an integer value that indicates the lexicographic relation between the two strings. If the current string is lexicographically greater than the argument string, then a positive integer is returned. If the current string is lexicographically less than the argument string, then a negative integer is returned. If the two strings are equal, then the method returns 0.

Here's an example:

String str1 = "hello";
String str2 = "world";
int result = str1.compareTo(str2);
if (result < 0) {
    System.out.println("str1 is less than str2");
} else if (result > 0) {
    System.out.println("str1 is greater than str2");
} else {
    System.out.println("str1 and str2 are equal");
}
 

In this example, str1 is compared with str2 using the compareTo() method. Since str1 is lexicographically less than str2, the method returns a negative integer, and the output will be "str1 is less than str2".

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...