Java String compareTo() examples

The Java String compareTo() method compares two strings lexicographically (alphabetical order). It returns a positive number, negative number, or zero. s1.compareTo(s2) if s1 < s2, it returns negative number. if s1 > s2, it returns positive number. if s1 == s2, it returns 0. Table of contents 1. "a".compareTo("c"), negative integer 2. "c".compareTo("a"), positive integer …

Read more

How to compare strings in Java

In Java, we use equals() to compare string value. String str1 = "apple"; // compare strings case-sensitive if (str1.equals("apple")) { System.out.println("I have an apple."); } String str2 = "apple"; // compare strings case-insensitive if (str2.equalsIgnoreCase("APPLE")) { System.out.println("I have an APPLE."); } Output Terminal I have an apple. I have an APPLE. In this article, we …

Read more