Java Interview Questions

Previous Java Interview Questions Next

Java Strings - Theory Questions

1. What is String in Java and how is it different from primitive data types?

In Java, String is not a primitive data type but a class from the java.lang package. Unlike primitive types (int, char, boolean, etc.), String is an object that represents a sequence of characters. Strings are immutable in Java, meaning once created, their values cannot be changed. Primitive types store actual values directly, while String objects store references to character sequences in memory.

2. Explain String immutability in Java and its advantages.

String immutability means that once a String object is created, its value cannot be modified. Any operation that appears to modify a String actually creates a new String object. Advantages include: Thread safety (immutable objects can be shared between threads safely), Security (preventing unauthorized modifications), Caching (String pool optimization), and Consistency in hash-based collections since hashcode doesn't change.

3. What is the String Pool in Java?

The String Pool is a special memory area in the Java heap where String literals are stored. When you create a String using literals (e.g., String s = "hello"), Java checks if an identical String exists in the pool. If found, it returns the reference to the existing object; if not, it creates a new String in the pool. This mechanism saves memory and improves performance by reusing common Strings.

4. Difference between String, StringBuilder, and StringBuffer.

String is immutable and thread-safe. StringBuilder is mutable and not thread-safe, but faster for frequent modifications. StringBuffer is mutable and thread-safe (synchronized), making it slower than StringBuilder. Use String for constants, StringBuilder for single-threaded string manipulation, and StringBuffer for multi-threaded environments where thread safety is required.

5. What is the difference between == and .equals() method for String comparison?

The == operator compares object references (memory addresses), checking if two references point to the same object. The .equals() method compares the actual content (character sequence) of the Strings. For example, String s1 = "hello"; String s2 = new String("hello"); s1 == s2 returns false (different objects), while s1.equals(s2) returns true (same content).

6. How does String interning work in Java?

String interning is the process of storing only one copy of each distinct String value in the String Pool. You can explicitly intern a String using the intern() method, which returns a canonical representation of the String object. If the String already exists in the pool, the existing reference is returned; otherwise, the String is added to the pool and its reference is returned. This helps save memory by avoiding duplicate String objects.

7. What are the important methods available in the String class?

Key String methods include: length() - returns string length, charAt(int index) - returns character at specified index, substring(int begin, int end) - extracts substring, equals(Object obj) - compares content, compareTo(String anotherString) - lexicographical comparison, toLowerCase()/toUpperCase() - case conversion, trim() - removes whitespace, split(String regex) - splits string, and replace() - replaces characters.

8. Explain the concept of String literals vs String objects.

When you create a String using double quotes (e.g., String s = "hello"), it's a String literal that goes into the String Pool. When you use the new keyword (e.g., String s = new String("hello")), it creates a String object in the heap memory, outside the String Pool. Literals are pooled and reused, while objects created with 'new' always create new instances, even if identical Strings exist.

9. Why are Strings made immutable in Java?

Strings were made immutable for several key reasons: Security - preventing tampering with sensitive data like network connections, file paths; Thread safety - immutable objects can be safely shared across threads; Caching - enables String pool optimization; Hashcode caching - since Strings are immutable, their hashcode can be cached for better performance in hash-based collections; Class loading - class names are Strings and immutability ensures correct class loading.

10. How does String concatenation work in Java?

String concatenation can be done using the + operator or concat() method. Under the hood, the + operator uses StringBuilder (since Java 5) for multiple concatenations in a single statement. However, in loops, using + creates multiple StringBuilder objects, making it inefficient. For frequent concatenations in loops, it's better to use StringBuilder or StringBuffer explicitly for better performance.

11. What is the difference between String.valueOf() and toString() methods?

String.valueOf() is a static method that converts any object to String representation, handling null values by returning "null". toString() is an instance method that must be called on an object and throws NullPointerException if the object is null. Use String.valueOf() when you need to handle potential null values safely, and toString() when you're sure the object is not null.

12. How does String handling work in memory?

String objects are stored in the heap memory. String literals are stored in the String Pool (a special area in heap). When a String is created using literals, JVM checks the pool first. When created with 'new', it always creates a new object in heap. The intern() method can move a String to the pool. Due to immutability, operations like concatenation create new objects rather than modifying existing ones, which is why StringBuilder is preferred for heavy string manipulation.

13. What are the performance implications of String manipulation?

String manipulation can be expensive due to immutability. Each modification creates new objects, leading to: Memory overhead from temporary objects, Garbage collection pressure, and Reduced performance in loops. For heavy string operations, StringBuilder (single-threaded) or StringBuffer (multi-threaded) should be used as they modify the same object without creating new instances for each operation.

14. How do you check if a String is empty or null?

You can check using: str == null for null check, str.isEmpty() for empty string (Java 6+), or str.length() == 0. For comprehensive check including null: str == null || str.isEmpty(). Since Java 7, you can also use Objects.requireNonNull() for explicit null checking. Always check for null before calling methods on Strings to avoid NullPointerException.

15. What are the best practices for using Strings in Java?

Best practices include: Use StringBuilder/StringBuffer for heavy string manipulation in loops, Use equals() for content comparison (not ==), Use String literals when possible for pool benefits, Handle null checks properly, Consider String.join() for joining multiple strings (Java 8+), Use try-with-resources for I/O operations with Strings, and Be cautious with memory leaks in long-lived applications holding large Strings.

Previous Java Interview Questions Next