12 Java String class Interview Q&As

Q1. What is the difference between “==” and “equals(…)” in comparing Java String objects?
A1. When you use “==” (i.e. shallow comparison), you are actually comparing the two object references to see if they point to the same object. When you use “equals(…)”, which is a “deep comparison” that compares the actual string values. For example:

The variable s1 refers to the String instance created by “Hello”. The object referred to by s2 is created with s1 as an initializer, thus the contents of the two String objects are identical, but they are 2 distinct objects having 2 distinct references s1 and s2. This means that s1 and s2 do not refer to the same object and are, therefore, not ==, but equals( ) as they have the same value “Hello”. The s1 == s3 is true, as they both point to the same object due to internal caching. The references s1 and s3 are interned and points to the same object in the string pool.

String Pool Caches and you create a String object as a literal without the "new" keyword for caching

Create a String object as a literal without the “new” keyword for caching

In Java 6 — all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool.

In Java 7 – the string pool was relocated to the heap. So, you are not restricted by the limited size.

How about comparing the other objects like Integer, Boolean, and custom objects like “Pet”? Object equals Vs “==“, and pass by reference Vs value.

Q2. Can you explain how Strings are interned in Java?
A2. String class is designed with the Flyweight design pattern in mind. Flyweight is all about re-usability without having to create too many objects in memory.

[ Further Reading: Flyweight pattern and improve memory usage & performance ]

A pool of Strings is maintained by the String class. When the intern( ) method is invoked, equals(..) method is invoked to determine if the String already exist in the pool. If it does then the String from the pool is returned instead of creating a new object. If not already in the string pool, a new String object is added to the pool and a reference to this object is returned. For any two given strings s1 & s2, s1.intern( ) == s2.intern( ) only if s1.equals(s2) is true.

Two String objects are created by the code shown below. Hence s1 == s2 returns false.

s1.intern() == s2.intern() returns true, but you have to remember to make sure that you actually do intern() all of the strings that you’re going to compare. It’s easy to forget to intern() all strings and then you can get confusingly incorrect results. Also, why unnecessarily create more objects?

Instead use string literals as shown below to intern automatically:

s1 and s2 point to the same String object in the pool. Hence s1 == s2 returns true.

Since interning is automatic for String literals String s1 = “A”, the intern( ) method is to be used on Strings constructed with new String(“A”).

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

A3. 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

Q4. 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.

Q5. Can you write a method that reverses a given String?
A5. 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.

Q6. Can you remember a design pattern discussed in this post?
A6. 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).

Q7. 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“.

Q8. What is a static factory method, and when will you use it?
A8. 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.

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

“Car,Jeep, Wagon Scooter Truck, Van”

A9. Regular expressions to the rescue.

Q10. 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.

Q11. 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”?
A11. 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

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

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

A. No.

