What is String ?
- String is non-premitive data type
- String is a sequence of characters (String is array of characters)
char c = {‘c’,’k’,’e’}; //charSequence interface used to represent string
String s = new String(c); - String is a class and it is a final class
public final class String extends Object implements CharSequence,Serializable,Comparable{ } - String s = new String();
This creates a immutable object - String can be created in two ways
String s1 = “abc”;
String s2 = new String(“abc”); - We can create String Object using 3 classes, String, StringBuffer and StringBuilder
- Strings are immutable there by making it thread safe
String Constant Pool (SCP)
- Until Java 1.6 String Constant Pool resided in Method Area, from 1.7 it resides in the heap memory. (Reason: Memory was constant in Method Aread but Heap Size can increase its size)
- Garbage collection never happens in String Constant pool
- When a String is created with the new keyword,
Example: String s1 = new String(“abc”); //2 objects are created- it is stored in Heap Area,
- but if it contains a literal with double quotes like “abc” then an object is also created in String Constant Pool.
- String Constant Pool Object is pointed by an internal reference created by JVM.
- Note: The reason 2nd object is created in the String Constant pool is that it could be used in the future.
- When a String is created as below
Example : String s2 = “xyz”
This string is directly created in String Constant Pool and only 1 object is created - When below operation is performed
String s1 = new String(“abc”); //Line 1
s1=s1.concta(“pqr”); //Line 3
s1.concat(“xyz”); //Line 2
Note : Same concept is applied when + symbol is used instead on concat.- At 1st line “abc” String object is created in SCP and it is also created in Heap and it is pointed by s1 reference.
- At 2nd line “pqr” String object is created in SCP and string “abcpqr” is created in Heap and s1 reference is pointed to “abcpqr” in heap and “abc” object in heap is eligible for garbage collection.
- At 3rd line “xyz” String object is created in SCP and string “abcpqrxyz” is created in Heap but is also eligible for garbage collection since no reference is pointing to the string “abcpqrxyz”
- Run time operations like + or .concat will always create object in heap and string literals like “abc” is compile time and it is stored in SCP
- When below operation is performed
String s1=”abc” //SCP
s1=s1.concat(“xyz”)//Run time operation s1 is Heap and “xyz” in SCP
s1=”pqr”+”uvw”//Compile time operations s1 is in SCP
Reference
Why String Constant Pool ?
- the string constant pool exists mainly to reduce memory usage and improve the re-use of existing instances in memory. When a string object is assigned a different value, the new value will be registered in the string constant pool as a separate instance.
- One way to skip this memory allocation is to use the new keyword while creating a new string object. The ‘new’ keyword forces a new instance to always be created regardless of whether the same value was used previously or not. Using ‘new’ forces the instance to be created in the heap outside the string constant pool which is clear, since caching and re-using of instances isn’t allowed here.
String Immutability
- What is Immutable? Immutable are things that cannot be changed
- Why String is immutable?
- String objects are cached inside the String pool.
- These cached String Objects are shared by multiple String references.
- So if we change the actual value of the String Object, it could change the value of other references that are pointing to that String object.
- Hence we never modify a String Object in String Pool instead we create a new object in String Constant Pool.
- Hence Strings are immutable
String is a final Class
No other class will be able to extend the String class and modify its contents
String intern method
- Intern method is add a String into String Costant pool
- If the String already exist in String Constant pool then that objects reference is returned.
String .equals() method and == operator
- .equals method is used to compare the contents of the string
- == operator is used to compare the reference of the string
String Constructors
String methods
Search in String
- indexOf
- lastIndexOf
- charAt
- contains
- startsWith
- endsWith
- substring (returns String)
- subSequence (returns character array)
- concat
- join
- replace
- replaceFirst
- replaceAll
String Buffer
- StringBuffer create mutable object
- We can use .append() method to add String
- All the methods in StringBuffer are synchronized which causes the threads to execute only 1 thread at a time and there is also a lock involved in it which effects the performance
String Builder
- Introduced in java 1.5
- StringBuilder exactly the same as StringBuffer but the methods are non syncronized
- So the efficiency is more compare to StringBuilder is a concurrent environment
- Same methods of StringBuffer is used in StringBuilder
Difference between String, StringBuffer and StringBuilder
String | StringBuffer | StringBuilder | |
Storage | Heap Area and SCP | Heap Area | Heap Area |
Object | Immutable object | Mutable Object | Mutable Object |
Memory | If we change data a lot more memory is consumed | consumes less memory | consumes less memory |
Thread Safe | not Thread-safe | All methods are synchronized and thus is Thread-safe | Not Synchronized hence not Thread-safe |
Performance | Slow | Fast compared to String | Fast compared to StringBuffer |
Usage | If data is not changing frequently | In a multithreaded environment where data changes frequently | In Thread-safe environment where data changes frequently |
Interview Questions :
- WAP to Reverse a String (chatAt())
- WAP to check palindrome (chatAt())
- WAP to find max and min occurring char in String
- WAP to count the number of words in String
- WAP to print all permutations of a String
- WAP to print the duplicate character from the given String
- WAP to remove the characters from 1st String which are present in 2nd String
- WAP to find non-repetitive characters in string
- WAP to check if strings are anagram of each other
- WAP to split comma separated String in java
Proof String is immutable :
public class ProofStringIsImmutable { public static void main(String[] args) { String s1 = "ABC"; String s2 = s1; System.out.println(s1.hashCode()); s1="XYZ"; System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); } }
How many objects are created while String s = new String(“ABC”); ?
Inside java heap memory there is a string constant pool. When String s = new String("ABC"); Since new is used here the object has to be created in the heapmemory itself but it checkes if the entry of "ABC" exist in the String constant pool as well, and if it does not exist then it will make an entry into the string constant pool. But it will refear to the Object created in the heap only.
String methods :
Reference :