Chapter 17

Great! Let's move on to the Strings in Java (Part 1) with the same detailed style, including theory, code examples, memory maps, technical terminologies, and best practices.


Strings in Java (Part 1)

Introduction to Strings

In Java, String is a class provided in the java.lang package, used to handle text data. It is one of the most commonly used data types in Java programming.


Key Concepts Covered:

  • What is a String in Java?

  • How to create Strings

  • String pool concept in Java

  • Memory allocation for Strings

  • String methods (length, charAt, substring, equals, etc.)

  • Immutability of Strings

  • Memory maps during string operations

  • Best practices and technical terminologies


1. What is a String in Java?

A String represents a sequence of characters. In Java, strings are objects that are backed internally by a char array.

  • Example:

      String greeting = "Hello, World!";
    
  • Technical Detail: Java uses the UTF-16 encoding for String storage, meaning each character typically takes 2 bytes.


2. How to Create Strings in Java

There are two ways to create strings:

a) Using String Literals:

String s1 = "Hello";
String s2 = "Hello"; // Reuses the same object from the String pool
  • Why String Literals? Java optimizes memory by storing all string literals in a common pool called the String Pool.

b) Using the new Keyword:

String s3 = new String("Hello"); // Creates a new object every time

3. String Pool Concept in Java

The String Pool is a special memory area in the Java Heap Memory where string literals are stored to avoid redundancy.

Memory Map Example:

Memory AreaStored Objects
String Pool"Hello"
Heap MemoryNew String("Hello")
  • Note: Strings created with new are stored separately in the heap memory, not in the pool.

4. Memory Allocation for Strings

In Java, when you create a string literal, JVM checks the pool:

  • If the string exists, it reuses the object.

  • If not, it creates a new one.


5. String Methods in Java

MethodDescriptionExample
length()Returns the length of the string.s.length() → 11 (for "Hello World")
charAt(index)Returns the character at the specified index.s.charAt(0) → 'H'
substring(start, end)Returns a substring from start to end-1.s.substring(0, 5) → "Hello"
equals(Object obj)Checks if two strings are equal (case-sensitive).s1.equals(s2) → true
equalsIgnoreCase()Checks equality ignoring case differences."hello".equalsIgnoreCase("HELLO") → true
toUpperCase()Converts all characters to uppercase.s.toUpperCase() → "HELLO WORLD"
toLowerCase()Converts all characters to lowercase.s.toLowerCase() → "hello world"
trim()Removes leading and trailing spaces." hello ".trim() → "hello"
concat(String str)Concatenates two strings."Hello".concat(" World") → "Hello World"

6. Immutability of Strings

What is Immutability?

  • Once a String object is created, it cannot be changed.

  • Any operation that seems to modify a string actually creates a new string object.

  • Example:

      String s = "Hello";
      s = s + " World"; // A new object "Hello World" is created.
    

Why Strings are Immutable?

  • Security: Used in classes like String, Integer, etc., to avoid security vulnerabilities.

  • Performance: String pool allows memory optimization.

  • Synchronization: Immutable objects are inherently thread-safe.


7. Memory Maps During String Operations

OperationMemory State
String s1 = "Hello";String Pool → {"Hello"}
String s2 = "Hello";Reuses the same "Hello" object from the pool
s1 = s1 + " World";New Object in Heap → {"Hello World"}

8. Best Practices for Strings in Java

  • Use StringBuilder or StringBuffer for mutable strings when frequent modifications are needed.

  • Always use .equals() for string comparison instead of ==.

  • Avoid using new String() unnecessarily to save memory.

  • Use String.format() for complex string formatting.


Technical Terminologies Explained

  • Heap Memory: The runtime memory area where all Java objects are allocated.

  • String Pool: A special area within the heap where string literals are stored.

  • Immutability: The property that prevents modification of the object once created.

  • UTF-16 Encoding: A character encoding scheme where each character uses 16 bits.

  • Concatenation: Joining two or more strings together.


Interview Questions on Strings


1. What is the difference between == and .equals() when comparing strings?

  • == Operator: Compares references (memory addresses) of two objects. It checks whether both references point to the same memory location.

  • .equals() Method: Compares the contents (actual characters) of two strings, not their memory addresses.

Example:

String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

System.out.println(s1 == s2);      // true (Both refer to the same object in String pool)
System.out.println(s1 == s3);      // false (Different memory locations)
System.out.println(s1.equals(s3)); // true (Contents are the same)

2. Why are strings immutable in Java?

Reasons for String Immutability:

  1. Memory Efficiency: String pool helps save memory by reusing strings.

  2. Security: Strings are used in sensitive areas like file paths, class names, etc. If mutable, they could be altered, leading to vulnerabilities.

  3. Thread Safety: Immutable objects can be shared across threads without synchronization.

  4. Caching Hashcode: Strings cache their hashcode for better performance in hashing-based collections like HashMap.


3. Explain the concept of the String pool in Java.

The String pool is a special memory region inside the heap memory where string literals are stored. It helps in:

  • Reducing memory usage by reusing existing strings.

  • Improving performance since no new object is created if an identical string already exists in the pool.

Example:

String s1 = "Java";     // Stored in String pool
String s2 = "Java";     // Reuses the same object from the pool
String s3 = new String("Java"); // Created in heap memory (outside the pool)

4. What is the output of:

String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2);

Output:

false

Explanation:

  • s1 refers to the object in the String pool.

  • s2 refers to a new object created in the heap.

  • Since == compares references, and both are in different memory locations, the result is false.


5. How can you create mutable strings in Java?

Java provides two classes for mutable strings:

  • StringBuilder – Faster and not synchronized.

  • StringBuffer – Thread-safe due to synchronization.

Example:

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);  // Output: Hello World

Why use them?

  • If you need to modify strings frequently, use StringBuilder or StringBuffer to avoid creating new objects each time.

Conclusion for Strings in Java (Part 1)

In this part, we covered the fundamentals of Strings in Java, including creation, memory management, methods, and immutability. Understanding these basics lays the groundwork for more advanced string manipulations and memory-efficient coding in Java.