Skip to main content

Top 10 mostly asked Java String Interview Questions

Introduction


String is the most widely used class in any language. In this post, we will explore String in Java context. This post will help you to understand the String in-depth and to answer String related questions in a Job interview.

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 methods

a) compareTo(String)
b) equals(String)

Conclusion

I have shortlisted these questions based on my personal experiences of the interview. If you want to add any important String related question or find any error related to these questions, please leave your comments in the comment box.




Comments

Popular posts from this blog

Eclipse - Server Tomcat v8.5 Server at localhost failed to start.

When I try to launch the tomcat from Eclipse, I encountered the following error Server Tomcat v8.5 Server at localhost failed to start. Solution Step 1  Delete the .snap file located at the following location     eclipse workspace Path\ .metadata\.plugins\org.eclipse.core.resources Step 2 Delete the  tmp0  folder from the following path      eclipse workspace Path \.metadata\.plugins\org.eclipse.wst.server.core Step 3  Delete the server from servers list Step 4  Remove already added Tomcat Server      i)  Click on Define a new Server     ii)  Select Server Runtime Environments     iii) Select the Tomcat Server and remove it as follows Remove Selected Server Step 5 Make sure that correct version of Server is configured in Project Properties Step 6 Restart the Eclipse IDE.

hibernate-release-5.4.4.Final - Required Jars

Introduction Hibernate (Object Relational Mapping framework) is an implementation of Java Persistence API (JPA) specification.   Required Jars for Hibernate 5.4.4 Following Jars resided inside the required folder are the mandatory jars required for Hibernate 5.4.4 antlr-2.7.7.jar byte-buddy-1.9.11.jar classmate-1.3.4.jar dom4j-2.1.1.jar FastInfoset-1.2.15.jar hibernate-commons-annotations-5.1.0.Final.jar hibernate-core-5.4.4.Final.jar istack-commons-runtime-3.0.7.jar jandex-2.0.5.Final.jar javassist-3.24.0-GA.jar javax.activation-api-1.2.0.jar javax.persistence-api-2.2.jar jaxb-api-2.3.1.jar jaxb-runtime-2.3.1.jar jboss-logging-3.3.2.Final.jar jboss-transaction-api_1.2_spec-1.1.1.Final.jar stax-ex-1.8.jar txw2-2.3.1.jar Hibernate 5.4.4 release is compatible with  Java 8 or 11  JPA 2.2 References https://hibernate.org/orm/releases/5.4/

Intellij : How to add @author comment to every new class

 Introduction In this tutorial, we will learn how to add @author comments to every new class that we create. We can achieve it using either of the following two solutions Solution 1:  Automatically add @author comments to every new class using Files and Code Templates Open File -> Settings -> Editor -> File and Code Templates -> Includes Click on Includes . Under File Header , enter the following comments text /**  * @author ${USER}  * @Date ${DATE}   */ Intellij - add @author comments Solution 2: Autocompletion of @author Open File  ->  Settings  ->  Editor  -> Live Templates Select Java and then click on + button In Abbreviation, enter @a In template text , enter the following comments           /**             * @author ${USER}             * @Date ${DATE}            */ In option , Expands with select SPACE Intellij - Autocompletion @author You can simply add the @author comments by typing @a and then click SPACE