- String is a final in java.lang package and not a keyword.
- 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
1. Is String immutable in java?
Yes, String class is immutable in java. Immutable means once the object is created, its value can not be changed.
2. How many objects are created using new keyword?
String str = new String("JavaHungry");
Two objects are created by the above statement. One object in the heap memory and one object in the String constant pool.
3. How to convert String to char Array?
You can convert String to char Array using toCharArray() method.
4. Are String thread-safe in java?
As we know String objects are immutable. It means they are thread-safe also.
5. Which class is final among String,StringBuilder and StringBuffer?
String class is the only class which is final.
6. Is String primitive type or object (derived) type in java?
String is object(derived) type in java.
7. Can we use String in switch statement?
Yes, you can use String in switch statement in java 7. Prior to java 7 , you had to use if-else statements to achieve the task.
8. What is the difference between StringBuilder and StringBuffer in java?
Below are the main differences between StringBuilder and StringBuffer in java.
1. StringBuilder is not thread-safe. StringBuffer is thread-safe.
2. StringBuilder is not synchronized and StringBuffer is synchronized.
3. StringBuilder is faster while StringBuffer is slower as it is thread-safe.
9. What is the difference between below statements ?
String str = new String("abc");
String str = "abc";
In the first statement, String str = new String("abc");
JVM will create one object in the heap memory. Another object in the String constant pool, if the object is not present. Otherwise,if present in the String constant pool ,it will return the reference to it.
In the second statement, String str = "abc";
JVM checks for the string "abc" in the String constant pool. If the string is not present in the constant pool then it will create a new String object and stores it in pool.
If the string "abc" is found in string constant pool , then it simply creates a reference to it but does not create a new object.