Java String Compare - Java Language Basics

Java examples for Language Basics:String

Introduction

Java String class defines following methods to compare Java String object.

int compareTo( String anotherString )

The methods above compare two string based upon the unicode value of each character in the String.

  • Returns negative int if first string is less than another
  • Returns positive int if first string is greater than another
  • Returns 0 if both strings are same.
int compareToIgnoreCase( String anotherString )

The method above compares two strings ignoring the character case of the given String.

Demo Code


public class Main {

  public static void main(String args[]) {

    String str = "Hello World";
    String anotherString = "hello world";
    Object objStr = str;/*from w ww. j  a v  a 2  s  .c om*/

    /* compare two strings, case sensitive */
    System.out.println(str.compareTo(anotherString));
    /* compare two strings, ignores character case */
    System.out.println(str.compareToIgnoreCase(anotherString));

  }

}

Result


Related Tutorials