Top 35 Java String Interview Questions with Answers

The  String class and concept is a very important class in Java. There is not a single Java program out there which is not using String objects and that's why it's very important from the interview point of view as well. In this article, I am going to share 35 String-based questions from different Java interviews. It includes questions on java.lang.String class as well as a string as data structure like. some coding questions something like I have shared in my earlier article about 75 Coding questions to Crack any Programming Job interviews

You can use this list to refresh your knowledge about String in Java as well as to prepare for your next Java interview. If you have any good String questions which are not on this list, feel free to drop a note and I'll include in this list.

35 Java String Concept Interview Questions and Answers

1)  Why is String final in Java? (answer)
There are a couple of reasons for this e.g. String pool, Caching, Performance but Security is probably the most important reason. Given String is used in sensitive places like specifying the host and port details, locking it for modification prevents from may Security related risks. It's one of the popular Java interview questions so you better read more about it in a given answer.

2)  How does the substring method work in Java? (answer)
This return a substring of specified range from the original String on which it is called. It returns a new String object because String is immutable and can't be changed, but, prior to Java 7 it also holds the reference of the original array which can prevent it from Garbage collected and cause a memory leak, which is not ratified.  See The Complete Java Masterclass learn more about how Garbage collection works in Java.

Top 35 String Concepts Interview Questions with Answers in Java

3)  What is the String pool in Java? What is the difference in String pool between Java 6 and 7? (answer)
It's a pool of cached String objects for minimizing the number of String instances and improving performance by sharing the same instance with multiple clients and reducing garbage collection. Prior to Java 7, the Sring pool was located on meta-space where class metadata was stored but from JDK 7 onwards it's moved into heap space.

4)  What is the difference between "ABC".equals(str) and str?equals("ABC"), where str is a String object? (answer)
Though both look similar and return the same result if str is equal to "ABC" but the real difference comes when given String is null i.e. str = null. In that case, the first code snippet will return false, while the second code snippet will throw NullPointerException.

This is one of the tricky Java questions and if a candidate can answer this then he has good knowledge of Java fundamentals.

 It's also one of the several weird tricks to avoid NullPointerException which I have mentioned in my earlier post about how to avoid NPE in Java.

5)  Difference between str1 == str2 and str1.equals(str2)? (answer)
The key difference is that the first one is using == operator which does reference-based comparison while the second one is using equals() method which does a content-based comparison. Since String class overrides equals() to perform character-based comparison  The first will return true only if both str1 and str2 point to the same object but the second one will return true if str1 and str2 have the same content even if they are a different object. If you are interested, you can read more about == vs equals in my post difference between equals and == in Java.

6)  When you execute String str = new String("abcd")? how many String objects are created? (answer)
This is another tricky Java interview question as many Java developers will answer just one but that's not true. There are two String objects are created here, the first String object is created by String literal "abcd" and the second one is created by new String().  If you are not sure about how

7)  What does the intern() method of String class do? (answer)
The intern() method of String class put the String on which it has called into String pool like str.intern() will put the String str into the pool. Once the String is the pool it can be reused and improve performance. See Java Fundamentals: The Java Language to learn more about the String pool in Java.

Top 35 Java String Interview Questions with Answers

8)  How do you split comma separated String in Java? (answer)
You can use either the StringTokenizer or the split() method of java.lang.String class to split a comma-separated String. The split() method is better because it also expects a regular expression and returns an array of String which you can use or pass to a function. See the answer link for a sample Java program to split String in Java.

9)  The difference between String and StringBuffer in Java? (answer)
The key difference between String and StringBuffer is that String is Immutable while StringBuffer is mutable, which means you can change the content of a StringBuffer without creating separate String objects. If you are creating string programmatically, consider using StringBuffer for better performance as it put less pressure on Garbage Collector by reducing the number of temporary objects.

10) The difference between StringBuffer and StringBuilder in Java? (answer)
Now, this is interesting because both StringBuffer and StringBuilder represents mutable String. This is also asked a follow-up question of the previous question.

Anyway, the real difference is that methods of StringBuffer like append() are synchronized, hence slow, while those of StringBuilder is not synchronized, hence fast.

Otherwise, StringBuilder is just a copy of StringBuffer and you can see that in the Javadoc of the StringBuilder class as well. See The Complete Java Masterclass to learn more about the StringBuilder class in Java.

difference between StringBuffer and StringBuilder in Java?

11) Write a program to reverse a String in Java without using StringBuffer? (answer)

12) Write a program to replace a character from a given one in Java? (answer)

13) Java program to count the occurrence of a character in String? (answer)

14) Why char array is better than String for storing sensitive information? (answer)

15) How to check if a String contains only numeric digit? (answer)

16) Write a program to check if a String is a palindrome in Java? (answer)

17) How to format String in Java? (answer)
You can use the format() method of java.lang.String class to format a given String in Java. If you just want to print the formatted String, you can also use the System.out.printf() method, which prints the formatted string to console.