300+ Core Java Interview Q&As
Module 1 Java Overview+
Unit 1 17 Java Overview Interview Q&As  - Preview
Unit 2 4 Java Compile-time Vs Runtime Interview Q&As  - Preview
Module 2 Java data types-
Unit 1 8 Java data types interview Q&As  - Preview
Unit 2 7 Java primitives & objects memory consumption Q&As  - Preview
Unit 3 4 Java autoboxing & unboxing interview Q&As  - Preview
Unit 4 12 Java String class Interview Q&As  - Preview
Module 3 Java modifiers, annotations, initializers & constructors+
Unit 1 6 Java Modifiers every interviewer seems to like  - Preview
Unit 2 10 Java initializers, constructors, regular methods and static factory methods Q&As
Unit 3 8 Java Annotations interview Q&As
Unit 4 4 Java annotation types & processing interview Q&As
Module 4 Java classes, interfaces & class loaders+
Unit 1 12 Java classes and interfaces interview Q&As
Unit 2 3 Abstract classes Vs interfaces interview Q&As
Unit 3 3 Java class loading interview Q&As to ascertain your depth of Java knowledge
Module 5 Java Objects Interview Q&As+
Unit 1 5 Java Object class methods interview Q&As  - Preview
Unit 2 3 Object wait( ) & notify( ) interview Q&As
Unit 3 7 Object equals Vs == and pass by reference Vs value interview Q&As
Unit 4 10 Java immutable objects interview Q&As
Unit 5 10 Java serialization, cloning, and casting interview Q&As
Module 6 OOP & FP+
Unit 1 10 Java OOP Interview Q&As
Unit 2 5 Inheritance Vs Composition OOP Interview Q&As  - Preview
Unit 3 2 Polymorphism OOP Interview Q&As
Unit 4 8 OOP Design principles interview Q&As
Unit 5 5 OOP Vs FP, FP concepts & where to use FP Q&As  - Preview
Unit 6 19 Java Functional Programming (i.e. FP) interview Q&As
Unit 7 Java FP Lambda expressions by examples
Module 7 Generics & Java Collection Framework(JCF)+
Unit 1 12 Java Generics Interview Q&As  - Preview
Unit 2 5 Java Generics Wildcards Interview Q&As
Unit 3 17 Java Collection Framework (JCF) interview Q&As
Unit 4 9 Java data structures interview Q&As
Unit 5 4 Sorting objects in a Collection interview Q&As
Unit 6 8 Java Map interface & Caching interview Q&As
Unit 7 Lambda expressions to work with Java 8 Collections
Module 8 Java multithreading+
Unit 1 17 Java multi-threading interview Q&As  - Preview
Unit 2 7 Java locks & synchronized keyword interview Q&As
Unit 3 9 blocking, scheduling & daemon threads interview Q&As
Unit 4 7 Java Executor framework Interview Q&As
Unit 5 ExecutorService Vs Fork/Join & Future Vs CompletableFuture Interview Q&As
Unit 6 7 Java ThreadLocal interview Q&As
Unit 7 Java Thread stop, resume, suspend & interrupt interview Q&As
Unit 8 12 Java multi-threading differences between X and Y Q&As
Unit 9 Java multi-threading 15 scenarios interview Q&As
Module 9 What is wrong with this multithread code?+
Unit 1 5 Ways to debug Java thread-safety issues  - Preview
Unit 2 Heap Vs Stack, Thread safety & Synchronization  - Preview
Unit 3 Deep Vs Shallow comparison & multithreading
Unit 4 An excellent written test multithreading question - wait/notify
Unit 5 Multithreading & Locks
Unit 6 Java Collection & ConcurrentModificationException
Unit 7 HashMap & Race condition
Unit 8 ConcurrentHashMap & Atomic operations
Unit 9 JConsole for debugging deadlocks in Java
Unit 10 jvisualvm to debug deadlocks in Java
Module 10 Exceptions Handling+
Unit 1 5 Java exception handling interview Q&As
Module 11 Java I/O & NIO+
Unit 1 15 Java old I/O and NIO (i.e. New I/O) interview Q&As
Unit 2 Java 8 way to reading files
Module 12 JVM+
Unit 1 11 JVM memory model and Atomicity, Visibility, and Ordering interview Q&As
Unit 2 8 Java Garbage Collection interview Q&As to ascertain your depth of Java knowledge
Unit 3 jvisualvm to sample Java heap memory
Unit 4 5 JMX and MBean interview Q&As
Module 13 What is new?+
Unit 1 Java 7 features list
Unit 2 Java 8 features list
Module 14 Java code quality+
Unit 1 How will you go about improving on the following Java code?
Unit 2 How will you go about ensuring code quality in Java apps?
Unit 3 5 Java unit testing interview Q&As
Unit 4 Mocks, stubs, domain, and anemic objects interview Q&As
Unit 5 30+ Java Code Review Checklist Items
Module 15 Debugging Java applications+
Unit 1 7 debugging Java interview questions & answers
Unit 2 Debugging "NoSuchMethodError" in Java
Unit 3 Debugging JAR hell issues in Java
Unit 4 Debugging Java version issues
Unit 5 Remote debugging in Java with Java Debug Wire Protocol (JDWP)
Unit 6 Debugging like a pro with eclipse IDE tutorial for Java developers
Module 16 Performance considerations & memory management+
Unit 1 4 Java application performance considerations interview Q&As
Unit 2 8 Java memory management interview Q&As
Unit 3 jvisualvm to detect memory leak
Module 17 Design Patterns Interview Q&As+
Unit 1 12 Java design patterns interview Q&As
Unit 2 5 Java singleton design pattern interview Q&As
Unit 3 Java Proxy, Decorator, Adapter, Bridge, and Facade design patterns Interview Q&As
Unit 4 3 Flyweight design pattern Interview Q&As to improve memory usage & performance
Learn by categories on the go...
Learn by categories such as FAQs – Core Java, Key Area – Low Latency, Core Java – Java 8, JEE – Microservices, Big Data – NoSQL, Architecture – Distributed, Big Data – Spark, etc. Some posts belong to multiple categories.