How to Initialize and Compare Strings in Java?



You can compare Strings using compareTo() method or, equals() method or, or == operator. Following example demonstrates how to initialize and compare strings in Java.

Example

Live Demo
 public class StringDemo { public static void main(String[] args) { String str1 = "tutorials"; String 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 
Updated on: 2019-07-30T22:30:21+05:30

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements