Java String Compare Example

  1. /*
  2. Java String compare example.
  3. This Java String compare example describes how Java String is compared with another
  4. Java String object or Java Object.
  5. */
  6.  
  7. public class JavaStringCompareExample{
  8.  
  9. public static void main(String args[]){
  10.  
  11. /*
  12.   Java String class defines following methods to compare Java String object.
  13.   1) int compareTo( String anotherString )
  14.   compare two string based upon the unicode value of each character in the String.
  15.   Returns negative int if first string is less than another
  16.   Returns positive int if first string is grater than another
  17.   Returns 0 if both strings are same.
  18.   2) int compareTo( Object obj )
  19.   Behaves exactly like compareTo ( String anotherString) if the argument object
  20.   is of type String, otherwise throws ClassCastException.
  21.   3) int compareToIgnoreCase( String anotherString )
  22.   Compares two strings ignoring the character case of the given String.
  23.   */
  24.  
  25. String str = "Hello World";
  26. String anotherString = "hello world";
  27. Object objStr = str;
  28.  
  29. /* compare two strings, case sensitive */
  30. System.out.println( str.compareTo(anotherString) );
  31. /* compare two strings, ignores character case */
  32. System.out.println( str.compareToIgnoreCase(anotherString) );
  33. /* compare string with object */
  34. System.out.println( str.compareTo(objStr) );
  35.  
  36. }
  37.  
  38. }
  39.  
  40. /*
  41. OUTPUT of the above given Java String compare Example would be :
  42. -32
  43. 0
  44. 0
  45. */

Post new comment

To combat spam, please enter the code in the image.


Suggested Reading

Oracle Magazine
Contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for developers and DBAs, and more.
Cost: FREE

View/Subscribe
NASA Tech Briefs
Features exclusive reports of innovations developed by NASA and its industry partners/contractors that can be applied to develop new/improved products and solve engineering or manufacturing problems.
Cost: FREE

View/Subscribe
FierceBiotech IT
Is a free, easy to read weekly email service that brings must read biotech IT news to senior biotech, pharma, and IT executives.
Cost: FREE

View/Subscribe
Simply SQL
Simply SQL is a practical step-by-step guide to writing SQL.
Cost: FREE

View/Subscribe
Simply JavaScript
Packed with full-color examples, Simply JavaScript is all you need to start programming in JavaScript the right way.
Cost: FREE

View/Subscribe
PCMag.com's What's New Now
Lance Ulanoff, Editor in Chief of the PC Magazine Network, brings you this twice-weekly roundup of the latest top tech stories, the best new product reviews, plus special offers from Ziff Davis and its partners.
Cost: FREE

View/Subscribe

Could not find what you are looking for? Search Java Examples




Feel Tired? Read Jokes & Inspirational Stories, Play Games!