One the most common tasks in programming is to compare two variable or we can say string to execute the code, on the basis of the result of comparisons, so in this article, I have explained how to compare strings in Java using various possible methods available in java.
String in Java
If you are new to java, you may wonder "What is string in java"? So here is your answer, string is basically an object that represents the sequence of char values. An array of characters works same as java string. For example:
//String is an array of characters
char[] arrSample = {'J', 'A', 'V', 'A'};
String strSample_1 = new String (arrSample);
Now we always cannot write our strings as arrays, hence we can define the String in Java as follows:
//Representation of String
String strSample_2 = "JAVA";
The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is created. For mutable string, you can use StringBuffer and StringBuilder classes.
There are two ways to create String object:
By string literal
String s="welcome"; //string literal is created by double quotes
By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In the above method, JVM will create a new string object in normal(non-pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non-pool).
Now let's come back to main topic of this article, "String comparison"
String Comparison in Java
We can compare string in java on the basis of content and reference.
It acn be used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.
There are three ways to compare string in java:
- By equals() method
- By = = operator
- By compareTo() method
Let's take a look on each of the above method one by one, so we can understand it usage
String compare by equals()
This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Example Code:
public class StringCompareequl{
public static void main(String []args){
String s1 = "qawithexperts";
String s2 = "qawithexperts";
String s3 = new String ("QA With Experts");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
}
}
Output will be:
true
false
String compare by == operator
Compares references, not values. The use of ==
with object references is generally limited to the following:
- Comparing to see if a reference is null.
- Comparing two enum values. This works because there is only one object for each enum constant.
- You want to know if two references are to the same object
public class StringCompareequl{
public static void main(String []args){
String s1 = "qawithexperts";
String s2 = "qawithexperts";
String s3 = new String ("qa with experts");
System.out.println(s1 == s2);
System.out.println(s2 == s3);
}
}
Output of the above code will be
true
false
Note:
==
handles null strings fine, but calling .equals() from a null string will cause an exception.
String compare by compareTo() method
Compares values and returns an int which tells if the values compare less than, equal, or greater than.
Suppose str1 and str2 are two string variables. If:
- str1 == str2 :0
- str1 > str2 :positive value
- str1 < str2 :negative value
Example :
public class StringCompareEmp{
public static void main(String args[]){
String value1 = "cat";
String value2 = "bird";
// Compare these strings.
int result1 = value1.compareTo(value2);
System.out.println(result1);
int result2 = value2.compareTo(value1);
System.out.println(result2);
// Compare string against itself.
// ... It is equal so the result is 0.
int result3 = value1.compareTo(value1);
System.out.println(result3);
}
}
Output will be:
1
-1
0
There is one more method which can be used to ignore case-sensitivity of strings
String compareToIgnoreCase() Method
The method compareToIgnoreCase()
is similar to the compareTo()
method as it also compares two strings lexicographically. The only difference between them is that compareToIgnoreCase()
ignores the case (uppercase or lowercase) while comparing two strings.
Example :
public class StringCompareToIgnoreCaseEmp{
public static void main(String args[]){
String string1 = "HELLO";
String string2 = "hello";
String string3 = "Hello";
int var1 = string1.compareToIgnoreCase(string2);
System.out.println(var1);
int var2 = string1.compareToIgnoreCase(string3);
System.out.println(var2);
int var3 = string1.compareToIgnoreCase("HeLLo");
System.out.println(var3);
}
}
Output of the above code will be:
0
0
0
As all strings were same, and we are ignoring case-sensitivity of the letters that's why all output values are equal and hence it is 0.
Important Method in Java Strings
- char charAt(int index): It returns the character at the specified index. Specified index value should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>= length of String.
- void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the characters of src array to the dest array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
- boolean equals(Object obj): Compares the string with the specified string and returns true if both matches else false.
- boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the case while comparing strings. It does a case insensitive comparison.
- int compareTo(String string): This method compares the two strings based on the Unicode value of each character in the strings.
- int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the case during comparison.
- boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It compares the substring of input to the substring of specified string.
- boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): Another variation of regionMatches method with the extra boolean argument to specify whether the comparison is case sensitive or case insensitive.
- boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the specified offset index) is having the specified prefix or not.
- boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.
- int hashCode(): It returns the hash code of the string.
- int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the string.
- int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the string from the specified fromIndex.
- int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
- int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from fromIndex.
- int indexOf(String str): This method returns the index of first occurrence of specified substring str.
- int lastindexOf(String str): Returns the index of last occurrence of string str.
- String substring(int beginIndex): It returns the substring of the string. The substring starts with the character at the specified index.
- String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.
- String concat(String str): Concatenates the specified string “str” at the end of the string.
- String replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar with the newChar.
- boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char values. If yes then it returns true else false. It throws NullPointerException of ‘s’ is null.
- String replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given regular expression “regex” with the specified replacement string.
- String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.
- String[] split(String regex, int limit): It splits the string and returns the array of substrings that matches the given regular expression. limit is a result threshold here.
- String[] split(String regex): Same as split(String regex, int limit) method however it does not have any threshold limit.
- String toLowerCase(Locale locale): It converts the string to lower case string using the rules defined by given locale.
- String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).
- String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined by specified locale.
- String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
- String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.
- char[] toCharArray(): Converts the string to a character array.
- static String valueOf(data type): This method returns a string representation of specified data type.
- byte[] getBytes(String charsetName): It converts the String into the sequence of bytes using the specified charset encoding and returns the array of resulted bytes.
- byte[] getBytes(): This method is similar to the above method it just uses the default charset encoding for converting the string into the sequence of bytes.
- int length(): It returns the length of a String.
- boolean matches(String regex): It checks whether the String is matching with the specified regular expression regex.
That's it.
You may also like to read:
Pyramid Triangle pattern programs in Java with explanation
Difference between HashMap and Hashtable in Java
Hello World program in Java (CMD and Eclipse Examples)
Program to remove duplicate elements in an array in Java
Which is the best method to iterate through the hashmap in java?