July 14 2016

Java compareToIgnoreCase example

Java compareToIgnoreCase example

The method ‘compareToIgnoreCase’ compares two strings ignoring case differences. It is similar to the ‘compareTo’ method, ‘compareTo’ method compares two strings with respect to case.

Syntax

int compareToIgnoreCase(String str)

Return type

The return type of the method is integer. If the return value is

  • >0 current string is greater than input string
  • =0  both the strings are equal
  • <0 current string is less than input string

Example


package com.answersz;

public class JavaCompareToIgnoreCase {

public static void main(String[] args) {

// Java compareToIgnoreCase example

String str1 = "APPLE";
String str2 = "apple";
String str3 = "Orange";
String str4 = "Banana";

// Case sensitive comparison

int result1 = str1.compareTo(str2);

System.out.println("result1 :" + result1);

// Case insensitive comparison

int result2 = str1.compareToIgnoreCase(str2);

System.out.println("result2 : " + result2);

int result3 = str3.compareToIgnoreCase(str4);

System.out.println("result3 : " + result3);

int result4 = str1.compareToIgnoreCase(str4);

System.out.println("result4 : " + result4);

}
}


Output


result1 :-32
result2 : 0
result3 : 13
result4 : -1



Copyright © 2014. All rights reserved.

Posted July 14, 2016 by answersz in category Core Java

Leave a Comment

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

*