String in Java

Java string can be created in several ways. In this tutorial, we will see how to create a string. Here we will see substring in java and how to get substring java.

Here is the table content of the article we will cover this topic.
1. What is String in Java?
2. Properties of Java String?
3. Creation of string by string literal?

i) How does it work in a string constant pool?
4.
Creation of string object by use of new keyword in java?
i) How does String work in heap memory and string constant pool?
5. Declaring string in java?
6.
String initialization in Java?
7. String literal VS String by new keyword?
8. StringBuilder in java?
i) How to create a string by StringBuilder?
ii) Some important constructors?
iii) Important methods of StringBuilder?

9. StringBuffer in java?
i) How to create a string by StringBuffer?
ii) Some important constructors?
iii) Important methods of StringBuilder?

10. Difference between String and StringBuffer in java?
11. Difference between String and StringBuilder in java?
12. Difference between StringBuilder and StringBuffer?

What is String in Java?

In a recent post, we have seen String in java and discussed how many ways to create a string in java. In this post, we will be discussing Java String and String class in java.

Definition of string
A String is a sequence of characters or group of characters, A string meaning it can have a group of characters like “JavaGoal”, here the string “JavaGoal” contains multiple characters that are ‘J’, ‘a, ‘v’, ‘a’, ‘G’, ‘o’, ‘a’, ‘l’. String class that presents in java.lang package.

String class in java

Java string class exists in java.lang package and implementing three interfaces that are Serializable, Comparable, and CharSequence.
The string is a class in java that is used to create the object of String type. The object of the String class always contains a string(a group of characters). Suppose you want to store your name in a variable then you can create an object of String class and assign the name to the object.

string class in java

In the above example, we are creating an object of the String class and assigning a string that is “JavaGoal” to the object. There are some other ways to create an object of the String class we will discuss them later.

Properties of Java String

1. As we know string is a group of characters, but a java String always be an object and it can’t be a primitive type.

2. Whenever we want to create a string(Group of characters), we need to an object of type String.

3. To create a string the sequence of characters enclosed within double quotes ” “.

4. In java String class is the final class, so we can’t extend it.

5. The objects of String are immutable which means a constant and cannot be changed once created. If we try to change it, the JVM creates a new string object in the background. We will discuss in detail how the string is immutable.

NOTE: Each object created by the String class is immutable. We will discuss it later in the immutable string.

How to create a string? 

There are two ways to create the string by using the String class. We can create an object of String by string literal and new keyword. Whenever we create a string, it always stores in String constant pool. Let us see how we can create an object of String in both ways.

Creation of string by string literal

The most common way to create a string is by the string literal. In this case, a string literal is enclosed with double quotes. Whenever we create a string by java string literal the JVM creates an object of String. Let us see how we create a string by use of a string literal:

String class in java

String: To create an object by string literal we use the String class.
referenceVariable: is the name of a variable that holds the object of String.
“string”: In simple terms, it is a group of characters, but it is considered an object of the String class.

String nameOfStudent = “Ravi”;
String s = "Hi";
String obj1 = "Hello";
String obj  = "123";

Here nameOfStudent is the object of String and the value of the object is Ravi.

Whenever we create a string by String literal it always stores in the string constant pool. The string constant pool is part of the heap memory. Let’s see how to string is stored in memory.

How does it work in a string constant pool?

Step 1: When we create a string by use of String literal. Firstly, JVM checks whether that string is already presented in the string constant pool or not.
Step 2: If the created string already exists in the String constant pool, then JVM returns the reference of the existing string.
Step 3: If the string doesn’t exist in the String constant pool, a new string object is created in the string constant pool.

String name = “Ravi”;

When JVM executes the above statement, it performs all the operations mentioned above. Step1: Firstly, it checks the string “Ravi” in String constant pool. Step2:  But there is no string stored in String constant pool. Step3: So, now a new Object of String is created in String constant pool.

String class in java

