What other classes exist ?
To perform Operations with the String data , C and C++ programming languages have provided a set of predefined functions like concat(), trim(), equals(), strlen(),….
Similarly , to perform String operations in Java, JAVA programming language has provided the following predefined classes.
java.lang.Stringjava.lang.StringBufferjava.lang.StringBuilderjava.util.StringTokenizer
Q) What are the differences between String and StringBuffer?
- String class objects are immutable objects, where the immutable objects are not allowing modifications on their content directly, here the immutable object data is allowed for the modifications but the modified resultant data will not be stored back in the original object, here the resultant modified data will be stored by creating another new object of the same class.
StringBuffer class objects are mutable objects, where the mutable objects are able to allow modifications directly on their content.
- String class objects are fixed length objects, that is the data which is available in the String class object is having fixed length.
StringBuffer class objects are variable length objects, that is the data which is available in the StringBuffer class object is having variable length.
Q) What are the differences between StringBuffer and StringBuilder?
- StringBuffer was introduced in JDk1.0 version.
StringBuilder was introduced in JDK1.5 version.
- StringBuffer is a synchronized resource.
StringBuilder is a non synchronized resource.
- StringBuffer allows only one thread at a time to execute the application.
StringBuilder allows more than one thread at a time to execute the application.
- StringBuffer follows sequential execution.
StringBuilder follows parallel execution.
- StringBuffer will increase application execution time.
StringBuilder will reduce application execution time.
- StringBuffer will reduce application performance.
StringBuilder will increase application performance.
- StringBuffer is giving guarantees for the data consistency.
StringBuilder is not giving guarantee for the Data Consistency.
- Majority of the methods in StringBuffer are synchronized.
No Method is synchronized in Stringbuilder.
Strings – Introduction
Anything within double quotes is treated as String.
“Telusko”
Collection or series of characters enclosed within double quotes “” is called String in Java.
String is a class in Java.
In Java, string data is treated as an Object. String is a class.
Strings in Java are immutable, meaning, such string objects which would not change once it is created.
Create String object
To create immutable string objects, we use String class.
// different ways of creating immutable String in Java
String str = "Java"; // stores in String constant pool in Heap area
String str = new String("Java"); // creates object in Heap area
char[] chars = {'J', 'a', 'v', 'a'};
String str = new String(chars);
How String objects get created
String interning
If you create String objects using direct string literal, then that String data gets resolved at compile time and String objects get created in the String constant pool in the heap area.
In Java, the “string constant pool” (also known as the “string pool”) is a special area of memory where the JVM (Java Virtual Machine) stores a pool of string literals. It is a mechanism that the Java platform uses to optimize memory usage and improve performance when working with strings.
String Interning: When you create a string literal (e.g., “Hello”), Java checks if the string already exists in the constant pool. If it does, a reference to the existing string object is returned. If not, a new string object is created and added to the pool.
It helps save memory because it ensures that identical string literals are not duplicated. Instead, multiple references point to the same string object in the pool. This is especially useful when you have many strings with the same content.
// A new string object "Hello" is created in the pool.
String str1 = "Hello";
// Since "Hello" already exists in the pool, str2 points to same object as str1.
String str2 = "Hello";
// Outputs true, as they refer to the same object.
System.out.println(str1 == str2);
// A new string object is created, but it's not in the constant pool.
String str3 = new String("Hello");
// Outputs false, as they reference different objects.
System.out.println(str1 == str3);
// Outputs true, as their content is the same.
System.out.println(str1.equals(str3));
It’s important to note that the constant pool is specific to string literals and only applies to strings created using string literals (e.g., “Hello”). If you create strings using the new keyword, they are not automatically added to the pool.
Q) Does garbage collect reclaim string objects in the String constant pool ?
In Java, the string constant pool is a special area of memory where string literals are stored. Unlike objects created in the regular heap memory, objects in the string constant pool are managed by the JVM, and you generally don’t have direct control over their disposal.
String literals in the constant pool are created when your Java program loads and are typically not eligible for garbage collection during the lifetime of the program. They persist throughout the execution of the program. The JVM manages the constant pool and ensures that string literals are available for the entire duration of the application.
Objects created in the heap memory, whether they are strings or other types of objects, can be garbage collected when they are no longer reachable. However, this doesn’t apply to string literals in the constant pool.
In summary, string objects in the string constant pool are not typically subject to garbage collection during the execution of a Java program. They remain in the constant pool for the entire lifetime of the application.
Adding Strings to String constant pool
Using the intern() Method
You can manually add a string to the string constant pool using the intern() method. This method returns a reference to the equivalent string from the pool if it exists or adds it to the pool if it doesn’t.
String str1 = new String("Hello").intern(); // Explicitly interns the string.
If you want to intern a string created with new into the constant pool, you can explicitly use the intern() method.
String Class Library:
Constructors:
1. public String():
It can be used to create a String class object without data.
public class Test {
public static void main(String[] args) {
String str = new String();
System.out.println(str);
}
}
2. public String(String data):
It can be used to create a String class object with the provided String data.
public class Test {
public static void main(String[] args) {
String str = new String("Durga Software Solutions");
System.out.println(str);
}
}
Durga Software Solutions
In the above program, when we pass a String class object reference variable as parameter to System.out.println() method then JVM will access toString() method over the provided String class reference variable internally.
In the above context, JVM will search for the toString() method in the String class, String class has its own toString() method and it is not dependent on the Object class provided toString() method, String class has overridden Object class provided toStgring() method in such a way that to return a String that contains the content of the String object.
Q) What is the difference between the following two statements?
String str = “abc”;String str = new String(“abc”);
1. String str = “abc”;
This statement will create a String class object in the String Constant Pool Area that is in Method Area.
2. String str = new String(“abc”);
This Statement will create String objects in both String Constant Pool Area and in Heap Memory.
2. If any object is created in String constant pool area then that Object is not eligible for the Garbage Collection, where the Objects which are created in the String Constant Pool area are destroyed automatically when the Application execution is terminated or when the JVM is in shutdown mode or when the JVM free up the total memory which was assigned to the program execution.
If any object is created in Heap memory then that object is eligible for the Garbage Collection.
3. If any object is created in the String Constant Pool Area then that object is reusable object, if we are trying to create a String object some data in String Constant pool ARea then JVM will check that whether any object is already existed with the same data or not, if any object exist already with the same data then JVM will not create new object, instead JVM will reuse the existed object reference value to the new reference variable.
If we are trying to create any object in the Heap memory by using new keyword then that object is not reusable object, if we are trying to create a new object by using “new” keyword in the Heap memory then JVM will create a new object with the data without checking whether any object is existed with the same data or not.
3. public String(byte[] b):
It can be used to create a String class object with the String equivalent of the specified byte[] , where byte[] represents the ASCII values of the characters.
public class Test {
public static void main(String[] args) {
byte[] bytes = { 65, 66, 67, 68, 69, 70 };
String data = new String(bytes);
System.out.println(data);
}
}
ABCDEF
4. public String(byte[] b, int startIndex, int numberOfElements):
It can be used to create a String class object with the String equivalent of the specified byte[] which starts from the specified start index and up to the specified number of elements.
public class Test {
public static void main(String[] args) {
byte[] bytes = { 65, 66, 67, 68, 69, 70 };
String data = new String(bytes, 1, 3);
System.out.println(data);
}
}
BCD
Note: The above two constructors are used to convert the data from byte[] to String.
5. public String(char[] ch):
It can be used to create a String class object with the String equivalent of the specified char[].
public class Test {
public static void main(String[] args) {
char[] chars = {'A', 'B', 'C', 'D', 'E', 'F'};
String data = new String(chars);
System.out.println(data);
}
}
ABCDEF
6. public String(char[] chars, int startIndex, int numberOfElements):
It can be used to create a String class object with the String equivalent of the specified char[] which starts from the specified start index and up to the specified number of elements.
public class Test {
public static void main(String[] args) {
char[] chars = {'A', 'B', 'C', 'D', 'E', 'F'};
String data = new String(chars, 1, 3);
System.out.println(data);
}
}
BCD
Note: The above two Constructors are able to convert the data from the char[] to String.
String class Methods
1. public int length():
It can be used to return the size of the String object.
public class Test {
public static void main(String[] args) {
String str = new String("Durga Software Solutions");
System.out.println(str);
System.out.println(str.length());
}
}
Durga Software Solutions
24
2. public String equals(Object obj):
It will compare two String objects data.
Q) What is the difference between == operator and equals() method?
In Java, == operator is a boolean operator or a comparison operator, it will check whether two operand values are the same or not, where the operands may be normal primitive variables or Object reference variables.
Initially, equals() was defined in the java.lang.Object class, it was implemented in such a way that to perform two objects references comparison, String class is not dependent on the Object class provided equals() method, String class has its own equals() method, String class has overridden the Object class provided equals() method in such a way that to perform two String objects contents comparison instead of two String objects references comparison.
class A{
}
public class Test {
public static void main(String[] args) {
int i = 10;
int j = 20;
A a1 = new A();
A a2 = new A();
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(i == j);// false
System.out.println(a1 == a2);// false
System.out.println(str1 == str2);// false
System.out.println(a1.equals(a2));// false
System.out.println(str1.equals(str2));// true
}
}
false
false
false
false
true
3. public boolean equalsIgnoreCase(Object obj):
In the String class, equals() method will perform case sensitive comparison, but equalsIgnoreCase() method will perform case insensitive comparison.
public class Test {
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("ABC");
System.out.println(str1.equals(str2));// false
System.out.println(str1.equalsIgnoreCase(str2));// true
}
}
false
true
4. public int compareTo(Object obj):
It can be used to compare two String objects content as per the dictionary order.
str1.compareTo(str2);
1. If str1 comes first when compared with str2 in dictionary order then the compareTo() method will return -ve value.
2. If str2 comes first when compared with str1 in dictionary order then the compareTo() method will return +ve value.
3. If str1 and str2 are at the same position in the dictionary order then the compareTo() method will return ‘0’.
public class Test {
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("xyz");
String str3 = new String("abc");
System.out.println(str1.compareTo(str2)); // "abc".compareTo("xyz");==> -ve
System.out.println(str2.compareTo(str3)); // "xyz".compareTo("abc");==> +ve
System.out.println(str3.compareTo(str1)); // "abc".compareTo("abc");==> 0
}
}
-23
23
0
5. public boolean startsWith(String data):
It can be used to check whether a string starts with the specified String or not.
6. public boolean endsWith(String data):
It can be used to check whether a String ends with the specified String or not.
7. public boolean contains(String data):
It can be used to check whether a String contains the specified String or not.
public class Test {
public static void main(String[] args) {
String data = new String("Durga Software Solutions");
System.out.println(data);
System.out.println(data.startsWith("Durga"));
System.out.println(data.endsWith("Solutions"));
System.out.println(data.contains("Software"));
}
}
Durga Software Solutions
true
true
true
8. public char charAt(int index)
It can be used to return a character which is available at the specified index value.
9. public String replace(char oldChar, char newChar):
It can be used to replace the specified old character with the new character in a String.
public class Test {
public static void main(String[] args) {
String data = new String("Durga Software Solutions");
System.out.println(data);
System.out.println(data.charAt(6));
System.out.println(data.replace('S', 's'));
}
}
Durga Software Solutions
S
Durga software solutions
10. public int indexOf(String str):
It will return an index value where the specified Strings first occurrence exists.
11. public int lastIndexOf(String str):
It will return an index value where the specified Strings last occurrence exists.
public class Test {
public static void main(String[] args) {
String data = new String("Durga Software Solutions");
System.out.println(data);
System.out.println(data.indexOf("So"));
System.out.println(data.lastIndexOf("So"));
}
}
Durga Software Solutions
6
15
12. public String concat(String data):
It can be used to add the provided String data to the String object content in an immutable manner.
public class Test {
public static void main(String[] args) {
String str1 = new String("Durga ");
String str2 = str1.concat("Software ");
String str3 = str2.concat("Solutions");
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
}
Durga
Durga Software
Durga Software Solutions
Note: In Java applications, we are able to perform the concatenation operation by using ‘+’ operator also.
13. public String subString(int startIndex)
It can be used to generate a Substring from a String which starts from the specified start index.
14. public String subString(int startIndex, int endIndex):
It can be used to generate a Substring from a String which starts from the specified start index and up to the specified end index.
public class Test {
public static void main(String[] args) {
String data = new String("Durga Software Solutions");
System.out.println(data.substring(6));
System.out.println(data.substring(6, 14));
}
}
Software Solutions
Software
15. public byte[] getBytes():
It can be used to convert the data from String type to the equivalent byte[].
public class Test {
public static void main(String[] args) {
String data = new String("Durga Software Solutions");
byte[] bytes = data.getBytes();
for(int index = 0; index < bytes.length; index++) {
System.out.println(bytes[index]+ " -----> "
+(char)bytes[index]);
}
}
}
68 -----> D
117 -----> u
114 -----> r
103 -----> g
97 -----> a
32 ----->
83 -----> S
111 -----> o
102 -----> f
116 -----> t
119 -----> w
97 -----> a
114 -----> r
101 -----> e
32 ----->
83 -----> S
111 -----> o
108 -----> l
117 -----> u
116 -----> t
105 -----> i
111 -----> o
110 -----> n
115 -----> s
16. public char[] toCharArray():
It can be used to convert the data from the String type to the equivalent char[].
package com.durgasoft.test;
public class Test {
public static void main(String[] args) {
String data = new String("Durga Software Solutions");
char[] chars = data.toCharArray();
for(int index = 0; index < chars.length; index++) {
System.out.print(chars[index]+" ");
}
}
}
D u r g a S o f t w a r e S o l u t i o n s
17. public String split(String delimiter):
It can be used to divide the provided String into the number of tokens in the form of String[] on the basis of the provided elimiter.
package com.durgasoft.test;
public class Test {
public static void main(String[] args) {
String data = new String("Durga Software Solutions");
String[] tokens = data.split(" ");
for(int index = 0; index < tokens.length; index++) {
System.out.println(tokens[index]);
}
}
}
Durga
Software
Solutions
18. public String trim():
It can be used to remove pre spaces and post spaces of a particular String.
public class Test {
public static void main(String[] args) {
String data = new String(" Durgasoft ");
System.out.println(data);
System.out.println(data.trim());
}
}
Durgasoft
Durgasoft
19. Public String toUppercase():
It can be used to convert the String data into the upper case letters.
20. public String toLowerCase():
It can be used to convert the data to lower case letters.
public class Test {
public static void main(String[] args) {
String data = new String("Durga Software Solutions");
System.out.println(data.toLowerCase());
System.out.println(data.toUpperCase());
}
}
durga software solutions
DURGA SOFTWARE SOLUTIONS
In Java applications, if we perform any operation over the String data then JVM will create a new String object whenever the new data is created from the respective String operations, if new data is not created from the respective String operation then JVM will not create a new String object JVM will share the existing String object reference value to the new reference variable.
public class Test {
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = str1.concat("");
System.out.println(str1 == str2); // true
}
}
public class Test {
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = str1.concat(" ");
System.out.println(str1);//abc
System.out.println(str2);//abc
System.out.println(str1 == str2);
}
}
abc
abc
false
public class Test {
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = str1.trim();
System.out.println(str1);
System.out.println(str2);
System.out.println(str1 == str2);
}
}
abc
abc
true
String Operations
Comparing Strings
compareTo() method
This method is used to compare strings. This method returns an integer as a result.
Concatenating Strings
concat() method
+ operator
Whenever you have a direct string literal, one copy must be there in the string constant pool.
Whenever you involve a reference variable, or new keyword or inbuilt method, in spite of an object getting created in the string constant pool, the object also gets created in the heap area and that will be referenced. [ above, check examples, s3, and s4]
Concatenating strings : ‘+’operator v/s concat() method
- Using the concat() method, we can’t add null values.
- However, using the ‘+’ operator, we can add null values.
Using the concat(), we can’t add any other values other than strings. However with ‘+’ operator, we can add values of any type to existing string object.
NOTE – final concept is different, immutable string concept is different. If a variable is final, we cannot be able to change its value once initialized. However, for strings, though they are immutable, we can assign a new string object to the string reference variable.
Immutable object means that object cannot be modified. But the reference variable can be assigned a new object.
StringBuffer
Creating StringBuffer object
With StringBuffer (or) StringBuilder, we can’t directly assign string literals. We have to create objects only.
Default capacity – 16
capacity() – how does it work ??
StringBuffer sb = new StringBuffer("hello");
System.out.println(sb.capacity()); // 21
StringBuffer sb1 = new StringBuffer();
sb1.append("hello");
System.out.println(sb1.capacity()); // 16
When we create a StringBuffer object with a string at the declaration itself, then the capacity will be calculated as – string length + default capacity – in our case, 5 + 16 = 21.
When we create an empty StringBuffer object, then the default capacity is allocated, which is 16. Till the default capacity is exhausted, the capacity remains the same. Once the capacity is exhausted, new capacity is calculated with formula : (2 * old capacity) + 2
StringBuffer is a thread safe class. All methods are synchronized. Decreases performance.
StringBuilder is a non-thread safe class.
public StringBuffer()
It can be used to create a StringBuffer class object without the data but with the 16 elements initial capacity.
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
System.out.println(sb);
System.out.println(sb.capacity());
}
}
16
public StringBuffer(String data)
It can be used to create a StringBuffer class object with the provided data, where the capacity value will be increased like below.
NewCapacity = InitialCapacity+data.length();
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abc");
System.out.println(sb);
System.out.println(sb.capacity());
}
}
abc
19
public StringBuffer(int capacity)
It can be used to create a StringBuffer class object with the provided capacity value.
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(20);
System.out.println(sb.capacity());
}
}
20
Methods :
1. public int capacity():
It will return the capacity value of the Stringbuffer.
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abc");
System.out.println(sb);
System.out.println(sb.capacity());
}
}
abc
19
2. public StringBuffer append(String data):
It is able to append the provided String data to the StringBuffer object content as per the mutable nature.
public class Test {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("Durga ");
StringBuffer sb2 = sb1.append("Software ");
StringBuffer sb3 = sb2.append("Solutions");
System.out.println(sb1);
System.out.println(sb2);
System.out.println(sb3);
}
}
Durga Software Solutions
Durga Software Solutions
Durga Software Solutions
3. public ensureCapacity(int capacity)
This method can be used to provide a particular capacity value to the StringBuffer object explicitly.
- If the provided capacity value is less than 16 then the capacity value set to the StringBuffer is 16.
- If the provided capacity value is between 16 and 34 then the capacity value set to the StringBuffer is 34.
- If the provided capacity value is greater than 35 then the capacity value set to the StringBuffer is the specified value.
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity());
sb.ensureCapacity(35);
System.out.println(sb.capacity());
}
}
16
35
4. public StringBuffer reverse()
It can be used to reverse the StringBuffer object content.
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Durga Software Solutions");
System.out.println(sb);
System.out.println(sb.reverse());
}
}
Durga Software Solutions
snoituloS erawtfoS agruD
5. public StringBuffer insert(int index, String data):
It can be used to insert the specified data at the specified index.
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Durga Solutions");
System.out.println(sb);
System.out.println(sb.insert(6, "Software "));
}
}
Durga Solutions
Durga Software Solutions
6. public StringBuffer delete(int startIndex, int endIndex):
It can be used to delete the String from the StringBuffer object which starts from the specified start index and up to the specified end index.
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Durga Software Solutions");
System.out.println(sb);
System.out.println(sb.delete(6, 15));
}
}
Durga Software Solutions
Durga Solutions
== and equals() method on StringBuffer
StringBuffer (or) StringBuilder class has not overridden equals() method. So, it compares references only which is the default behavior of the Object class.
To compare string and stringbuffer, we need to use contentEquals() method.
StringTokenization
Q) What is String Tokenization and how is it possible to perform String Tokenization in the Java application?
The process of dividing a String into the number of pieces or Tokens is called String Tokenization.
In general, we will use String Tokenization in the following areas
- To prepare Lexical Analysis in the Compiler COnstruction.
- To perform Data Validations.
- To perform Pattern checking in Regular Expressions.
- To prepare Circuits design
- To perform Security implementations
- ——-
- ——–
To perform String Tokenization in Java applications , JAVA has provided a predefined class in the form of “java.util.StringTokenizer”. To perform String Tokenization in Java applications we have to use the following steps.
- Create a
StringTokenizerclass object by providing String data. - Read tokens from the StringTokenizer object.
Create a StringTokenizer class object by providing String data:
To create a StringTokenizer class object we have to use the following constructors.
public StringTokenizer(String data)
It will perform String Tokenization over the provided data by using the default delimiter[Separator]
public StringTokenizer(String data, String delimterInRegularExpression)
It will perform String Tokenization over the provided data by using the provided delimiter[Separator]
EX:StringTokenizer st = new StringTokenizer(“Durga Software Solutions”);
When we execute the above instruction, JVM will perform the following actions.
- JVM will recognize the provided String data to tokenize and the provided or default delimiter.
- JVM will divide the complete String into the number of tokens on the basis of the provided or default delimiter.
- JVM will create a StringTokenizer class object with the generated tokens.
Note: When a StringTokenizer class object is created with the tokens , automatically a cursor or a pointer will be created before the first token in the StringTokenizer object in order to retrieve tokens from the StringTokenizer object.
Read tokens from the StringTokenizer object:
To read tokens from the StringTokenizer object we have to use the following steps.
- Check whether more tokens are available or not from the current cursor position by using the following method.
public boolean hasMoreTokens()
It will check atleast next token is available or not, if the next token is available then it will return true value otherwise it will return false value.
- If atleast next token is available from the current cursor position then read the next token and move the cursor to the next position.
public String nextToken()
To get the tokens count from the StringTokenizer class object we have to use the following method.
public int countTokens()
package com.durgasoft.test;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
StringTokenizer stringTokenizer =
new StringTokenizer("Durga Software Solutions");
int tokens = stringTokenizer.countTokens();
System.out.println("No Of Tokens : "+tokens);
while(stringTokenizer.hasMoreTokens()) {
System.out.println(stringTokenizer.nextToken());
}
}
}
No Of Tokens : 3
Durga
Software
Solutions
package com.durgasoft.test;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
StringTokenizer stringTokenizer =
new StringTokenizer("02-12-2023","-");
while(stringTokenizer.hasMoreTokens()) {
System.out.println(stringTokenizer.nextToken());
}
}
}
02
12
2023
Takeaways
String is treated as an Object in Java.
String is a collection of characters within double quotes “ “ is considered a String object in Java.
Anything and everything between double quotes is treated as a String object.
( “ “, “ 123”, “A”, “@#$”, “Telusko” )
There are 2 types of string objects :
1. Immutable string → String class is used to create Immutable String object
2. Mutable String → StringBuffer / StringBuilder classes are used to create Mutable String objects.
Immutable string object is such an object which cannot be changed once it’s created.
Mutable string object is such an object which can be changed once it is created.
There are 2 usual ways to create Immutable String object:
String s = “Telusko”; → String constant pool of heap area (Only once – duplicates are not allowed)
String s = new String(“Telusko”); → Heap area and reference is referring to heap area string object. One copy also will be maintained on SCP by JVM with implicit references (Hence if we use a new keyword – 2 string objects get created) .
Ways to compare string :
== → references of strings are compared
equals() —> actual string object is compared. StringBuffer/StringBuilder, this method is not overridden, so for those classes, references are compared.
equalsIgnoreCase() – actual string object will be compared ignoring case sensitivity.
compareTo() – string objects are compared lexicographically char by char considering ASCII representation of each char.