What is String in Java?

Strings in Java are Objects that are backed internally by a char array. Strings are immutable. Whenever a change to a String is made, a brand new String is created.

The class String includes methods for examining individual characters of the sequence, comparing strings, searching strings, extracting substrings, and creating a copy of a string with all characters translated to uppercase or to lowercase.

The case mapping for each String is based on the Unicode Standard version specified by the Character class.

What is the string compareTo() method in Java?

In Java String, the compareTo() method compares two strings in alphabetical order. The comparison is based on the Unicode value of each character present in the strings.

and it returns the results as positive, negative, and zero. Depending on this output we can decide if the given Strings are equal or not.

if str1 and str2 are 3 strings and

we are using the compareTo() method to compare both Strings then.

  • if if str1 < str2, it returns negative number.=> str1 is smaller than str2.
  • if str1 > str2, it returns positive number. => str1 is greater than str2.
  • if str1 == str2, it returns 0 => b0th Strings are equal.

Syntax:

public int compareToIgnoreCase(String str)

Compares two strings lexicographically, ignoring case differences. it returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase(character) and Character.toUpperCase(character)) on each character.

This method throws ClassCastException If this object cannot get compared with the specified object and throws NullPointerException if the specified object is null.

This method is introduced in the jdk 1.2 version.

StringCompareToExample.java

package com.asyncster.string.examples;

public class StringCompareToExample {
	public static void main(String args[]) {
		
		String str1 = "Welcome";
		String str2 = "WELCOME";
		String str3 = "Welcome";
		String str4 = "welcome";

		System.out.println(str1.compareTo(str2));// 32 str2 is grater than str1 
		System.out.println(str1.compareTo(str3)); //0  both are equals
		System.out.println(str1.compareTo(str4)); //-32  str1 is grater than str2

	}
}

output:

output:
32
0
-32

Important points for String’s compareTo() method

  • The compareTo() method returns a negative number if the first String is null or empty.
  • The compareTo() method returns a positive number if Second String is null or empty.

The internal implementation for compareToMethod is given Below.

   public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

String compareTo() method without case sensitive – compareToIgnoreCase()

compareToIgnoreCase()

The Java String compareToIgnoreCase() method compares two strings alphabetically, It will ignore the lower case and upper case of the given String.

  System.out.println("JAVA".compareTo("java"));    //0      
  System.out.println("JAVA".compareToIgnoreCase("JAVA")) //0

How do you write a compareTo method in Java?


package com.asyncster.string.examples;

public class StringCompareToWithIgnoreCaseExample {
	public static void main(String args[]) {

		String str1 = "Welcome";
		String str2 = "WELCOME";
		String str3 = "Welcome";
		String str4 = "welcome";

		System.out.println(str1.compareToIgnoreCase(str2));// 0 both are equals
		System.out.println(str1.compareToIgnoreCase(str3)); // 0 both are equals
		System.out.println(str1.compareToIgnoreCase(str4)); // 0 both are equals

		StringBuffer sb1 = new StringBuffer("welcome");// new Object

		StringBuffer sb2 = new StringBuffer("welcome"); // new Object

		System.out.println(sb1.equals(sb2));// false // its not overridden for content comaprison
		System.out.println(sb1 == sb2); // false // different memory location

	}
}

output:

output:
0
0
0
false
false

Questions Related to Java String compareTo() method examples

Can we compare two strings using == in Java?

Yes, we compare two strings using == in Java, but this comparison is for the reference(memory location-based) comparison.

For the content comparison, we need to use the equals() method.

The equals() method is present in the Object class, which means reference comparison. In some classes, it’s overridden for meaningful purposes like in the String class.

But in some classes like StringBuffer and in StringBuilder class, it’s not overridden.

So if we have,

StringBuffer sb1 = new StringBuffer("welcome");

StringBuffer sb2= new StringBuffer("welcome");
System.out.println(sb1.equals(sb2));// false // its not overridden for content comaprison
System.out.println(sb1 == sb2); // false  // different memory location

How do you compare 2 strings in Java?

There are various ways to compare String in Java.

  • By using the String Equals Method.
  • By using String Equals Ignore Case.
  • By using String Compare To Method
  • By using == operator.
  • By using the Object’s class Equals Method.

Can you use == to compare objects in Java?

In java == is used for the reference comparison, which means two objects pointing to the same memory location. whereas the equals method is used for content comparison.

In this article we have seen String class’s compareTo() and compareToIgnoreCase() method with examples.

Java String compareTo() method examples
Tagged on:

Leave a Reply

Your email address will not be published. Required fields are marked *