GamifiedGamified challengesPracticeRaceLeaderboardPricing

Learn data structures by watching them move, then doing it yourself. Press M anytime to toggle sound.

A product of Amypo Technologies, Coimbatore.

Learn

  • All topics
  • Learning path
  • How it works
  • About dotprep

Practice

  • Practice arena
  • Daily challenge
  • Gamified challenges
  • Race mode
  • Leaderboard

Interview prep

  • Java interview
  • Coding questions
  • Company questions
  • System design
  • Jobs & careers

You

  • Dashboard
  • Settings
  • Pricing
  • Create account

© 2026 dotprep

Content last updated 20 November 2026

GamifiedGamified challengesPracticeRaceLeaderboardPricing
Java interviewStrings & memory

Strings & memory

Why String is immutable, how the string pool works, StringBuilder, and where Java keeps your data.

beginner 14 min read 7 interview questions

On this page

1/7
  1. 01String is immutable
  2. 02The string pool
  3. 03StringBuilder and StringBuffer
  4. 04Stack vs heap
  5. 05Primitives, wrappers and autoboxing
  6. 06Interview questions
  7. 07Quick check
Back to top

String is immutable

Once created, a String never changes. Methods like toUpperCase() or concat() return a new string; the original stays as it was.

java
String s = "java";
s.toUpperCase(); // result thrown away
System.out.println(s); // java
s = s.toUpperCase(); // s now points at a new object "JAVA"
  • Security: strings are used for file paths, URLs and class names; nobody can change one after it was checked.
  • Thread safety: immutable objects can be shared between threads without locks.
  • Caching: the hash code is computed once and cached, which makes strings fast HashMap keys.
  • String pool: sharing literals is only safe because they can't change.

The string pool

String literals are stored once in the string pool (part of the heap since Java 7). Two literals with the same text refer to the same object. new String("x") always creates a separate object. intern() returns the pooled copy.

java
String a = "hello";
String b = "hello";
String c = new String("hello");
a == b; // true: same pooled object
a == c; // false: c is a separate object
a.equals(c); // true: same characters
a == c.intern(); // true

Always compare strings with equals(). == only tells you whether two references point at the same object.

StringBuilder and StringBuffer

Building a string with += in a loop creates a new string each time and copies all characters so far: O(n²) for n pieces. StringBuilder keeps a growable character array and appends in amortized O(1), like a dynamic array.

java
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i).append(',');
sb.setLength(sb.length() - 1); // drop the last comma
String result = sb.toString(); // "0,1,2,3,4"
StringStringBuilderStringBuffer
MutableNoYesYes
Thread-safeYes (immutable)NoYes (synchronized)
SpeedSlow for repeated editsFastestSlower than StringBuilder

Stack vs heap

Each thread has its own stack of frames: one per method call, holding parameters, local primitives and references. Objects (including arrays and strings) live on the shared heap. When a method returns its frame is popped; heap objects stay until no references reach them, then the garbage collector frees them.

  • Too-deep recursion fills the stack: StackOverflowError.
  • Too many live objects fill the heap: OutOfMemoryError.
  • Primitives inside objects (fields) live on the heap with the object.

Primitives, wrappers and autoboxing

Each primitive has a wrapper class (int → Integer). Collections hold objects only, so Java converts automatically: autoboxing (int → Integer) and unboxing back.

java
Integer a = 127, b = 127;
a == b; // true: values -128..127 are cached
Integer c = 128, d = 128;
c == d; // false: different objects
c.equals(d); // true
Integer n = null;
int x = n; // NullPointerException while unboxing

See it animated

StringsStack vs heap memory

Interview questions

Try answering out loud first, then open the model answer.

Q1Why is String immutable in Java?beginner

For security (strings hold paths, URLs and class names that must not change after validation), thread safety without locks, a cached hash code for fast map keys, and to make sharing literals in the string pool safe.

Q2What's the difference between == and equals() for strings?beginner

== checks whether two references point at the same object; equals() checks whether the characters are the same. Two equal strings can be different objects (e.g. one from new String() or built at run time), so use equals().

Q3How many objects does new String("abc") create?intermediate

Up to two: the literal "abc" in the string pool (only if it isn't there already, at class load) and one new String object on the heap from new.

Q4When would you use StringBuilder over String concatenation?beginner

When building a string in a loop or in many steps. Each + on a String creates a new object and copies characters, which is O(n²) overall; StringBuilder appends into one growable buffer. (The compiler already uses a builder for a single expression like a + b + c.)

Q5StringBuilder vs StringBuffer?beginner

Same API. StringBuffer's methods are synchronized, so it's thread-safe but slower. StringBuilder isn't synchronized; prefer it, since builders are almost always local to one thread.

Q6Why does Integer a = 128, b = 128; a == b print false but 127 prints true?intermediate

Autoboxing uses Integer.valueOf(), which caches values from -128 to 127. Inside that range both variables get the same cached object; outside it each boxing creates a new object, so == compares two different references. Use equals() for wrappers.

Q7What is stored on the stack and what on the heap?beginner

The stack holds a frame per method call: local primitives and references. The heap holds all objects and arrays, including their fields. Stacks are per-thread; the heap is shared by all threads and managed by the garbage collector.

Quick check

Question 1

1.String s = "a"; s.concat("b"); What is s now?

Question 2

2.Best choice for building a big string in a loop:

Question 3

3.Where do objects created with new live?

Question 4

4.Unboxing a null Integer into an int causes…

0 of 4 answered

Core Java & OOPException handling
Log inStart free