Now, create another String object with value.

String name2 = “Ravi”;

When JVM executes the above line, it will again perform all the steps again:

Step1: Firstly, it checks the string “Ravi” in String constant pool.
Step2: As you know “Ravi” already Exists in String constant pool. So JVM will return the reference of an existing object

String class in java

Creation of string object by use of new keyword in java

We can create a String by use of new keyword in java. String class has many constructors that take the characters in different forms and create the string. We will discuss how we can create String by use of the constructor.

String class in java

String: To create an object we use the String class.
nameOfObj: nameOfObj is the name of a variable that holds the object of String.
new: It is an operator that is used to call the constructor of the String class.
string(“groupOfCharacters”): It is a constructor that accepts the string(a group of characters). You can read all the string constructors.

String name = new String("Hi");
String obj = new String("123");
String obj1 = new String("Java Goal"); 

NOTE: If we don’t provide any parameter(string) in the constructor, then it will create a blank String in heap memory. Whenever we create the String by new keyword then JVM will create a new String in heap memory and place the same string in String constant pool.

String name = new String(); 

Another example of a String object:

String name2 = new String(“Ravi”);

When JVM executes the above statement, it creates the new object of String in heap memory and also places the same string in String constant pool. The value of the object is Ravi.

String class in java

How does String work in heap memory and string constant pool?

Whenever we create a string object with a new keyword. It always stores in the heap memory and string constant pool. Let’s see how does string stores in memory.

Step 1: When we create a string by the use of a new keyword. JVM creates a new string object in the heap memory whether it exists in the heap or not. After that JVM checks whether that string is already presented in the string constant pool or not.
Step 2: If the created string already exists in the String constant pool, then JVM doesn’t create it again.
Step 3: If the string doesn’t exist in the String constant pool, a new string object is created in the string constant pool.

NOTE: When we create a java string object by a new keyword, JVM creates two objects in memory. Firstly, it creates the object in Heap memory after that it will create in String constant pool.

String name = new String("JavaGoal");
String name1 = new Sting("JavaGoal");

When JVM execute the above statement, it performs all the operation mentioned above.

Step 1: Firstly, it creates a new String object in heap memory with the value “JavaGoal” and returns the object reference to “name“. After that JVM checks the string “JavaGoal” in String constant pool.

Step 2:  But there is no string stored in String constant pool.

Step 3: So, now it will create a new Object of String created in the String constant pool.

Step4: Now it will execute the second line and it will create again a new object in heap memory with value “JavaGoal” and return the object reference to “name1“. After that JVM will check the string “JavaGoal” in String constant pool.

Step 5: Now the “JavaGoal” string is already presented in String constant pool. So it will not create an object again.

String class in java
public class StringExample 
{
    public static void main(String[] arg) 
    {
    	String name1 = ""; // blank string by string literal 
    	String name2 = new String(""); // blank string by new  keyword 
    	String name3 = "Hi"; // Creating string by string literal 
    	String name4 = new String("Hi"); // Creating string by new keyword 
    	String name5 = "Hi"; // Creating string by string literal 
    	String name6 = new String("Hi"); // Creating string by new keyword literal 
    	String name7 = "Hi JavaGoal"; // Creating string by string literal 
    	String name8 = new String("Hi JavaGoal"); // Creating string by new keyword 
    	
    	System.out.println("Are name1 and name2 same : "+ (name1 == name2));
    	System.out.println("Are name3 and name4 same : "+ (name3 == name4));
    	System.out.println("Are name3 and name5 same : "+ (name3 == name5));
    	System.out.println("Are name4 and name6 same : "+ (name4 == name6));
    	System.out.println("Are name1 and name2 same : "+ (name7 == name8));
    }
}

Output: Are name1 and name2 same : false
Are name3 and name4 same : false
Are name3 and name5 same : true
Are name4 and name6 same : false
Are name1 and name2 same : false

Declaring string in java

