java tutorial - Compare two strings in Java - java programming - learn java - java basics - java for beginners



 compare two string in java

Learn java - java tutorial - compare two string in java - java examples - java programs

Comparing two strings:

  • unicode value of each path character in the String.
  • Returns negative int if first string is less than another
  • Returns positive int if first string is grater than another
  • Returns 0 if both strings are same.
  • int compareTo( String anotherString )
  • int compareTo( Object obj ) – It behaves accurately like compareTo ( String anotherString) - if argument object is of type String, or else throws ClassCastException.
  • int compareToIgnoreCase( String anotherString ) – It compares two strings ignoring the character case of the given String.

Sample Code|:

import java.util.Arrays;
 
public class kaashiv_infotech
{
     public static void main(String args[])
     { String stringvalue1 = "WelcoMe To KaashiV";
        String stringvalue2 = "welcome to kaashiv";
        Object stringvalue3 = stringvalue1;
 System.out.println(stringvalue1.compareTo(stringvalue2));
 System.out.println(stringvalue1.compareToIgnoreCase(stringvalue2));
  System.out.println(stringvalue1.compareTo(stringvalue3.toString()));
     }
 
}

Output:

-32
0
0

Related Searches to Compare two strings in Java