Skip to main content

Interview questions - Strings

1. Why Strings are immutable?

 In Java, String is immutable, meaning once a String object is created, its value cannot be changed. Any operation that seems to modify a String actually creates a new object instead of modifying the existing one. Lets understand with below program. find code here



The String Constant Pool (also known as the String Intern Pool) is a special memory area inside the heap where Java stores string literals to optimize memory usage and improve performance.



When we create String password = "password@123"; using literal it will create instance in String constant pool and when we assign password = "changepassword", it will not change previous instance, but create new one inside String constant pool.
Check hash code before and after changing value both are different.

Lets understand scenario2 : code

public class StringMemoryCheck {
    public static void main(String[] args) {
        String s1 = "Java";  // String Pool
        String s2 = "Java";  // Reuses Pool Object
        String s3 = new String("Java");  // Heap
        String s4 = s3.intern();  // Moves reference to String constant Pool

        System.out.println(s1 == s2); // true  (Both in String Pool)
        System.out.println(s1 == s3); // false (Heap vs Pool)
        System.out.println(s1 == s4); // true as s4 moves to string constant pool

        System.out.println("s1: " + System.identityHashCode(s1));
        System.out.println("s2: " + System.identityHashCode(s2)); // Same as s1
        System.out.println("s3: " + System.identityHashCode(s3)); // Different (Heap)
        System.out.println("s4: " + System.identityHashCode(s4)); // Same as s1
    }
}

  • Using new creates a new object in heap memory
            If you create a string using the new keyword, Java does not use the string constant pool. Instead, it             creates a new string object in the heap.
  • Explicitly adding a string to the pool using intern()
            The intern() method forces a string to be placed in the pool, so it can be reused.

2. How Does Java Make String Immutable?

  • String stores characters in a private final array:
                public final class String {

                        private final char value[];
                }

          The final keyword prevents modification.

  • No Public Methods to Modify CharactersUnlike StringBuilder, String lacks methods like setCharAt(), ensuring immutability.

3. What are the advantages of String being immutable?

  1. Security - String is widely used in security-sensitive areas like passwords, database connections, and file paths
  2. String Pool Optimization
  3. Thread Safety - Since String is immutable, it is automatically thread-safe.

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

String: Immutable, meaning once created, it cannot be changed. Any modification creates a new object.
StringBuffer: Mutable and thread-safe (synchronized). Used when multiple threads need to modify a string.
StringBuilder: Mutable but not thread-safe (not synchronized). It is faster than StringBuffer and should be used in single-threaded environments.

5. What is the main advantage of using StringBuilder or StringBuffer over String?

Since String is immutable, modifying a String creates new objects, leading to unnecessary memory usage.
StringBuilder and StringBuffer allow modifying strings in-place, improving performance and reducing memory overhead.

6. What are the key differences between StringBuilder and StringBuffer?


7. Which one is thread-safe: StringBuilder or StringBuffer? Why?

StringBuffer is thread-safe because all its methods are synchronized, meaning only one thread can modify an instance at a time.
StringBuilder is not thread-safe because it does not use synchronization, making it faster but unsafe for multi-threaded use.
















Comments

Popular posts from this blog

Coding - Mostly Asked Coding Interview Question

 1. Print Mostly occurred string in Hello String import java.util.Map ; import java.util.Optional ; import java.util.stream.Collectors ; public class MostOccuringCharacter { // print most occuring character in hello string and write program to use optional public static void main ( String [] args ) { String str = "Hello" ; Optional < Map . Entry < Character , Long >> character = str .chars() .mapToObj( x -> ( char ) x ) .collect( Collectors . groupingBy ( x -> x , Collectors . counting ())) .entrySet() .stream() .max( Map . Entry . comparingByValue ()); if ( character .isPresent()){ System . out .println( "Most occurring character: " + character .get().getKey()); } //or character .ifPresent( c -> System . out .println( "Most occurring character: " + c .getKey())); } }

Internal Working of HashMap in Java

  A HashMap is a part of Java's Collections Framework , and it stores data in key-value pairs. Internally, it uses a hash table to store entries, making it efficient for fast lookups, insertions, and deletions. The underlying structure of a HashMap is based on a dynamic array of buckets (or "bins") and the hashing technique for quick access. Here’s an overview of how HashMap works internally: 1. Structure of HashMap A HashMap consists of the following key components: Buckets : A bucket is essentially an index in an array where hash collisions are stored. A HashMap is backed by an array, and each entry (a key-value pair) is stored in one of the array's indices (buckets). Entries (Key-Value Pairs) : Each entry is a key-value pair, stored in the buckets. Hashing : A hash function is used to determine the index (bucket) where a key-value pair will be stored. 2. Hashing Process When a key-value pair is added to a HashMap , the key undergoes a hashing process to de...