String Class in Java | Why String is Immutable in Java?

In Java, a string is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type string. String class in Java is defined in the java.lang package. Thus, this class available to all the programs automatically. When you create a String Class object, you are creating a string that cannot be changed. Hence, the objects of the String class are immutable.




What is String immutability?

String objects in Java are immutable that means you cannot change the content of a string once they created. Let's understand the concept of string immutability with an example. In this example, we created a string object with the help of a new keyword that contains the string "Java" and in the next statement, we want to concat this string with other string "Tutorial"

But when we concat the string a new object will be created in the existing object, and we can't able to perform any changes. When we concat "Java" with "Tutorial" it will become Java Tutorial. But this new object is not assigning with any reference variable then automatically this object eligible for the garbage collector. That's why we will get only "Java" as an output. See the image given below:

String class in java


class StringExample{
	public static void main(String args[]){
		String str = new String("Java");
	    str.concat("Tutorial");
	    System.out.println(str);
	}
}

Output:
Java 


How to create a string object in Java?

We can create a string object in java by using two ways:
1. By using String literals. 

2. By using the new Keyword. 

1. By using String literals: We can create a string object by using string literals. In String literals, we can create a string by using double-quotes. For example:


String str = "Javastudypoint";
Each time when you create a String by using String literal, the JVM first checks whether the object is present in the string pool or not. If it is already present then the same reference is returned otherwise a new object will be created in the string pool and then return the reference. 

2. By using the new keyword: When we create a String using the new keyword, the JVM creates a new String object in heap memory and the String literal "Javastudypoint" will be placed inside the String pool and the variable str will refer to the String object in heap.


String str = new String("Javastudypoint");



Advantage of String Constant Pool:

The biggest advantage of String constant pool is the same object can be reused multiple times instead of creating new objects. Therefore memory will be saved and performance will be improved.



Disadvantage of String Constant Pool:

As we know, because of the string constant pool one object can be reused by multiple references. If one reference any person can try to change then all the remaining references can be affected this is the biggest disadvantage of String Constant Pool.



Why String class objects are immutable?

The meaning of the immutable string is once we create a string its value cannot be changed. The String is immutable in nature because it uses the concept of String literals. Let's take an example to understand this:
                             String str1 = "Java";
                             String str2 = "Java";
In this example, the two reference variables refer to the same object. if one reference variable changes the value of the object(suppose "java" to "python"), It will affect to all the reference variable. That's why the String object is immutable in nature.



Java String class constructors:

The String class in java supports several constructors. The most commonly used constructors are given below:

1. String(): Initializes a newly created String object so that it represents an empty character sequence. For example:

 String str = new String(); 

2. String(char chars[]): This constructor can be used to create a string initialized by an array of characters. For example.

char chars[] = {'a', 'b', 'c'};
String str = new String(chars);  //abc


3. String(char chars[], int startIndex, int numChars): This constructor can be used to specify a subrange of a character array as an initializer. Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use. For example.

char chars[] = {'a', 'b', 'c', 'd', 'e', 'f'};
String str = new String(chars, 2, 3);  //cde.

4. String(String strObj): We can use this constructor to construct a String object that contains the same character sequence as another string object. Here, stringObj is a string object. For example.

char ch[] = {'J', 'a', 'v', 'a'};
String str1 = new String(ch);  //Java.
String str2 = new String(str1); //Java.

5. String(byte[] b ): This constructor is used to create a new string object by decoding the byte array. These byte values are converted into corresponding characters. For example.

byte[] b = {97, 98, 99, 100);
String str = new String(b);
System.out.println(str); //abcd

6. String(StringBuffer buffer): This constructor is used to create a new string that contains the sequence of characters currently contained in the StringBuffer argument. For example.

StringBuffer buffer = new StringBuffer("Javastudypoint");
String str = new String(buffer); // Javastudypoint

7. String(StringBuilder builder): This constructor is used to create a new string that contains the sequence of characters currently contained in the StringBuilder argument. For example.

StringBuilder builder = new StringBuilder("Javastudypoint");
String str = new String(builder); // Javastudypoint



String class Methods in Java

The String Class in Java provides many methods. The most commonly used methods are given below. We can discuss each method in detail in our next tutorials. Here, we can only introduce these methods. 

1. char charAt(int index): This method is used to return the char value at the specified index. If the specified index is not there then you will get StringIndexOutOfBoundExceptions: string index out of range.

2. String concat(String str): This method is used to concatenates the specified string to the end of this string.

3. boolean equals(Object obj): This method is used for content comparison. It is the overriding method of the object class. The equals() method by default check content including case also i.e. The comparison is case sensitive. If the comparison is case insensitive then this method returns false.

4. boolean equalsIgnoreCase(String str): This method is used to perform the comparison that ignores the case differences. When it compares two strings, it considered A-Z to the same as a-z.

5. boolean isEmpty(): This method is used to check whether the string is empty or not. If the string is empty, it returns true else it returns false.

6. int length(): This method is used to returns the number of characters in the string. Remember that the length variable is used for array and the length() method is used for String. If you can use the length variable to find the length of the string then the compiler will get a compile-time error.

7. String replace(char oldChar, char newChar): This method is used to replacing all the occurrences of the oldChar in this string with newChar. 

8. String substring(int startIndex): This method returns the string from the beginning index to the end of the string. Here, startIndex specifies the index at which the substring will begin.

9. String substring(int startIndex, int endString): This method returns String from the beginning index, up to, but not including, the ending index.

10. int indexOf(int ch):
This method returns the index of the first occurrence of the specified character. If the specified character is not present there then it returns -1. 

11. int lastIndexOf(int ch): This method returns the index of the last occurrence of the specified character.

12. int indexOf(int ch, int fromIndex): This method returns the index of the first occurrence of the specified character, starting the search from the specified index.

13. int lastIndexOf(int ch, int fromIndex): This method returns the index of the last occurrence of the specified character, starting the search from the backward specified index. 

14. int indexOf(String str): This method returns the index of the first occurrence of the specified substring. 

15. int lastIndexOf(String str): This method returns the index of the last occurrence of the specified substring. 

16. int indexOf(String str, int fromIndex): This method returns the index of the first occurrence of the specified substring, starting the search from the specified index.

17. int lastIndexOf(String str, int fromIndex): This method returns the index of the last occurrence of the specified substring, starting the search from the backward specified index. 

18. String toLowerCase(): This method converts all the characters in a string from uppercase to the lowercase.

19. String toUpperCase(): This method converts all the characters in a string from lowercase to the uppercase.

20. String trim(): This method returns the copy of the string by removing whitespaces at both ends. It doesn't remove the whitespaces in the middle.

21. char[] toCharArray(): This method is used to convert a string into a char array.

22. int compareTo(String str): This method is used to compare the two strings lexicographically. It returns a positive number, negative number or 0.
String Class in Java | Why String is Immutable in Java? String Class in Java | Why String is Immutable in Java? Reviewed by Prashant Srivastava on January 03, 2020 Rating: 5

No comments:

Powered by Blogger.