Top 35 Java String Interview Questions with Answers for 2 to 5 Years Experienced Programmers

Hello Java Programmers, if you are preparing for a Java developer interview and want to refresh your knowledge about  String class in Java then you have come to the right place. In the past, I have shared 130+ Core Java Interview Questions and 21 String Coding Problems for Interviews and in this article, I am going to share 35 Java String Questions for Interviews. The  String class and concept is a very important class in Java. There is not a single Java program out there which is not use 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.

This list of Java String questions 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 them in this list.

35 Java String Concept Interview Questions and Answers

Here is the list of 25 Java Interview questions that are based on concepts about the String class in Java. You can review this question to improve your knowledge about this key Java class a well. 

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 many 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 returns a substring of a 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.  

You can further see the Java Application Performance and Memory Management course on Udemy to learn more about how Garbage collection works in Java.

35 Java String Interview Questions with Answers for 1 to 3 Years Experienced

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 String 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 an 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 the 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 the == operator which does reference-based comparison while the second one is using the 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 different objects. 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 in the pool it can be reused and improve performance. See Java Fundamentals: The Java Language course 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 represent 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 are 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)
This is a common coding problem from Java interviews. You can use recursion or iteration to solve this problem as shown in the example in the answer article. 

12) Write a program to replace a character from a given one in Java? (answer)
This is another coding problem that is based upon String but it doesn't specify whether you can use String API or not. If not then you can use the replace method of String to solve this problem. 

13) Java program to count the occurrence of a character in String? (answer)
This problem requires the use of HashMap for string characters as key and their count as values. Once you know this trick you can easily solve such string coding problems. Just convert String to character array and then loop through the array. For each character store the character as key and value as 1 in HashMap, if the key or character already exists then increase the count by 1. 

14) Why char array is better than a String for storing sensitive information? (answer)
This is one of the trick questions from Java interviews. The reason is that because String is immutable they are cached in memory and there is a good chance that they will remain in memory for a longer duration posing a possible threat, while character array gives you the option to erase data once they are used. This is the primary reason but there are some more subtle reasons which you can find in the detailed answer linked to the question. 

15.How to check if a String contains only numeric digits? (answer)
This is one of the simple problems to solve. You can either use a regular expression to check if a string contains only numbers or you can convert it to a character array and then check the  ASCII value of those characters to see if they are in the range of numbers. You can further see the detailed answer for a clear-cut example. 

16. Write a program to check if a String is a palindrome in Java? (answer)
If you don't know, a string is said to be a palindrome if it's equal to its reverse. In order to check if a given String is palindrome or not, you need to first reverse it and then compare the reversed string with the original string, if they are equal the given String is a palindrome

If you remember, we have seen questions about reversing a string, you can either use that technique to reverse a string or you can use convert the String to StringBuffer and use its reverse() method to reverse the given string. 

17. How to format String in Java? (answer)
You can use the format() method of the 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 the 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 the 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 the 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 works 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)
This is a common pattern to declare String constants inside an enum. For example, days of Week can be declared as Enum so that you can use them as Enum instead of String. 

27) Write a Java program to print all permutations of a String? (answer)
This is one of the most popular string coding problems which can be easily solved using recursion, provided you know the permutations. You can see the answer for a complete code example of how to solve this String coding problem. 

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 the printf() method print formatted String to console. So, if you need a formatted String, use the 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 them. 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 represents 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 the 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 expand 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.

Related Interview Questions from Java67 blog

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

1 comment:

Feel free to comment, ask questions if you have any doubt.