Learn String operations in Java using examples
In the previous article, we discussed the String class in Java. We learnt the ways a String object can be constructed. We also figured out the difference between String and StringBuffer. We discussed 2 string methods length() and Intern() as well. I hope that the article would have been helped you in the endeavours learning Strings in Java.
If you are preparing for any automation related interview then you should read Commonly asked java programs in Selenium Interview
and you should read this post which covers the most common interview question related to String
5 Commonly Asked Java String Question in Selenium Interview
In continuation here we will talk about some more string operation (mostly useful for automation testing practice) through which String can be manipulated in the many ways according to the need. In automation testing, we face many situations where it is required to manipulate the string.
- Concatenating String: In Java, two or more string objects can be concatenated in 2 ways as below:
- Using + operator: Please take a look in the below program:
class StringConcatenation1{ public static void main(String args[]){ String s="Abode"+"QA"; System.out.println(s);//AbodeQA } }
//another example
class StringConcatenation2{ public static void main(String args[]){ String s1=new String(“Abode”); String s2=new String(“QA”); String s = s1 + s2; System.out.println(s);//AbodeQA } }
- Using concat() method: Please refer to below example:
class StringConcatenation2{ public static void main(String args[]){ String s1=new String(“Abode”); String s2=new String(“QA”); String s = s1.concat(s2); System.out.println(s);//AbodeQA } }
- Using + operator: Please take a look in the below program:
- CharAt: This method helps us to find the character at the given index of the String. The index starts from 0 i.e. the first character of the string is at the 0th index. The last character is at the length() – 1 index. (Syntax: public char charAt(int index) )
Public class testCharAt{ Public static void main( Stringargs[] ){ String str = “String operation in Java.”; Char start = str.charAt(0); Char last = str.charAt(str.length() - 1); Char random = str.charAt(10); System.out.println (start); // will print ‘S’ System.out.println (last);// will print ‘.’ System.out.println (random);// will print ‘r’ } }
- compareTo: This method is used to compare the two strings lexicographically. It returns int value as the comparison result.
Value ‘0’ is returned if both the strings are equal. Value less than ‘0’ is returned if the argument string is greater than this string. A value greater than ‘0’ is returned if the argument string is less than this string.class StringcompareTo{ public static void main(String args[]){ String s1 = "Sachin"; String s2 = "Sachin"; String s3 = "Tendulkar"; System.out.println(s1.compareTo(s2)); //0 System.out.println(s1.compareTo(s3)); //-1(because s1 < s3) System.out.println(s3.compareTo(s1)); //1(because s3 > s1 ) } }
CompareTo method can also be used to compare any 2 objects as this method is part of Java object class. So it is not limited to String comparisons only.
- ContentEquals: This method compares the String with StringBuffer and returns a Boolean value.
public class StringContentEquals { public static void main(String args[]) { String str1 = "One"; String str2 = "Two"; StringBuffer str3 = new StringBuffer( "One"); StringBuffer str4 = new StringBuffer( "Two"); System.out.println(str1.contentEquals(str3)); //true System.out.println(str2.contentEquals(str3)); //false System.out.println(str1.contentEquals(str4)); //false System.out.println(str2.contentEquals(str4)); //true } }
- Equals and equalsIgnoreCase: To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str)
Here, str is the String object is being compared with the invoked String object. It returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive. To perform a comparison that ignores case differences, call equalsIgnoreCase().
When it compares two strings, it considers A-Z to be the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object. It, too, returns true if the strings contain the same characters in the same order, and false otherwise.
Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):class equalsDemo { public static void main(String args[]) { String s1 = "Hello"; String s2 = "Hello"; String s3 = "Good-bye"; String s4 = "HELLO"; System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3)); System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4)); System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4)); } }
The output from the program is shown here:
Hello equals Hello -> true Hello equals Good-bye -> false Hello equals HELLO -> false Hello equalsIgnoreCase HELLO -> true
- getChars: If you need to extract more than one character at a time, you can use the getChars( ) method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) class getCharsDemo { public static void main(String args[]) { String s = "This is a demo of the getChars method."; int start = 10; int end = 14; char buf[] = new char[end - start]; s.getChars(start, end, buf, 0); System.out.println(buf); } }
Here is the output of this program:
demo
[the_ad_placement id=”incontent”]
- replace: The replace( ) method replaces all occurrences of one character in the invoking string with another character. It has the following general form:
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example,
String s = "Hello".replace('l', 'w');
puts the string “Hewwo” into s.
- split: Ahhh!! I just love this method. I have built a framework around this function only.
You can split a String using this method. The string is broken around the given delimiter(regular expression). It returns an array of Strings. Let’s understand by an example:class StringSplit { public static void main(String args[]) { String s = new String("Demo:of:the:Split:method."); String buf[] = s.split(“:”); System.out.println(buf); } }
Here is the output of this program:
Demo of the Split method.
Number of splited Strings can also be controlled by using the overloaded method of Split
(split(regex, limit)).
String s = new String("Demo:of:the:Split:method."); String buf[] = s.split(“:”, 3); System.out.println(buf);
output:
Demo of the:Split:method.
[the_ad_placement id=”incontent”]
- substring: You can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string. The second form of substring( ) allows you to specify both the beginning and ending index of the substring:
String substring(int startIndex, int endIndex)
Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.
class StringReplace { public static void main(String args[]) { String org = "This is a test. This is, too."; String search = "is"; String sub = "was"; String result = ""; int i; do { // replace all matching substrings System.out.println(org); i = org.indexOf(search); if(i != -1) { result = org.substring(0, i); result = result + sub; result = result + org.substring(i + search.length()); org = result; } } while(i != -1); } }
output:
This is a test. This is, too. Thwas is a test. This is, too. Thwas was a test. This is, too. Thwas was a test. Thwas is, too. Thwas was a test. Thwas was, too.
- toUppercase and toLowerCase: These 2 methods are used to convert the questioned string to all upper case letters and lower case letters respectively.
class StringtoUppercase { public static void main(String args[]){ String s1 = new String(“AbodeQA”); s1 = s1. toUppercase(); System.out.println(s1);//ABODEQA } }
class StringtoLowercase { public static void main(String args[]){ String s1 = new String(“AbodeQA”); s1 = s1.toLowercase(); System.out.println(s1);//abodeqa } }
- Trim: If there is a situation where you have the string which has spaces in its starting and in ending, this method will help you out to remove those.
class StringTrim{ public static void main(String args[]){ String s1 = new String(“ AbodeQA ”); s1 = s1.trim(); System.out.println(s1);//AbodeQA } }
If you want to explore more about String then read it from here
Read Similar Posts
This is a fantastic blog from which people can learn a lot. It is very informative and is explained in…
Thanks for sharing such knowledgeable Content on Automation testing, to know how to enhance the performance of ERP's like Oracle…
Thanks.. this list is much needed.
This one is also good to use. Thanks for sharing this.. Might be we can also add it in list…
How about youtube-dl?