String in Java

Strings are a sequence of characters enclosed within the double quotes which include alphabets, numbers, special characters and so on. Strings are objects in Java, which means strings are not a primitive data type.

The Architecture of Strings : char-sequence-string-selenium-webdriver We can form strings using below classes, all three classes implements CharSequence interface and extends Object Class :

  • String
  • StringBuffer
  • StringBuilder

Lets us discuss String Class first.

String Class in Java

String class implements CharSequence interface and extends Object class, object class is top most class in java.

String is represented with "" (double quotes). String is immutable which means once we create a string object, we cannot modify the String object.

The class String includes methods for examining individual characters of the String, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase.

We can create strings in two methods :

1. Double quotes method (most preferred method)
2. String object method

1. Double quotes method :
String is created by enclosing the string inside double quotes, Below are few processes happens when we use double quotes to create string.

  1. JVM checks String Constant pool for any value which same as what we are trying to create.
  2. If yes, point that string object reference to the variable that we are trying to create.
  3. If no, JVM creates new string object in String constant pool

										public static void main(String[] args) {
											// create chercher tech string
											String firstString = "CherCher Tech";
											System.out.println("String we created : "+firstString);

2. String object method :

We can also create a string by creating an object of String class. We have to call the String class constructor to create the string and that creates the string in the non-constant pool in the String pool.

JVM will not check for the duplicate strings, if we use String Constructor to create a string. So there can be duplicate strings in the non-constant pool.

										public class StringExample2 {
											public static void main(String[] args) {
												// create the string
												String secondString = new String("");
												// print the string
												System.out.println("String created is : "+secondString);

What is String pool :

String Pool is a pool of string values that are available to other parts of the program. String pool can be divided into two parts

  • Constant String pool
  • Non-Constant String pool

1. String Constant Pool :

String constant pool located inside a section of memory is called the heap. This is a part of memory that is used for run-time operations, working with classes and objects.

String constant pool does not allow users to create duplicate strings. If the user tries to create a duplicate string using "(double quotes), then string pool returns the address of the existing string.

So at any given time, Constant String pool will contain only unique values, and also user may not feel any difference with operations.

In below example, we will create two strings and we will verify the address of those strings.

										public class StringExample3 {
											public static void main(String[] args) {
												String str1 = "checrcher tech";
												String str2 = "checrcher tech";
												// get the address of the strings
												System.out.println("Address of the str1 : "+System.identityHashCode(str1));
												System.out.println("Address of the str2 : "+System.identityHashCode(str2));

Output : output-of-string-address-selenium-java

2. Non-Constant String Pool :
Non-constant string pool will allow the user to create duplicates. Below example print the address of the string created.

										public class StringExample4 {
											public static void main(String[] args) {
												String str3 = new String("");
												String str4 = new String("");
												// get the address of the strings
												System.out.println("Address of the str3 : "+System.identityHashCode(str3));
												System.out.println("Address of the str4 : "+System.identityHashCode(str4));

Output : new-string-object-java-selenium

Compare Strings : We cannot compare strings using '==' relational operator, as '==' operator tries to compare the address of the object. But most of the time strings may not be stored in the same object so the address will be different for each string. We should use equals() present in the String object to compare two strings.

										public static void main(String[] args) {
											String str1 = new String("CherCher tech");
											String str2 = "CherCher tech";
											System.out.println("Comparision using '==' : " + (str1 == str2));
											System.out.println("Comparision using 'equals()' : " +(str1.equals(str2)));

Output : string-comparision-java-selenium-webdriver

Really, Cannot we compare Strings using '==' : We can compare the strings using '==' sign as well but with one condition, Strings must have created using "".

In this case also '==' tries to compare the address but as the constant pool will let only unique values to present, so the address will be same when the content of the strings are same.

										public static void main(String[] args) {
											String s3 = "CherCher tech";
											String s4 = "CherCher tech";
											System.out.println("Comparision using '==' : " + (s3 == s4));
											System.out.println("Comparision using 'equals()' : " +(s3.equals(s4)));

Output : non-constant-string-pool-compare-java-selenium

Useful methods in String : There are so many methods present in String but we will learn about most used methods of String.
1. Length : length method return number of characters present in the string, it returns integer value.

								public static void main(String[] args) {
									String str = "";
									System.out.println("String Length : "+str.length());

Output : length-method-string-java-selenium

1. charAt : charAt method returns a character at a particular position, in java the index starts from 0. If we want to get 5th element then we have to query for 4th index index-of-string-char-java-selenium

								public static void main(String[] args) {
									String str = "";
									// index starts from zero
									System.out.println("Char at 5th element : "+str.charAt(4));

Output : charat-string-java-selenium

3. Concat : concat is nothing but adding two or more strings, concat() method helps the user to add two string into one string. This method will not disturb the existing strings, it will create a new string with concatenation and returns it.

								public static void main(String[] args) {
									String str = "CherCher";
									String str2 = "Tech";
									String abc = str.concat(str2);

									System.out.println("String  : "+str);
									System.out.println("String 2  : "+str2);
									System.out.println("String concat : "+abc);

Output : concat-string-java-selenium

4. startsWith : startsWith method verifies whether the String starts with given substring or not. This return a boolean value, true if the String starts with given substring else false.

								public static void main(String[] args) {
									String str = "";
									System.out.println("Starts with Cher : " +str.startsWith("Cher"));
									System.out.println("Starts with ABC : " +str.startsWith("ABC"));

Output : starts-with-string-java-selenium

5. endsWith : endsWith method verifies whether the String ends with given substring or not, endsWith method also return boolean value.

6. contains : contains method verifies whether the String contains substring or not, the substring could be anywhere in the main string.

								public static void main(String[] args) {
									String str = "";
									System.out.println("contains te : " +str.contains("te"));
									System.out.println("contains xyz : " +str.contains("xyz"));

Output : contains-string-java-selenium

7. equals : equals() method compares the two string based on the content present in the string, if the content matches the equals() method returns true else false.

								public static void main(String[] args) {
									String str = "";
									System.out.println("equals : " +str.equals(""));

8. isEmpty : isEmpty method verifies whether given string is empty("") or not, empty means string with no value ("").

								public static void main(String[] args) {
									String str = "";
									String str2 = "";
									System.out.println("str : " +str.isEmpty());
									System.out.println("str2 : " +str2.isEmpty());

Output : is-empty-string-java-selenium

9. replace : replace method replaces the specified value with the given new value in all occurrences

								public static void main(String[] args) {
									String str = "";
									System.out.println("After replace : " +str.replace("Cher", "AAAA"));

Output : replace-string-java-selenium

10. indexOf : this method returns the first index of the given substring or character.

								public static void main(String[] args) {
									String str = "";
									System.out.println("Index of he : " +str.indexOf("he"));

Output : indexof-string-java-selenium

11. toUpperCase /toLowerCase : We can convert the string into UPPERCASE or to lowercase using string methods.

								public static void main(String[] args) {
									String str = "";
									System.out.println("UpperCase : " +str.toLowerCase());
									System.out.println("LowerCase : " +str.toUpperCase());

Output : upper-lower-case-string-java-selenium

12. trim() : trim method removes the spaces at the starting and ending of the string and returns the string without spaces at the ends.

								public static void main(String[] args) {
									String str = "       ";
									System.out.println("Length before trim : " +str.length());
									System.out.println("Length after trim : " +str.trim().length());

Output : trim-string-java-selenium

Facts about Strings (not String Class) in Java

Below are the few facts about the strings in java, these are about strings only not about String class.

  1. String is a derived / object type, not a primitive type like int, long, float etc. Strings are objects in java.
  2. We can create Mutable and immutable Strings in java
  3. String, StringBuffer, and StringBuilder are final which means we can’t extend them. String, StringBuffer, and StringBuilder are members of java.lang package.
  4. toString() is overridden in String, StringBuffer and StringBuilder to print the string content
  5. String and StringBuffer objects are thread safety where as StringBuilder objects are not thread safety
  6. Strings in java are backed by character array. You can retrieve this array using toCharArray() method of String class.
  7. Unlike in C and C++, Strings in java are not terminated with a null character
  8. String is Designed to Optimize the Memory Usage, because which only the Constant Sting pool exists.
  9. Prefer StringBuilder when dealing with single threads only. Otherwise, if multiple threads could be accessing it, a StringBuffer (being synchronized) may be what you are after.
  10. String are stored as UTF-16 characters and maybe someday they will move to UTF-32 as well.
    1. Dynamic method dispatch in Java & Selenium

StringBuffer and StringBuilder

StringBuffer class is used to create mutable strings, which means we can alter the value of the string after we create it.

It represents grow-able and append-able character sequence. Strings are formed using StringBuffer class when we have to make a lot of modifications to our string.

StringBuffer class methods are synchronized, so multiple threads cannot access the string value.

StringBuilder class is similar to the StringBuffer class, the only difference is StringBuilder class methods are not synchronized, so multiple threads can access the String value.

Constructors of StringBuffer : StringBuffer has 4 constructors which are :

1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )

StringBuffer() creates an empty string buffer and reserves room for 16 characters.

StringBuffer(int size) creates an empty string buffer. accepts a int value to create room for character.

StringBuffer ( String str ) creates an given string buffer with character room based on length of the given string

StringBuffer ( charSequence [ ] ch ) creates a string buffer based on the character array passed to the constructor.

Methods present in the StringBuffer and String Builder : Let's discuss about few methods present in the StringBuffer.

append : append() method updates the current value of the string, given string will be added at the end of the string.

We can append data types like boolean, char, int, long, Strings. Unlike String, string buffer modifies the current value and returns the self.

										public static void main(String[] args) {
											StringBuffer str = new StringBuffer("CherCher");
											System.out.println("Str before append : "+str);
											// append the values
											System.out.println("Str after append : "+str);
											System.out.println("append with number: "+str);
											System.out.println("append boolean: "+str);

Output : stringbuffer-append-java-selenium

reverse : reverse method reverses the current string and applies it to the self. So when you retrieve later you will get only reversed string only.

										public static void main(String[] args) {
											StringBuffer str = new StringBuffer("CherCher tech");
											System.out.println("Str before reverse : "+str);
											// reverse the string
											System.out.println("Str after reverse : " +str);

Output : stringbuffer-reverse-java-selenium

delete(start, end) : delete method remove the substring/ characters from the current string based on the starting and ending index.

										public static void main(String[] args) {
											StringBuffer str = new StringBuffer("CherCher");
											System.out.println("Str before delete : "+str);
											// delete the substring
											str.delete(2, 4);
											System.out.println("Str after delete : "+str);

Output : stringbuffer-delete-java-selenium

insert(indexToinsert, contentToInsert) : insert method helps user to add any string value in between the existing string, not only at in between, we also insert at the start and end as well based on the index.

										public static void main(String[] args) {
											StringBuffer str = new StringBuffer("CherCher tech");
											System.out.println("Str before insert : "+str);
											// reverse the string
											str.insert(0, "AAAA");
											System.out.println("Str after insert at start : " +str);
											str.insert(9, "BBBB");
											System.out.println("Str after insert at somewhere : " +str);

Output : stringbuffer-insert-java-selenium

replace : This method replaces the characters in a substring of this StringBuffer with characters in the specified String.

									public static void main(String[] args) {
										StringBuffer str = new StringBuffer("CherCher tech");
										System.out.println("Str before replace : "+str);
										// reverse the string
										str.replace(0, 7, "TTTTTTTTTT");
										System.out.println("Str after replace : " +str);

Output : stringbuffer-replace-java-selenium

capacity : The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of the character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2.

For example, if your current capacity is 16, it will be (16*2)+2=34.

									public static void main(String[] args) {
										StringBuffer sb = new StringBuffer();
										System.out.println("Capacity before anyvalue: "+sb.capacity());
										System.out.println("Capacity after 8 chars: "+sb.capacity());
										System.out.println("Capacity after 18 chars: "+sb.capacity());

Output : stringbuffer-capacity-java-selenium

Xpath in Selenium

Strings are Immutable, but are we sure ? :

People will say Strings are immutable but not all the String are immutable. Strings created using String class are immutable but Strings created using StringBuffer, StringBuilder are mutable.

When we create strings using String class in java, JVM creates immutable strings. That means once you create a string object, you can’t modify the contents of that object.

If you try to modify the contents of string object, a new string object is created with modified content.

Below example explains how the Strings are immutable.

  1. Create a String variable str1 and assign "" as value
  2. Print the address of the str1
  3. Re-assign the str1 with ""
  4. Print the address of the str1
  5. Compare the address printed in step 2 and step 4, both the address are different because when we re-assign the value of String variable with another string, the variable points to the new address.

    The object on the first address ( will lose its reference and becomes a dead object. So when we change string variable value it leaves the dead objects on the String pool and changes its reference to its new value.

    This proves the immutability of the Strings.

										public class StringImmutability {
											public static void main(String[] args) {
												String str1 = "";
												System.out.println("Address of str1 : "+System.identityHashCode(str1));
												str1 = "";
												System.out.println("Address of str1 after change : "+System.identityHashCode(str1));

Output : string-immutability-java-selenium

Below example explains the String created by StringBuffer is Mutable. Below example is nothing but the StringBuffer version of the above symbol.

										public class SBuffMutability {
											public static void main(String[] args) {
												StringBuffer sb1 = new StringBuffer("");
												System.out.println("Address of str1 : "+System.identityHashCode(sb1));
												sb1.replace(0, sb1.length()-1, "");
												System.out.println("Address of str1 after change : "+System.identityHashCode(sb1));

Output : stringbuffer-java-selenium

Why Strings created by string class are immutable ?

Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.

Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.

Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).

Class loading: String is used as arguments for class loading. If mutable, it could result in the wrong class being loaded (because mutable objects change their state).

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Reply
  • Karthiq, your articles are pretty good, but you definitely need to improve your grammar in English.
    • admin[Karthiq]
      Thanks buddy, 
      I am trying to improve it
  • Protractor Training

    new tutorial I am starting new Protractor training batch on Weekends. Course starts from 08-june-2019 [10am IST to 1 pm IST] based on online for 6 days, and course fee is INR 10, 000.

    Interested people can confirm the seat by calling to +91 8971673487 or whatsapp to +91 9003381224

    Find the course content : View Content