02: ♥♦ 10 Java String class interview questions & answers

Q1. What will be the output of the following code snippet?

A1. The output will be

with the leading and trailing spaces. Some would expect a trimmed “Hello World”. So, what concepts does this question try to test?

  1. String objects are immutable and there is a trick in s.trim( ) line.
  2. Concept of object references and unreachable objects that are eligible for garbage collection. 3 String objects are created, and 2 of them become unreachable as there are no references to them, and gets garbage collected.
What follow on questions can you expect?
  1. You might get a follow on question on how many string objects are created in the above example and when will it become an unreachable object to be garbage collected.
  2. You might also be asked a follow on question as to if the above code snippet is efficient.
The best way to explain this is via a self-explanatory diagram as shown below. Click on it to enlarge.
No of String objects created

No of String objects created

If you want the above code to output “Hello World” with leading and trailing spaces trimmed then assign the s.trim( ) to the variable “s”. This will make the reference “s” to now point to the newly created trimmed String object.

The above code can be rewritten as shown below

Q2. What is the main difference between String, StringBuffer, and StringBuilder?

  • String is immutable in Java, and this immutability gives the benefits like security and performance discussed above.
  • StringBuffer is mutable, hence you can add strings to it, and when required, convert to an immutable String with the toString( ) method.
  • StringBuilder is very similar to a StringBuffer, but StringBuffer has one disadvantage in terms of performance as all of its public methods are synchronized for thread-safety. StringBuilder in Java is a copy of StringBuffer but without synchronization to be used in local variables which are inherently thread-safe. So, if thread-safety is required, use StringBuffer, otherwise use StringBuilder.

Q3. Can you write a method that reverses a given String? 
A3. A popular Java interview coding question.

Example 1: It is always a best practice to reuse the API methods as shown below with the StringBuilder(input).reverse( ) method as it is fast, efficient (uses bit wise operations) and knows how to handle Unicode surrogate pairs, which most other solutions ignore. The  code shown below handles null and empty strings, and a StringBuilder is used as opposed to a thread-safe StringBuffer, as the StringBuilder is locally defined, and local variables are implicitly thread-safe.

Example 2: Some interviewers might probe you to write other lesser elegant code using either recursion or iterative swapping. Some developers find it very difficult to handle recursion, especially to work out the termination condition. All recursive methods need to have a condition to terminate the recursion. Recursive solution.

Java Recursion - String example

Java Recursion – String example

Step 1: reverse(“RAW”)

Step 2: reverse(AW) + “R”      [Note: charAt[0] = “R”, and str.substring(1) = “AW” ]

Step 3: reverse(W) + “A” + “R”      [Note: charAt[0] = “A”, and str.substring(1) = “W” ]

Step 4: return “W” + “A” + “R”      [Exit condition is reached when “str.length( ) <=1” ]

outputs: “WAR”

Example 3: Iterative solution.

Q4. Can you remember a design pattern discussed in this post?
A4. Flyweight design pattern. The flyweight design pattern is a structural pattern used to improve memory usage (i.e. due to fewer objects and object reuse) and performance (i.e. due to shorter and less frequent garbage collections).

Q5. Can you give some examples of the usage of the flyweight design pattern in Java?

Example 1: As discussed above, String objects are managed as flyweight. Java puts all fixed String literals into a literal pool. For redundant literals, Java keeps only one copy in the pool.

Example 2: The Wrapper classes like Integer, Float, Decimal, Boolean, and many other classes like BigDecimal having the valueOf static factory method to apply the flyweight design pattern to conserve memory by reusing the objects.

If you use new Integer(5), a new object will be created every time.

Both the above examples will print “referencing the same object“.

Q6. What is a static factory method, and when will you use it?
A6. The factory method pattern is a way to encapsulate object creation. It has the benefits like

1. Factory can choose what to return from many subclasses or implementations of an interface. This allows the caller to specify the behavior desired via parameters, without having to know or understand a potentially complex class hierarchy. The lesser a caller knows about a callee’s internal details, the more loosely coupled a callee is from the caller.

