Java Strings...
Published: 2022-07-27 11:37:11

## Java String
In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example:

```
char[] ch={'A','B','C','D','E','F','G','H','I','J'};  
String s=new String(ch);  
Is same as
String s="ABCDEFGHIJ"; 

```
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo()

**CharSequence Interface**

The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by using these three classes.

The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created String objects are immutable. Immutable simply means unmodifiable or unchangeable.. For mutable strings, you can use StringBuffer and StringBuilder classes.

Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.

**There are two ways to create String object:**
**1.	By string literal**
**2.	By new keyword**

1.	When string literal is used to create a string object first it checks whether this string already exists in String Pool. String Pool is a set of string constants that sits in the heap area. If the string already exists in this String Pool then a reference is returned else a new string object is created in this pool and the reference of this newly created object is returned.

2.	When a new keyword is used to create a string object it always creates an object in the heap area and a reference of this object is returned. While creating a string object in the heap area it checks if this string object is present in String Pool or not. If the string object is not present in String Pool then it creates a new object in String Pool as well. But the newly created string variable will always point to the string object in the heap and not in the String Pool.

```
String Pool Example
public class Main {
	
	    public static void main(String[] args) {
	
	        String name1 = "Tom";
	        String name2 = "Tom";//name1.intern();
	
	        String name3 = new String("Bob");
	        String name4 = "Bob";
	
	        System.out.println(name1 == name2);
	        System.out.println(name3 == name4);
	
	    }
	}

```
**output :
true
false**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1z01dzq9xnh0ud1al7pm.png)
**StringBuilder :**

•	StringBuilder represents a mutable sequence of characters.
•	The instance of this class does not guarantee Synchronization and hence should not be used in multi-threaded environments.
•	Wherever possible we should always try to use StringBuilder instead of StringBuffer as StringBuilder is faster than StringBuffer under most implementations.

Below are the StringBuilder class’s methods and descriptions. They can be used as an individual method or in combination.

1.	append(): Appends the string representation of the specified argument to the specified StringBuilder instance sequence.
2.	insert(): Inserts the string representation of the specified argument to the specified StringBuilder instance sequence.

```
String builder example
public class Main {
	
	    public static void main(String[] args) {
	
	        StringBuilder stringBuilder = new StringBuilder("Abhiram");
	        System.out.println(stringBuilder);
	        stringBuilder.append(" Karnam");
	        System.out.println(stringBuilder);
	        stringBuilder.insert(8," Rama");
	        System.out.println(stringBuilder);
}}
output:
Abhiram
Abhiram Karnam
Abhiram Rama Karnam

```
```
Note: insert method can be used for appending the string at the end of the specified string using the length() function.
stringBuilder.insert("Abhiram".length()," Karnam");
//this results "Abhiram Karnam"
```
**StringBuffer :**

•	StringBuffer class represents a thread-safe, mutable sequence of characters.

•	A string buffer is like a String but it can be modified. At any point in time, it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

•	The methods of StringBuffer class are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

•	The principal operations on a StringBuffer instance are the append and insert methods, which are overloaded so as to accept data of any type. Each converts a given data to a string and then appends or inserts the characters of that string to the string buffer.

•	The append method always adds these characters at the end of the buffer and the insert method adds the characters at a specified point.

Below are StringBuffer class methods and descriptions. They can be used as an individual method or in combination. These methods are synchronized and can be used for a multi-threaded environment.

1.	append(): Appends the string representation of the specified argument to the specified StringBuffer instance sequence.

2.	insert(): Inserts the string representation of the specified argument to the specified StringBuffer instance sequence.

```
String buffer example
public class Main {
	
	    public static void main(String[] args) {
	
	        StringBuffer stringBuffer = new StringBuffer("Abhiram");
	        System.out.println(stringBuffer);
	        stringBuffer.append(" Karnam");
	        System.out.println(stringBuffer);
	        stringBuffer.insert(8, "Rama ");
	        System.out.println(stringBuffer);
	    }
	}

output:
Abhiram
Abhiram Karnam
Abhiram Rama Karnam

```

```
Java String Example
public class StringExample{    
public static void main(String args[]){    
String s1="java";//creating string by Java string literal    
char ch[]={'s','t','r','i','n','g','s'};    
String s2=new String(ch);//converting char array to string    
String s3=new String("example");//creating Java string by new keyword    
System.out.println(s1);    
System.out.println(s2);    
System.out.println(s3);    
}}    

 ```
The above code, converts a char array into a String object. And displays the String objects s1, s2, and s3 on console using println() method.

_Following are some features of String which makes String objects immutable._

**1. ClassLoader:**

A ClassLoader in Java uses a String object as an argument. Consider, if the String object is modifiable, the value might be changed and the class that is supposed to be loaded might be different.To avoid this kind of misinterpretation, String is immutable.

**2. Thread Safe:**

As the String object is immutable we don't have to take care of the synchronization that is required while sharing an object across multiple threads.

**3. Security:**

As we have seen in class loading, immutable String objects avoid further errors by loading the correct class. This leads to making the application program more secure. Consider an example of banking software. The username and password cannot be modified by any intruder because String objects are immutable. This can make the application program more secure.

**4. Heap Space:**

The immutability of String helps to minimize the usage in the heap memory. When we try to declare a new String object, the JVM checks whether the value already exists in the String pool or not. If it exists, the same value is assigned to the new object. This feature allows Java to use the heap space efficiently.

**Why String class is Final in Java?**

The reason behind the String class being final is because no one can override the methods of the String class. So that it can provide the same features to the new String objects as well as to the old ones.

```
**Happy reading friends....**
```