Introduction
1. What is String?
String is a final class in Java and not a primitive data type like int, float, etc. It is defined in java.lang package and therefore available by default.2. How to create objects of String?
There are two ways to create String
a. String literals
String str = "abc";
b. Using new operator
String str = new String("abc");
3. Where is String stored in memory?
String literals are stored in the String constant pool. A string is called immutable or constant i.e. once created then it can not be changed. Whenever we create a String using double quotes (String literal), Java looks into the String constant pool if an object with the same value is present, it returns the reference to that object otherwise creates a new String and stores it in String pool.
String created using new operator are stored on Java heap memory. intern() method can be used to store or retrieve an object from String pool.
4. How many objects will be created in the following code?
String str = "abc";
String str1 = "abc";
String str2 = new String ("abc");
Two objects will be created.
An object of str will be created and stored in String pool. Since str is already present in String pool, str1 will be assigned the reference. new operator will create a new String for str2.
5. How to reverse the value of String?
String str = "abc";
StringBuilder builder = new StringBuilder(str);
System.out.println(builder.reverse());
6. What is the difference between StringBuilder and StringBuffer?
Since String is immutable, StringBuilder and StringBuffer classes were introduced to create mutable/modifiable String objects. If you are using a lot of String concatenation in your code, a lot of Java objects will be created and can result in memory issues. StringBuilder and StringBuffer can be used to avoid memory issues.
StringBuffer is threadsafe whereas StringBuilder is not. Thread safety impacts the performance of code therefore StringBuilder is fast as compared to StringBuffer.
Note that since String is immutable, its thread-safe by default.
Objects of StringBuilder and StringBuffer are created using new operator. Both of these classes are final.
7. Like C/C++, is String in Java terminated with NULL?
No, Java Strings are treated as objects and not terminated with NULL character.8. What will be the output of the following code?
String str = "abc";
String str2 = "abc";
System.out.println(str == str2);
True will be print as a single object is stored in String constant pool and both refer to the same object.
9. What will be the output of the following code?
String str = "abc";
String str2 = new String("abc");
System.out.println(str == str2);
False will be print as str is stored in String constant pool and str2 is stored in Heap memory.
10. How can we compare two Strings in Java?
String class implements the Comparable interface by default, therefore, we can compare two Strings for equality with the following two methodsa) compareTo(String)
b) equals(String)
Comments
Post a Comment