Like other variables, we have to declare a reference variable for the string. Let’s see the java string syntax:

String class in java
String s;
String name;
String obj;

String initialization in Java

We have already seen we can initialize a string at the time of declaration. Here we will see how to initialize a string if it is already declared. The initialization can be done by the string literal or new keyword. If we want to use String literal then the values which we assign to the string should be enclosed with the double quotes ” ”. But if we want to initialize by the new keyword then we must choose the constructor of the string class.

String class in java
String s;
String name;
String obj;
s = "Hi";
name = "JavaGoal";
obj = "Hello"
s = new String("Hi");
name = new String("JavaGoal");
obj = new String("Hello");

String literal VS String by new keyword

Different memory use

String literal always uses the String constant pool to store the string objects. The String constant pool is part of heap memory.
When we create a string by a new keyword then JVM creates two objects in memory. Firstly, it creates the object in Heap memory after that it creates in String constant pool.

String name = “Ravi”; // Creating object in String constant pool

String address = new String(“CHD”); // Creating an object in heap memory and String constant pool.

String address1 = new String(“CHD”); // Creating an object in Heap memory but it will not create an object in String constant pool because this string is already present in<strong> pool.

String address2 = “CHD”; // It will not create any object in string constant pool because this string is already existing in the pool. So JVM will return the reference of an existing string.
String class in java

Reuse String

As you know string literal always stores in String constant pool. Whenever we create a string object by the string literal, JVM checks the string literal in String constant pool. If the string already exists in String constant pool, then JVM returns the same reference of an existing string. It doesn’t create a new string.
When we create the string by use of a new keyword, the JVM always creates a new string reference, even if the string exists in the heap memory. It creates two objects one is in heap memory and another is in String constant pool.

String name = “Ravi”;
String name1 = “Ravi”; 
String address = new String(“CHD”); 
String address1 = new String(“CHD”);
String class in java

StringBuilder in java

As we already know String class is used to create the immutable string in java. We have learned a lot of operations and methods on the immutable string. Now we will learn the StringBuilder in java, how to create a mutable string by StringBuilder, and StringBuilder methods in java.

Here is the table content of the article will we will cover this topic.
1. StringBuilder class in java
2. How to create a string by StringBuilder
3. Some important constructors
4. Important methods of StringBuilder

StringBuilder class in java

We can create a mutable string by use of the StringBuilder class. The StringBuilder class is placed in java.lang package. Serializable, Comparable, and CharSequence are three interfaces that are implemented by the StringBuilder class.

stringbuilder class in java

StringBuilder class is used to create a mutable string, by means of a mutable string, we can modify the string without creating a new object. The StringBuilder class is the same as the StringBuffer class except for thread-safe.

How to create a string by StringBuilder

To create a string by StringBuilder class we need to understand the Constructor of StringBuilder. Each constructor creates an object of StringBuilder that holds the string. Let’s take an example and create a string by use of the default constructor of StringBuilder.

public class StringBuilderExample
{
   public static void main(String args[])
   {
	   StringBuilder str = new StringBuilder();
	   System.out.println("Is it blank string: "+ (str.length() == 0));
	  
	   str.append("Hello");
	   System.out.println("Value after append: "+str);
   }
}

Output: Is it blank string: true
Value after append: Hello

Some important constructors

1. StringBuilder(): It is used to declare an empty string builder. Its initial capacity is 16.
2. StringBuilder(String str): It is used to declare a string builder with some specified value.
3. StringBuilder(int capacity): It is used to declare an empty string builder with a specified capacity.

1. StringBuilder()

The default constructor of the StringBuilder class creates an empty string builder object. This constructor doesn’t have any parameters. Its initial capacity is 16 which is provided by JVM at the time of object creation of StringBuilder.

StringBuilder name =  new StringBuilder();
class ExampleOfStringBuilder
{
  public static void main(String args[])
  {
    // creating a blank string
    StringBuilder name = new StringBuilder(); 
    // If name is blank its length is equals to 0 
    System.out.println("Is name is blank = "+ (name.length() == 0)); 
    // Display the capacity of name
    System.out.println(name.capacity()); 
  }
}

Output: Is name is blank = true
16

Memory representation:

                               
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

2. StringBuilder(String str)

It takes a string as a parameter that uses to create a string builder object with a specified string. This constructor takes one parameter of string type. Its initial capacity is 16 which is provided by JVM at the time of object creation of StringBuilder.

StringBuilder name =  new StringBuilder(specifiedString);
class ExampleOfStringBuilder
{  
	public static void main(String args[])
	{  
		// creating a StringBuilder with specified string
		StringBuilder name = new StringBuilder ("Ravi"); 
		System.out.println("Name of Student = "+ name); 
		System.out.println(name.capacity()); // Display the capacity of name
	}
}  

Output: Name of Student = Ravi
20

Memory representation:

3. StringBuilder(int capacity)

It takes a parameter as the capacity of the string and creates a blank string builder object with a specified capacity. This constructor takes one parameter of integer type. If you want to specify the capacity of string Builder you should use this constructor.

StringBuilder name =  new StringBuilder(int capacity);
class ExampleOfStringBuilder
{
  public static void main(String args[])
  {
    // creating a StringBuilderwith specified capacity
    StringBuilder name = new StringBuilder (10); 
    name.append("Ravi"); // Appending string in string buffer
    System.out.println("Name Of Student = "+ name);  
    System.out.println(name.capacity()); // Display the capacity of name
  }
}

Output: Is name is Student = Ravi
10

Memory representation:

R a v i              
0 1 2 3 4 5 6 7 8 9 10

Important methods of StringBuilder

1. append() method

This method is used to append the given text in a string.

class ExampleOfStringBuilder
{  
	public static void main(String args[])
	{  
                // creating a StringBuilder with specified string
                StringBuilder name = new StringBuilder("Ravi"); 
		name.append("kant"); // Appending string in string builder
		System.out.println("Name of Student = "+ name); 		
	}
}  

Output: Name of Student = Ravikant

2. insert() method

This method is used to insert the given text in the string at a given position.

class ExampleOfStringBuilder
{  
	public static void main(String args[])
	{  
		// creating a StringBuilder with specified string
                StringBuilder name = new StringBuilder("Ravi"); 
                // inserting string in string buffer
		name.insert(4, "kant"); 
		System.out.println("Name of Student = "+ name);		
	}
}  

Output: Name of Student = Ravikant

3. replace(startIndex, endIndex, string) method

This method is used to replace the string by given text. The replace() replaces the given string from the specified startIndex and endIndex.

class ExampleOfStringBuilder
{  
	public static void main(String args[])
	{  
		// creating a StringBuilder with specified string
		StringBuilder name = new StringBuilder("Ravi kant"); 
		name.replace(5, 7, "OK");
		System.out.println("Name of Student = "+ name);	
         }
} 

Output: Name of Student = Ravi OKnt

StringBuffer in java

In java String class is used to create the immutable string in java. We can perform different operations on the string by using methods. The string created by the String class is always immutable in java and We have learned the methods on the immutable string. In this post, we will learn the StringBuffer in java, mutable string by StringBuffer, and StringBuffer methods in java.

Here is the table content of the article will we will cover this topic.
1. StringBuilder class in java
2. How to create a string by StringBuilder
3. Some important constructors
4. Important methods of StringBuilder

StringBuilder class in java

The StringBuffer class provides a way to create a string in java. The StringBuffer class exists in java.lang package. Serializable, Comparable, and CharSequence are three interfaces that are implemented by the StringBuffer class.

StringBuffer in java

Like StringBuilder in java, StringBuffer in java uses to create a mutable string. A mutable string can be modified without creating a new object. StringBuffer objects are thread-safe.

How to create a string by StringBuffer

The StringBuffer class provides some constructors that are used to create the object of StringBuffer. Each and every constructor creates an object of StringBuffer that holds the string value. All constructors create a mutable string.

public class StringBufferExample
{
   public static void main(String args[])
   {
       StringBuffer str = new StringBuffer();
       System.out.println("Is it blank string: "+ (str.length() == 0));
      
       str.append("Hello");
       System.out.println("Value after append: "+str);
   }
}

Output: Is it blank string: true
Value after append: Hello

Some important constructors

1. StringBuffer(): This constructor creates an empty string with an initial capacity of 16.
2. StringBuffer(String str): This constructor creates a string buffer object with some specified value.
3. StringBuffer(int capacity): This constructor creates an empty buffer with a specified capacity.

1. StringBuffer()

This constructor creates an empty string buffer. This constructor doesn’t have any parameters. Its initial capacity is 16 which is provided by JVM at the time of object creation of StringBuffer.

StringBuffer name =  new StringBuffer();
class ExampleOfStringBuffer
{
  public static void main(String args[])
  {
    // creating a blank string
    StringBuffer name = new StringBuffer(); 
    // If name is blank its length is equals to 0
    System.out.println("Is name is blank = "+ (name.length() == 0)); 
    // Display the capacity of name
    System.out.println(name.capacity()); 
  }
}

Output: Is name is blank = true
16

Memory representation:

                               
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

StringBuffer(String str)

This constructor creates a string buffer with the specified string. This constructor takes one parameter of string type. Its initial capacity is 16 which is provided by JVM at the time of object creation of StringBuffer.

StringBuffer name =  new StringBuffer(specifiedString);
class ExampleOfStringBuffer
{  
	public static void main(String args[])
	{  
		// creating a StringBuffer with specified string
		StringBuffer name = new StringBuffer("Ravi"); 
		System.out.println("Name of Student = "+ name); 
		System.out.println(name.capacity()); // Display the capacity of name
	}
}

Output: Name of Student = Ravi
20

Memory representation:

3. StringBuffer(int capacity)

This constructor creates a blank string buffer with a specified capacity. This constructor takes one parameter of integer type. If you want to specify the capacity of the string Buffer you should use this constructor.

StringBuffer name =  new StringBuffer(int capacity);
class ExampleOfStringBuffer
{
  public static void main(String args[])
  {
    // creating a StringBuffer with specified capacity 
    StringBuffer name = new StringBuffer(10); 
    name.append("Ravi"); // Appedning string in string buffer
    System.out.println("Name Of Student = "+ name);
    System.out.println(name.capacity()); // Display the capacity of name
  }
}

Output: Is name is Student = Ravi
10

Memory representation:

R a v i              
0 1 2 3 4 5 6 7 8 9 10

Important methods of StringBuilder

1. append() method: This method is used to append the given text in a string.

class ExampleOfStringBuffer
{  
	public static void main(String args[])
	{  
                // creating a StringBuffer with specified string
                StringBuffer name = new StringBuffer("Ravi"); 
		name.append("kant"); // Appending string in string buffer
		System.out.println("Name of Student = "+ name); 		
	}
}  

Output: Name of Student = Ravikant

2. insert() method: This method is used to insert the given text in the string at a given position. StringBuffer class has various forms of this method we will discuss it later.

class ExampleOfStringBuffer
{  
	public static void main(String args[])
	{  
		// creating a StringBuffer with specified string
                StringBuffer name = new StringBuffer("Ravi"); 
                // inserting string in string buffer
		name.insert(4, "kant"); 
		System.out.println("Name of Student = "+ name);		
	}
}  

Output: Name of Student = Ravikant

3. replace(startIndex, endIndex, string) method: This method is used to replace the string by given text. The replace() replaces the given string from the specified startIndex and endIndex.

