Back to String & String Pool
Q10Question 10 of 12

What are the different ways to create a String?

Key Concepts
  • Literal: "hello" → auto-pooled, most common
  • new String("hello") → new heap object, bypasses pool
  • String.valueOf(42) → converts other types to String
  • StringBuilder.toString() → builds from a builder
  • char[].new String(chars) → from character array
  • String.format("%s: %d", name, count) → formatted string
  • Text block (Java 15+): triple-quoted multi-line strings

Definition

Strings can be created from literals (pooled), new String() (heap), valueOf(), StringBuilder.toString(), char arrays, String.format(), and text blocks.

Common creation methods:

  • Literal: "hello" – pooled, most common.
  • new String(): new String("hello") – new heap object, not pooled.
  • valueOf: String.valueOf(42) – converts int/double/boolean/char to String.
  • Builder: new StringBuilder().append("a").append("b").toString().
  • char array: new String(new char[]{'h','i'}).
  • format: String.format("Account %s balance %s", id, balance).
  • Text block: """multi-line text""" (Java 15+).

Seven doors into the bank: the main entrance (literal), the back door (new String), the ATM conversion (valueOf), the assembly line (StringBuilder), the manual entry (char array), the template printer (format), and the document scanner (text block).

Understanding the Concepts

All creation methods

JAVA
// 1. Literal (auto-pooled)
String a = "SAV2001";

// 2. new String (new heap object)
String b = new String("SAV2001");

// 3. valueOf (type conversion)
String c = String.valueOf(42);        // "42"
String d = String.valueOf(true);      // "true"
String e = String.valueOf(3.14);      // "3.14"

// 4. StringBuilder
String f = new StringBuilder("SAV").append("2001").toString();

// 5. char array
char[] chars = {'S', 'A', 'V'};
String g = new String(chars);  // "SAV"

// 6. String.format
String h = String.format("Account %s: Rs.%s", "SAV2001", "500000");

// 7. Text block (Java 15+)
String sql = """
    SELECT account_id, balance
    FROM accounts
    WHERE status = 'ACTIVE'
    """;

// 8. String.join
String csv = String.join(",", "SAV2001", "CUR3001", "LOAN5001");

What should a senior engineer know?

  • Prefer literals for constants and repeated values (pooled, fast).
  • Never use new String(literal) – it wastes memory creating a separate heap object.
  • String.formatted() (Java 15+) is an instance method: "Account %s".formatted(id).
  • Text blocks strip leading whitespace intelligently using stripIndent().

What are common mistakes?

A frequent mistake is using == to compare String content instead of equals().

Wrong approach:

JAVA
package com.bank.service;

public class AccountValidator {
    public boolean validateAccountType(String type) {
        // WRONG: == compares references, not content
        if (type == "SAVINGS") {
            return true;
        }
        return false;
    }
}

Correct approach:

JAVA
package com.bank.service;

public class AccountValidator {
    public boolean validateAccountType(String type) {
        // CORRECT: equals() compares content
        if ("SAVINGS".equals(type)) {  // null-safe: literal first
            return true;
        }
        return false;
    }
}

Using the literal on the left side of equals() prevents NullPointerException when the variable is null. This is a standard practice at National Bank of India for all string comparisons in service code.

What are the edge cases?

String behavior has several surprising edge cases that can catch banking developers off guard.

JAVA
package com.bank.edge;

public class StringEdgeCases {
    public static void main(String[] args) {
        // Edge case 1: compile-time constant folding
        String a = "SAV" + "2001";       // Compile-time constant
        String b = "SAV2001";
        System.out.println(a == b);       // true (same pool entry)

        // Edge case 2: variable concatenation is NOT pooled
        String prefix = "SAV";
        String c = prefix + "2001";       // Runtime concatenation
        System.out.println(b == c);       // false (different objects)

        // Edge case 3: final variable IS a compile-time constant
        final String finalPrefix = "SAV";
        String d = finalPrefix + "2001";  // Compile-time constant
        System.out.println(b == d);       // true (same pool entry)

        // Edge case 4: substring no longer shares char array (Java 7u6+)
        String full = "AccountNumber:SAV2001";
        String sub = full.substring(14); // New String, new char array
    }
}
TEXT
true
false
true

The final keyword makes the variable a compile-time constant, which changes how the compiler handles concatenation.

What are common interview follow-up questions?

Interviewers often follow up with these related questions:

  • How does this concept apply to a high-throughput banking transaction system?
  • What are the performance implications in a production environment?
  • How would you debug issues related to this concept?
  • What tools would you use to monitor this in production?
  • How does this behave differently in Java 8 vs Java 17+?

When answering follow-up questions, always relate your answer back to practical experience. For example, at National Bank of India, Rajesh debugged a production issue related to this concept by using JFR recordings and heap dumps. Providing concrete examples from banking systems shows the interviewer that you understand both the theory and the practice.

Visual Overview

DIAGRAM
  Ways to create a String:
    "literal"           → pooled (best for constants)
    new String("...")   → heap (avoid unless needed)
    String.valueOf(x)   → type conversion
    sb.toString()       → from builder
    new String(char[])  → from char array
    String.format(...)  → formatted
    """text block"""    → multi-line (Java 15+)
    String.join(",",...) → joined

Key Takeaway

Strings can be created from literals, new String(), valueOf(), StringBuilder, char arrays, format(), and text blocks. Use literals for constants (auto-pooled). Use StringBuilder.toString() for dynamic building. Avoid new String("literal") – it wastes memory.

One sentence to remember: use literals for constants, StringBuilder for building, valueOf for conversion, and text blocks for multi-line.

---

Share
Use ← → arrow keys to navigate