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 :
We can form strings using below classes; all three classes implement CharSequence interface and extends Object Class :
String class implements the CharSequence interface and extends Object class, and object class is a topmost class in java.
A string is represented with "" (double quotes). The 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 lowercase.
We can create strings in two methods :
The string is created by enclosing the string inside double-quotes. Below are a few processes that happen when we use double quotes to create a string.
public static void main(String[] args) {
// create chercher tech string
String firstString = "CherCher Tech";
System.out.println("String we created : "+firstString);
}
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("Selenium-webdriver.com");
// print the string
System.out.println("String created is : "+secondString);
}
}
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
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 the string pool returns the address of the existing string.
So at any given time, the Constant String pool will contain only unique values, and also users may not feel any difference with operations.
In the 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 :
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("Selenium-webdriver.com");
String str4 = new String("Selenium-webdriver.com");
// 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 :
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 :
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 the same when the content of the strings is the 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 :
Useful methods in String : There are so many methods present in String, but we will learn about the most used methods of String.
1. Length : length method return number of characters present in the string, it returns an integer value.
public static void main(String[] args) {
String str = "CherCher.tech";
System.out.println("String Length : "+str.length());
}
Output :
public static void main(String[] args) {
String str = "CherCher.tech";
// index starts from zero
System.out.println("Char at 5th element : "+str.charAt(4));
}
Output :
3. Concat : concat is nothing but adding two or more strings, concat() method helps the user to add two strings into one string. This method will not disturb the existing strings, and 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 :
4. startsWith : startsWith method verifies whether the String starts with given substring or not. This returns a boolean value, true if the String starts with given substring else false.
public static void main(String[] args) {
String str = "CherCher.tech";
System.out.println("Starts with Cher : " +str.startsWith("Cher"));
System.out.println("Starts with ABC : " +str.startsWith("ABC"));
}
Output :
5. endsWith : endsWith method verifies whether the String ends with given substring or not, endsWith method also returns a 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 = "CherCher.tech";
System.out.println("contains te : " +str.contains("te"));
System.out.println("contains xyz : " +str.contains("xyz"));
}
Output :
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 = "CherCher.tech";
System.out.println("equals : " +str.equals("CherCher.tech"));
}
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 = "CherCher.tech";
String str2 = "";
System.out.println("str : " +str.isEmpty());
System.out.println("str2 : " +str2.isEmpty());
}
Output :
9. replace : replace method replaces the specified value with the given new value in all occurrences
public static void main(String[] args) {
String str = "CherCher.tech";
System.out.println("After replace : " +str.replace("Cher", "AAAA"));
}
Output :
10. indexOf : this method returns the first index of the given substring or character.
public static void main(String[] args) {
String str = "CherCher.tech";
System.out.println("Index of he : " +str.indexOf("he"));
}
Output :
11. toUpperCase /toLowerCase : We can convert the string into UPPERCASE or to lowercase using string methods.
public static void main(String[] args) {
String str = "CherCher.tech";
System.out.println("UpperCase : " +str.toLowerCase());
System.out.println("LowerCase : " +str.toUpperCase());
}
Output :
12. trim() : The trim method removes the spaces at the starting and end of the string and returns the string without spaces at the ends.
public static void main(String[] args) {
String str = " CherCher.tech ";
System.out.println("Length before trim : " +str.length());
System.out.println("Length after trim : " +str.trim().length());
}
Output :
Below are the few facts about the strings in java; these are about strings only not about String class.
StringBuffer class is used to create mutable strings, which means we can alter the value of the string after we create it.
It represents a 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 that multiple threads can access the String value.
Constructors of StringBuffer : StringBuffer has 4 constructors which are :
Navigation methods in Selenium
Let's discuss a 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
str.append("tech");
System.out.println("Str after append : "+str);
str.append(10);
System.out.println("append with number: "+str);
str.append(false);
System.out.println("append boolean: "+str);
}
Output :
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
str.reverse();
System.out.println("Str after reverse : " +str);
}
Output :
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 :
insert(indexToinsert, contentToInsert) : insert method helps the 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 :
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 :
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());
sb.append("12345678");
System.out.println("Capacity after 8 chars: "+sb.capacity());
sb.append("12345678123456781");
System.out.println("Capacity after 18 chars: "+sb.capacity());
}
Output :
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 the String object, a new string object is created with modified content.
The below example explains how the Strings are immutable.
public class StringImmutability {
public static void main(String[] args) {
String str1 = "CherCher.tech";
System.out.println("Address of str1 : "+System.identityHashCode(str1));
str1 = "selenium-webdriver.com";
System.out.println("Address of str1 after change : "+System.identityHashCode(str1));
}
}
Output :
The below example explains the String created by StringBuffer is Mutable. The 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("CherChr.tech");
System.out.println("Address of str1 : "+System.identityHashCode(sb1));
sb1.replace(0, sb1.length()-1, "selenium-webdriver.com");
System.out.println("Address of str1 after change : "+System.identityHashCode(sb1));
}
}
Output :
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 the 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).