2. The factory can apply the fly weight design pattern to cache objects and return cached objects instead of creating a new object every time. In other words, objects can be pooled and reused. This is the reason why you should favor using Integer.valuOf(6) as opposed to new Integer(6).

3. The factory methods have more meaningful names than the constructors. For example, getInstance( ), valueOf( ), getConnection( ), deepCopy( ), etc.

Q7. How will you split the following string of text into individual vehicle types?

“Car,Jeep, Wagon Scooter Truck, Van”

A7. Regular expressions to the rescue.

Q8. What are the different ways to concatenate strings? and which approach is most efficient?

Plus (“+”) operator:

Using a StringBuilder or StringBuffer class.

Using the concat(…) method.

The efficiency depends on what you are concatenating and how you are concatenating it.

Concatenating constants: Plus operator is more efficient than the other two as the JVM optimizes constants.

Concatenating String variables: Any one of the three methods should do the job.

Concatenating in a for/while loop: StringBuilder or StringBuffer is the most efficient. Avoid using plus operator as it is the worst offender.

Prefer StringBuilder to StringBuffer unless multiple threads can have access to it.

Q9. Java being a stack based language, allows you to make recursive method calls. Can you write a recursion based solution to count the number of A’s in string “AAA rating”?
A9. A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iterations from many sorts of algorithms.

Recursion in stack based language like Java

Recursion in stack based language like Java

Recursion might not be the efficient way to code, but recursive functions are shorter, simpler, and easier to read and understand. Recursive functions are very handy in working with tree structures and avoiding unsightly nested for loops.

Bonus Java String Q&A

Q10. How do you stream a string class in Java 8? ★ ♟
A10. chars() method.

Q. Does parallel processing as shown below preserve the order?

A. No.

You may also like

17 Java overview interview Q&A | Web Services interview Q&A | Java EE Overview interview Q&A | Multithreading scenarios in Java applications interview Q&A

Print Friendly
The following two tabs change content below.
Arulkumaran Kumaraswamipillai
Mechanical Engineering to Java freelancer since 2003. Published Java/JEE books via Amazon.com in 2005, and sold 35K+ copies. Books are outdated and replaced with this online Java training.
Arulkumaran Kumaraswamipillai

Mechanical Engineering to Java freelancer since 2003. Published Java/JEE books via Amazon.com in 2005, and sold 35K+ copies. Books are outdated and replaced with this online Java training.

Posted in Data types
Tags: , , , ,
4 comments on “02: ♥♦ 10 Java String class interview questions & answers
  1. markad krushna says:

    it will be helpfull quitions for a stundent like mi……..thanks

  2. Hi Arul,

    A nice post. I have a few suggestions.

    Q6.3 Iterative solution uses a char variable created everytime inside a for loop. Though it is not a big overhead, it can still be avoided if it was declared outside the loop. After all, we are talking about memory consumption and hence it would be appropriate.

    Q12. Recursion can be used with indexOf() with an exit condition instead of going over every character, which may be a bit more efficient in this situation.

    Raghavan alias Saravanan Muthu

  3. satish says:

    excellent explanation.for more interview questions on String refer this link http://techno-terminal.blogspot.in/2015/09/important-string-interview-questions.html

Leave a Reply

Your email address will not be published. Required fields are marked *


1100+ paid subscribers. Reviews | Free Contents. Monthly 260K+ views & 40k+ visitors. 9 tips to earn more.

Java Developer Training – 800+ Q&As ♥Free|♦FAQ (Mouse Hover for Tooltip)

open all | close all

200+ Java Developer Job Interview FAQs

open all | close all

16 Java Programmer Key Areas to be a top-notch

open all | close all

80+ Java Tutorials – Step by step

open all | close all

100+ Java Developer Coding Exercises

open all | close all

How good are your …..Java job hunting & career fast-tracking skills?

open all | close all