We are moved to new domain
Click -> www.ehowtonow.com
Saturday, 2 May 2015

Java Example – String Compare

Following example we are going to see about how to compare two String using compareTo(String arg) , compareToIgnoreCase(String arg)  methods available in Java .
compareTo(String arg)
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 result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions
compareToIgnoreCase(String arg)
Compares two strings lexicographically, ignoring case differences. This method 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.toUpperCase(character)) on each character.
Sample Program
package com.javatutorialcorner.javastring;

public class CompareString {

    public static void main(String[] args) {
        String firstString = "Java Tutorials Corner";
        String secondString = "java tutorials corner";
        Object referenceObject = firstString;

        //Comapre
        System.out.println(firstString.compareTo(secondString));
        System.out.println(firstString.compareToIgnoreCase(secondString));
        System.out.println(firstString.compareTo(referenceObject.toString()));
        
    }

}

Output

The above sample code produce the following output

-32
0
0

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Java Example – String Compare Rating: 5 Reviewed By: eHowToNow