class ExampleOfStringBuffer
{  
	public static void main(String args[])
	{  
		// creating a StringBuffer with specified string
		StringBuffer name = new StringBuffer("Ravi kant"); 
		name.replace(5, 7, "OK");
		System.out.println("Name of Student = "+ name);	
        }
}

Output: Name of Student = Ravi OKnt

Difference between String and StringBuffer in java

In Java, String and StringBuffer are both classes use to create a string in java. Both classes have different ways to create a string that we have learned in the String class and StringBuffer class. Now we will see the difference between String and StringBuffer in java.

  String StringBuffer
1.   When we create a String by using of String class, it creates an immutable string. It means we can’t change/modify it. If we modify the string, JVM creates a new object of the string. You can read why string is immutable in java.The StringBuffer class creates an object of mutable string. It means we can change/modify it and JVM doesn’t create a new object of string. You can read the mutable string in java.
2. The String class is slower than StringBuffer. The performance of the String class is slow than StringBuffer. Let’s see the example of performance comparison.It is faster than the String class. The performance is faster than String. Let’s see the example of performance comparison.
3.   String consumes more memory in heap memory because when a user modifies any string it creates a new object of string. That degrades our performance and increases memory.StringBuffer consumes less memory than the string class because when a user modifies any object of StringBuffer it doesn’t create a new object which improves the performance also.
4.  We can compare two strings by use of the equals() method because the string class overrides the equals() method. The equals() method returns a boolean value. StringBuffer class doesn’t override the equals method. If we compare the string we need to convert it into the Object of String class by use of the toString() method. After conversion, we use the equal() method.


5.  
The object of the String class has a fixed length. The length of the string is initialized at the time of string creation. The object of the StringBuffer class is growable. When we modify the string the length of an object automatically grows.
6.   The object of a String can be stored in String constant pool or heap memory. The object of StringBuffer is stored in heap memory.

Difference between String and StringBuilder in java

In Java, String, and StringBuilder class both are classes that are used to create a string in java. Both classes provide different ways to create a string that we have learned in the String class and StringBuilder class. Let’s find all the difference between String and StringBuffer in java.

  String StringBuilder
1.   When we create a string by String class, The JVM creates an immutable string in heap memory. We can’t modify the string in the same string object, if we try to modify it the JVM creates a new object of String and update the string value to a new object. You can read why string is immutable in java.When we create an object of StringBuilder, The JVM creates a mutable string in heap memory. We can modify the string in the same string without creating a new object. You can read the mutable string in java.
2. If we talk about the performance, the performance of the String class is slower than StringBuilder. Let’s see the example of performance comparison.It performs operations quicker as compared to the String class. The performance is faster than String. Let’s see the example of performance comparison.
3.   The object of the String class takes more memory in heap memory because of the immutable string. It creates a new string after each modification in a string object that leads to more consumption of memory.The object of the StringBuilder class takes less memory than the string class because of the mutable string. When we made any changes in the string the JVM doesn’t create a new object.
4.  To make a comparison of two strings we can use the equals() method of the String class. The string class overrides the equals() method. The equals() method returns a boolean value. To make a comparison of two strings of the StringBuilder class we need to convert them into objects of the string class. We can convert them by use of the toString() method. After conversion, we can use the equal() method.


5.  
When we create the object of the String class, the JVM initializes the length of the string. We can’t change the length of the string object after creation. StringBuilder class always creates a growable object because we can modify it after creation. We can reinitialize the same object with the new length of the string.
6.   The object of the String class is always stored in String constant pool or heap memory. The object of StringBuffer is stored in heap memory.

Difference between StringBuilder and StringBuffer

1.  StringBuffer class introduced in Java 1.4 versions. But the StringBuilder class was introduced in 1.5 versions of java.

2. StringBuffer class has a synchronized method but the StringBuilder class doesn’t have synchronized methods.

3. StringBuffer class is thread-safe but the StringBuilder class is not Thread safe.

4. StringBuffer class is slower than the StringBuilder class.

Leave a Comment