String Comparison in Java

Strings in Java
Strings are combinations of characters used in Java programming. It is not a data type but are objects of String class. The String class represents the character strings. All the literals in java such as “bcde” are implemented as instance of class. Strings are constant and their values cannot be changed once created. String buffers support mutable strings and there values can be changed.
This is implemented using the StringBuffer class and it appends methods.
String class includes methods which examine the individual characters sequences for comparing strings, searching, substring extraction and for creating copy of all the characters with translation to upper or lowercase. String class provides support for string concatenation using ‘+’ operator. String class has numerous methods for manipulations.

Creating Strings
For Example
            String str=“Hello World”;
is equivalent to
            charch[]={‘H’,’e’,’l’,’l’,’o’,’ ‘,’W’,’o’,’r’,’l’,’d’};
            String str=new String(ch);
Comparing Strings
String class uses various methods to compare strings and portion of strings. When we talk about comparing the strings, various factors are involved and for instance, if all string characters is matched then the two strings are said to be equal. This is not true in case of programming languages. The string will be equal if and only if:

  • Both strings have same number of characters but characters should match each other. For example, “hello world” is not “helloworld”. Remember space is a special character in java and is not ignored when comparison is being performed.
  • The case must be taken in account while comparing the strings i.e. “Hello” and “hello” are not equal because the first letter in first case is in uppercase while in second it is in lowercase.
  • Lowercase matches lowercase and uppercase matches with uppercase.
  • All the punctuations are taken as characters and thus affect the comparison of strings.
Compare String predefined Java Methods: 
  • booleanendsWith(String suffix) and booleanstartsWith(String prefix): It returns true when the string starts or ends with the specified substring passed as a parameter in the function.
  • booleanstartsWith(String pref, int off): Compares the string starting from the mentioned index passed as argument with the given substring. It returns true when the match is found.
  • intcompareTo(String anotherString): Compares 2 strings and returns the integer value. If two strings are equal, zero is returned else when first string is greater, a value greater than zero is returned, else value less than zero is returned.
  • intcompareToIgnoreCase(String string1):This compares 2 strings and return integer value. The only difference to compareto() method is it is not case sensitive comparison, for instance “ABC” and “abc” both will be equal in this case. The string is compared with the similar character as done in general life. 
  • boolean equals(Object aObject): It returns true when the String object  representing character strings are matched with the current String object. 
  • booleanequalsIgnoreCase(String anotherString): Returns true when the String object representing  character strings are matched with the current String object, ignoring the case of characters.
  •  booleanregionMatches(int toffset, String other, int offset, int len): Checks if the identified region of string matches the stated region of String argument. The region here is the length of the string that is matched starting from the “toffset” for one string to “offset” for the other. 
  • booleanregionMatches(booleanignoreCase, int toffset,String other, int offset, int len): Identified region of string argument is matched with the stated region of  current String. The boolean parameter indicates if the case is to be ignored or not while comparing. 
  • boolean matches(String regex): Compares the string with the given regular expressions.
Simple Example of region Match function:
public class Demo {
public static void main(String[] args) {
       String search_str = “Hello World Everywhere”;
       String findMe = “World”;
intsearch_length = search_str.length();
intfindMe_length = findMe.length();
boolean found = false;
for (inti = 0;
i<= (search_length – findMe_length);
i++) {
if (search_str.regionMatches(i, findMe, 0, find_length)) {
found = true;
System.out.println(search_str.substring(i, i + find_length));
if (!found)
System.out.println(” Sorry No match found .”);
Comparing Strings as we can see is done by using the predefined function in java. It is not compulsory for the programmer to use these predefined functions though it is definitely recommended. The programmer can code his own algorithm for comparison.
Example String Comparison without using Predefined functions:
class Test {
public static void main(String args[]) {
     String str1 = “Jack eats Apple”;
             String str2 = “Jack eats Apple”;
//Converting String to Character array to compare
                        char[] ch1=str1.toCharArray();
                        char[] ch2=str2.toCharArray();
int f=0;
// Finding the length of  each strings
int len1=str1.length();
int len2=str2.length();
//Loop to compare every Character
for(int x=0;x<len1;x++)
            for(int y=0;y<len2;y++)
                        break;// Mismatch found loop breaks
                        System.out.println(“String not equal”);
                        System.out.println(“String are equal”);
Strings are equal
In the above example, every character of first string is compared to second string characters. As soon as there is a mismatch the loop breaks and a mismatch message is shown on the screen. Otherwise a success message is printed.
Comparison of Strings using Predefined Java functions:
class Test {
public static void main(String args[]) {
  String str1 = “Jack eats Apple”;
  String str2 = “Jack eats Apple”;
  String str3 = “Jill also eats apple”;
// Using compareto predefined java function.”result” stores the  integer value
returned by comparedto function.
// str1 is compared to str2
int result = str1.compareTo( str2 );
//srt2 is compared to str3
result = str2.compareTo( str3 );
//Str3 is compared to str1       
result = str3.compareToIgnoreCase ( str1 );
The above program gives three outputs. The comparison method of java calculates the difference of ASCII values of each character of two strings passed. If the difference of all the characters ASCII values comes to “0” strings are exactly equal. Otherwise, it prints the difference of ASCII value of first non-matched character. If value is negative first string is greater, else the second is greater. Similarly comparetoIgnoreCase works but the function ignores the case of the string charactes.

Leave a Reply

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