18) How to convert Enum to String in Java? (answer)
Similar to any Java object, you can also use the toString() method to convert an Enum to String in Java. The Enum class provides a toString() method which can be overridden by your Enum implementations.

19) How to convert String to Date in Java? (answer)
Prior to Java 8, you can use DateFormat or SimpleDateFormat class to convert a String to Date In Java or vice-versa. From Java 8 onwards, when you use the new Date and Time API, you can also use the DateTimeFormatter class to convert String to LocalDate, LocalTime, or LocalDateTime class in Java.

20) Is String thread-safe in Java? Why? (answer)
Yes, String is a thread-safe because it's Immutable. All Immutable objects are thread-safe because once they are created, they can't be modified, hence no issue with respect to multiple threads accessing them.

21) Can we use String as the HashMap key in Java? (answer)
Yes, we can use String as a key in HashMap because it implements equals() and hashcode() method which is required for an object to be used as a key in HashMap. If you want to learn more about HashMap, you can further see this list of free Java courses to learn more.

Can we use String as HashMap key in Java?

22) How to check if a String is empty in Java? (answer)
There are many ways to check if a String is empty in Java e.g. you can check its length. If the length of String is zero then it's empty. Otherwise, you can also use the isEmpty() method which returns true if String is empty. Though, you need to be careful with requirements e.g. a String may contain whitespace which will look empty but length will not be zero. So it depends upon your requirements.

23) How to convert String to int in Java? (answer)
There are many ways to convert the String to the int primitive in Java but the best way is by using Integer.parseInt() method. This method parses the given string and returns a primitive int value. If you need a wrapper class Integer object, you can use Integer.valueOf() method. Although it internally uses the parseInt() method it caches frequently used Integer values e.g. -128 to 127, which can reduce temporary objects.

24) How does String concatenation using + operator work in Java? (answer)
The + operator can be used to concatenate two String in Java. This is the only operator that is overloaded i.e. it can be used two add numbers as well as to concatenate String. Internally, the concatenation is done by using StringBuffer or StringBuilder append() method, depending upon which version of Java you are using.

25) Can we use String in switch case in Java? (answer)
Yes, after the JDK 7 release, you can use the String in the switch case in Java. Earlier it wasn't possible but now it's possible.

26) What is the String enum pattern in Java? (answer)

27) Write a Java program to print all permutations of a String? (answer)

28) What is the difference between String in C and Java? (answer)
Even though both C and Java String is backed by character array, C String is a NULL-terminated character array while Java String is an object. This means you can call methods on Java String e.g. length, toUpperCase, toLowerCase, substring, etc.

29) How to convert String to double in Java? (answer)
Similar to Integer.parseInt() method which is used to convert String to double, you can use the Double.parseDouble() method to convert a String to double primitive value. If you want to learn fundamentals like this, I also suggest picking one of the Java Programming courses for beginners from this list.

30) How to convert String to long in Java? (answer)
It's similar to converting String to int or String to double in Java. All you need to do is just use the parseLong() method of the Long class. This method returns a primitive long value. Even though you can use the Long.valueOf() method which can be used to convert String to Long but it returns a Long object, hence you would need to use auto-boxing to convert wrapper object to a primitive value.

31) Difference between format() and printf() method in Java? (answer)
Even though both methods can be used to format String and they have the same rules the key difference is that format() method returns a formatted String while printf() method print formatted String to console. So, if you need a formatted String, use format method and if you want to print, then use the printf() method.

32) How do you append leading zero to a numeric String? (answer)
You can use the format() method of String to append leading zeros to a numeric String in Java. See the link for an example.

33) How to remove white space from String in Java? (answer)
You can use the trim() method to remove white space from String in Java. It's similar to SQL Servers LTRIM() and RTRIM() methods.

34) How to check if two Strings are Anagram in Java? (solution)
There are multiple ways to solve this problem. One way is to sort both the string and then compare it. This way all characters will come into the same place and if Strings are anagram then they will be equal to each other.

35) What is the character encoding? What is the difference between UTF-8 and UTF-16?(answer)
Character encoding is the algorithm which is to represent a character using bytes. The UTF-8 character encoding uses 1 byte or 8 bits to represent a character of UTF-16 uses 2 bytes or 16-bits to represent a character. They come into picture when you convert raw bytes to character or String in Java.

That's all about Top 35 Java String Interview Questions. These questions are not only good for preparing Java job interviews but also it expands your knowledge about String in Java, one of the key classes. Even after programming in Java for more than 10 years, I still discover things about core classes, which I should have known earlier. Truly, there is so much to learn in Java.

Further Learning
The Complete Java Masterclass
Java Fundamentals: The Java Language
Data Structures and Algorithms: Deep Dive Using Java
The Core Java SE 9 for the Impatient
The String API Documentation (Java SE 10)
Java Interview Guide: 200+ Interview Questions and Answers

Thanks for reading this article so far. If you like these Java String Interview Questions then please share with your friends and colleagues. If you have any doubt or feedback, then please drop a note. 

1 comment: