- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Compare Two Strings
The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string.
- The result is a negative integer if this String object lexicographically precedes the argument string.
- The result is a positive integer if this String object lexicographically follows the argument string.
- The result is zero if the strings are equal, compareTo returns 0 exactly when the equals(Object) method would return true.
Example
import java.lang.*; public class StringDemo { public static void main(String[] args) { String str1 = "tutorials", str2 = "point"; // comparing str1 and str2 int retval = str1.compareTo(str2); // prints the return value of the comparison if (retval < 0) { System.out.println("str1 is greater than str2"); } else if (retval == 0) { System.out.println("str1 is equal to str2"); } else { System.out.println("str1 is less than str2"); } } }
Output
str1 is less than str2
- Related Articles
- Program to Compare two strings in Java
- Java Program to Compare two strings lexicographically
- Java Program to Compare Strings
- Golang program to compare two strings
- Compare two Strings in Java
- C++ Program to Compare two strings lexicographically
- Golang program to compare two strings lexicographically
- Compare two strings lexicographically in Java.
- Java Program to compare strings for equality
- Compare two Strings lexicographically in Java programming
- Compare the two Strings lexicographically in Java
- Golang Program to compare two strings by ignoring case
- Java Program to compare two sets
- How to compare two strings without case sensitive in Java
- Java Program to compare Two Java short Arrays

Advertisements