String Comparisons in Java: Understanding How to Work with Multiple Strings
Strings are a combination of characters used in Java programming. Strings are not a data type. Instead, they are objects of the String class. All character variables in Java such as “bcde” or “kdsfj1898” are implemented as an instance of the class. Strings are considered immutable, which means values don’t change. To modify a string, you use the Java StringBuffer class.
The String class includes methods that examine individual characters sequences for comparing strings, searching strings, substring extraction and creating a copy of all the characters. String methods also include translations to upper or lowercase. The String class provides support for string concatenation using ‘+’ operator. The String class has numerous methods for manipulations, which will be discussed in this article.
Learn more about Java string comparisons at Udemy.com
Creating Strings
For Example
String str=“Hello World”; is equivalent to char ch[]={‘H’,’e’,’l’,’l’,’o’,’ ‘,’W’,’o’,’r’,’l’,’d’}; String str=new String(ch);
Comparing Strings
The String class uses various methods to compare strings and portion of strings.When we talk about comparing the strings, various factors are involved. For instance, if all string characters are 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:
- Both strings have same number of characters and characters match. For example, “hello world” is not the same as “helloworld”. Remember, the space is a special character in Java and is not ignored when a comparison is being performed.
- Comparisons are case-sensitive. The strings “Hello” and “hello” are not equal, because the first letter in first string is in uppercase while in second is in lowercase.
- All punctuation (special characters) is taken as characters and thus affect the comparison of strings.
Learn more about Java programming with a course at Udemy.com.
Compare String predefined Java Methods:
- boolean endsWith(String suffix) and booleanstartsWith(String prefix): It returns true when the string starts or ends with the specified substring passed as a parameter.
- boolean startsWith(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 an integer value. If two strings are equal, zero is returned. Otherwise, when the 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 an integer value. The only difference from the previous compareto() method is that comparetoIgnoreCase() is not a case sensitive comparison. For instance, “ABC” and “abc” 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 matches with the current String object
- boolean equalsIgnoreCase(String anotherString): Returns true when the String object representing character strings are matched with the current String object, ignoring the character case.
- boolean regionMatches(inttoffset, String other, int offset, intlen): Checks if the specified region matches the region passed as an argument. The region is the length of the string that matches the starting point (“toffset”) to the “offset” of the other.
- boolean regionMatches(booleanignoreCase, int toffset, String other, int offset, intlen): This method has the same function as the previous one, but “ignoreCase” will ignore character case.
- 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”; int search_length = search_str.length(); int findMe_length = findMe.length(); boolean found = false; for (int i = 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)); break; } } if (!found) System.out.println(" Sorry No match found ."); } }
You can compare strings using the predefined function in Java. You can also write your own methods or functions to perform comparisons.
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; // Find 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++) { if(ch1[x]==ch2[x]) else { f=1; break;// Mismatch found loop breaks } } } if(f=1) { System.out.println("String not equal"); } else { System.out.println("String are equal"); } } } }
Output:
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. The “result” stores the integer value returned by comparedto function. // str1 is compared to str2 int result = str1.compareTo( str2 ); System.out.println(result); //srt2 is compared to str3 result = str2.compareTo( str3 ); System.out.println(result); //Str3 is compared to str1 result = str3.compareToIgnoreCase( str1 ); System.out.println(result); } }
Output:
-8
8
Learn Java programming from scratch at Udemy.com
The above program gives three output values. The Java comparison method calculates the difference of ASCII values for each character of two strings passed. If the difference comes to “0”, the strings are exactly equal. Otherwise, it prints the difference of ASCII value for the first non-matched character. If the value is negative, the first string is greater. Otherwise, the second is greater.
Recommended Articles
Top courses in Java
Java students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.