- 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
In how many ways can I compare Strings in Java explain with example?
We can compare Strings in Java using the compareTo() method and the == operator.
comapareTo() method − 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 == operator − You can compare two strings using == operator. But, it compares references of the given variables not values.
The equals() method of the String class accepts a String as parameter and it compares the current string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object
Example
public class Example { public static void main(String[] args) { String str1 = "tutorials", str2 = "point"; int retval = str1.compareTo(str2); Boolean bool = str1.equals(str2); System.out.println(bool); System.out.println(str1==str2); 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
false false str1 is less than str2
- Related Articles
- In how many ways we can concatenate Strings in Java?
- How do I compare strings in Java?
- How to compare strings in Java?
- How many ways a String object can be created in java?
- Compare two Strings in Java
- What is overriding in Java can explain briefly with an example?
- How to Initialize and Compare Strings in Java?
- How many ways can we read data from the keyboard in Java?
- Compare two strings lexicographically in Java.
- In how many ways you can retrieve the elements of a collection in Java?
- How many ways can get the instance of a Class class in Java?
- How can we compare a StringBuilder with StringBuffer in Java?
- Compare the two Strings lexicographically in Java
- Compare two Strings lexicographically in Java programming
- Program to Compare two strings in Java
