String Handling
What is difference between String and StringBuffer
- String is immutable that object created for one string and on concatenating with that string it will not add with that string or it create new object with concatenation and StringBuffer is mutable that it appends with created string
- Strings in Java are Objects that are backed internally by a char array.
- Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created.
Eg:-
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(outputFromString());
System.out.println(outputFromStringBuffer());
}
private static StringBuffer outputFromStringBuffer() {
StringBuffer sb=new StringBuffer("Santosh");
sb.append("Gupta");
return sb; //Output will be SantoshGupta
}
private static String outputFromString() {
String s=new String("Santosh");
s.concat("Gupta");
return s; //Output will be Santosh
}
Memory allotment of String
Whenever a String Object is created, two objects will be created- one in the Heap Area and one in the String constant pool and the String object reference always points to heap area object.
For example:
String str = “Geeks”;
An Example that shows how to declare String
// Java code to illustrate String
import java.io.*;
import java.lang.*;
class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String s = "GeeksforGeeks";
// Prints the String.
System.out.println("String s = " + s);
// Declare String using new operator
String s1 = new String("GeeksforGeeks");
// Prints the String.
System.out.println("String s1 = " + s1);
}
}
Output:
String s = GeeksforGeeks
String s1 = GeeksforGeeks
- In String class equals() method is used for content comparison as it overrides the method from Object class bcz in object class equals() method is used for reference comparison as similar as == operation
In StringBuffer equals used for reference comparison as it does not overrides object equals method
Eg:-
String s1=new String("Santosh");
String s2=new String("Santosh");
System.out.println(s1==s2); //false
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equalsIgnoreCase(s2));
// String Buffer
StringBuffer sb1=new StringBuffer("Gupta");
StringBuffer sb2=new StringBuffer("Gupta");
System.out.println(sb1.equals(sb2)); //false
System.out.println(sb1==sb2); //false
Sting object and String literal
String s1=new String(“Santosh”)
It will create two object one for Heap side and another for SCP(String Constant Pool) side for future purpose
String s2=”Santosh”
It will create only one object if object with same content not available
eg:-
Example2
Example 3:-
6 objects are created 3 in heap area and 3 in scp and 2 objects are eligible for garbage collection as durga and durga software
String Constant Pool(SCP)
In SCP Same object can be used with multiple references
Eg:-
We have 1 crore voter in hyderabad so instead of creating new object for every voter having city hyderabad it will point with same object from SCP
This way performance and memory utilization will increase
Why string is immutable just because of using the same object by multiple references as if one object changed then others objects will be affected. To overcome this immutability arise that if one object change it will create new object in SCP
All Wrapper classes like Integer , Character etc are also immutable
Need of String Buffer
If the constant keeps changing it is not recommended to use String, we use StringBuffer as for every change a new object is going to create.
StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.
StringBuffer may have characters and substrings inserted in the middle or appended to the end
It will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth.
StringBuffer Constructors
StringBuffer( ): It reserves room for 16 characters without reallocation.
StringBuffer s=new StringBuffer();
StringBuffer( int size)It accepts an integer argument that explicitly sets the size of the buffer.
StringBuffer s=new StringBuffer(20);
StringBuffer(String str): It accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.
StringBuffer s=new StringBuffer(“GeeksforGeeks”);
StringBuilder Class
The function of StringBuilder is very much similar to the StringBuffer class, as both of them provide an alternative to String Class by making a mutable sequence of characters. However the StringBuilder class differs from the StringBuffer class on the basis of synchronization.
Interview Questions and Answers
1) Is String a keyword in java?
No. String is not a keyword in java. String is a final class in java.lang package which is used to represent the set of characters in java.
2) Is String a primitive type or derived type?
String is a derived type.
3) In how many ways you can create string objects in java?
There are two ways to create string objects in java. One is using new operator and another one is using string literals. The objects created using new operator are stored in the heap memory and objects created using string literals are stored in string constant pool.
String s1 = new String("abc");//Creating string object using new operator
String s2 = "abc"; //Creating string object using string literal
4) What is string constant pool?
String objects are most used data objects in Java. Hence, java has a special arrangement to store the string objects. String Constant Pool is one such arrangement. String Constant Pool is the memory space in heap memory specially allocated to store the string objects created using string literals. In String Constant Pool, there will be no two string objects having the same content.
Whenever you create a string object using string literal, JVM first checks the content of the object to be created. If there exist an object in the string constant pool with the same content, then it returns the reference of that object. It doesn’t create a new object. If the content is different from the existing objects then only it creates new object.
5) What is special about string objects as compared to objects of other derived types?
One special thing about string objects is that you can create string objects without using new operator i.e using string literals. This is not possible with other derived types (except wrapper classes). One more special thing about strings is that you can concatenate two string objects using ‘+’. This is the relaxation java gives to string objects as they will be used most of the time while coding. And also java provides string constant pool to store the string objects.
6) What do you mean by mutable and immutable objects?
Immutable objects are like constants. You can’t modify them once they are created. They are final in nature. Where as mutable objects are concerned, you can perform modifications to them.
7) Which is the final class in these three classes – String, StringBuffer and StringBuilder?
All three are final. (Interviewer will ask this type of questions to confuse you)
8) What is the difference between String, StringBuffer and StringBuilder?
9) Why StringBuffer and StringBuilder classes are introduced in java when there already exist String class to represent the set of characters?
The objects of String class are immutable in nature. i.e you can’t modify them once they are created. If you try to modify them, a new object will be created with modified content. This may cause memory and performance issues if you are performing lots of string modifications in your code. To overcome these issues, StingBuffer and StringBuilder classes are introduced in java.
10) How many objects will be created in the following code and where they will be stored in the memory?
String s1 = “abc”; String s2 = “abc”; |
Only one object will be created and this object will be stored in the string constant pool.
11) How do you create mutable string objects?
Using StringBuffer and StringBuilder classes. These classes provide mutable string objects.
12) Which one will you prefer among “==” and equals() method to compare two string objects?
I prefer equals() method because it compares two string objects based on their content. That provides more logical comparison of two string objects. If you use “==” operator, it checks only references of two objects are equal or not. It may not be suitable in all situations. So, rather stick to equals() method to compare two string objects. [more]
13) Which class will you recommend among String, StringBuffer and StringBuilder classes if I want mutable and thread safe objects?
StringBuffer
14) How do you convert given string to char array?
Using toCharArray() method.
15) How many objects will be created in the following code and where they will be stored?
String s1 = new String(“abc”); String s2 = “abc”; |
Here, two string objects will be created. Object created using new operator(s1) will be stored in the heap memory. The object created using string literal(s2) is stored in the string constant pool.
16) Where exactly string constant pool is located in the memory?
Inside the heap memory. JVM reserves some part of the heap memory to store string objects created using string literals.
17) I am performing lots of string concatenation and string modification in my code. which class among string, StringBuffer and StringBuilder improves the performance of my code. Remember I also want thread safe code?
StringBuffer class gives better performance in this scenario. As String class is immutable, if you use this class, a new object will be created after every string concatenation or string modification. This will lower the performance of the code. You can use StringBuilder also, but it is not thread safe. So, StringBuffer will be optimal choice here.
18) What is string intern?
String object in the string constant pool is called as String Intern. You can create an exact copy of heap memory string object in string constant pool. This process of creating an exact copy of heap memory string object in the string constant pool is called interning. intern() method is used for interning. [more]
24) What is the similarity and difference between String and StringBuffer class?
The main similarity between String and StringBuffer class is that both are thread safe. The main difference between them is that String objects are immutable where as StringBuffer objects are mutable.
25) What is the similarity and difference between StringBuffer and StringBuilder class?
The main similarity between StringBuffer and StringBuilder class is that both produce mutable string objects. The main difference between them is that StringBuffer class is thread safe whereas StringBuilder class is not thread safe.