- 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 string using compareTo() method
The compareTo(obj) method compares this String to another Object.The value 0 is returned if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.
We have the following two strings −
String str1 = "tom"; String str2 = "tim";
Let us check them for all the return values.
if(str1.compareTo(str2) > 0) { System.out.println("First string is greater!"); } if(str1.compareTo(str2) == 0) { System.out.println("First string is equal to Second string!"); } if(str1.compareTo(str2) < 0) { System.out.println("Second string is greater!"); }
The following is the final example.
Example
public class Demo { public static void main(String[] args) { String str1 = "tom"; String str2 = "tim"; if(str1.compareTo(str2) > 0) { System.out.println("First string is greater!"); } if(str1.compareTo(str2) == 0) { System.out.println("First string is equal to Second string!"); } if(str1.compareTo(str2) < 0) { System.out.println("Second string is greater!"); } } }
Output
First string is greater!
Let us see another example.
Example
public class Demo { public static void main(String[] args) { String one = "This is demo text!"; String two = new String("This text is for demo!"); String three = new String("This is demo line!"); String four = new String("The line is demo!"); int res = one.compareTo( two ); System.out.println(res); res = one.compareTo( three ); System.out.println(res); res = one.compareTo( four ); System.out.println(res); } }
Output
-11 8 4
- Related Articles
- String compare by compareTo() method in Java
- Java String compareTo() method
- Java String compareTo() Method example.
- How does the Java compareTo() method, compare strings?
- Java Integer compareTo() method
- IntBuffer compareTo() method in Java
- FloatBuffer compareTo() method in Java
- DoubleBuffer compareTo() method in Java
- ShortBuffer compareTo() method in Java
- ByteBuffer compareTo() method in Java
- CharBuffer compareTo() method in Java
- Duration compareTo() method in Java
- LocalTime compareTo() method in Java
- MonthDay compareTo() method in Java
- LocalDateTime compareTo() method in Java

Advertisements