Fundamentals 5 min read

Understanding Java String Object Creation and Memory Allocation

This article explains how Java handles string literals and new String objects, detailing the creation of objects in the constant pool and heap, the resulting memory layout, and the outcomes of reference comparisons, while also providing code examples and additional resources.

Top Architect
Top Architect
Top Architect
Understanding Java String Object Creation and Memory Allocation

The author, a senior architect, introduces the topic of Java string object creation and memory allocation.

1. String a = "abc" creates zero or one objects depending on whether the literal exists in the string constant pool. The process involves checking the pool, possibly creating the literal, creating a char array on the stack, constructing a String object on the heap, and placing it into the pool.

常量池中不存在"abc"字符串:
(1)在栈中创建3个char型字符'a','b','c'
(2)在堆中new一个String对象,值为上述char数组
(3)把这个String对象放进字符串常量池中
(4)将a指向这个对象在字符串常量池中的地址。
String a = "abc";
等价于
char data[] = {'a','b','c'};
String a = new String(data);

2. String a = new String("abc") always creates a new object on the heap, resulting in one or two objects overall.

The author then compares several references:

String a = "abc";
String b = "abc";
String c = new String("abc");
String d = new String("abc");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(c == d);

The output is true , false , false , demonstrating that literals share the same object while new String creates distinct heap objects.

The article concludes by inviting readers to discuss, ask questions, and join the architect community, and provides links to additional resources and interview question collections.

JavaMemory ManagementObject CreationString()Constant PoolReference Comparison
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.