02: 10 Java String class interview Q&As

Java Collection interview questions and answers and Java String class interview questions and answers are must know for any Java developer as these two APIs are the most frequently used in your Java application code. You can’t write any decent Java application without these 2 APIs.

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.

Learn more at Recursion Vs. Tail Recursion.

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.

300+ Java & Big Data Interview FAQs

16+ Java Key Areas Interview Q&As

800+ Java Interview Q&As

300+ Java & Big Data Tutorials