Fiveable
Fiveable
Fiveable
Fiveable

11.1 String Declaration and Initialization

2 min readLast Updated on July 25, 2024

Strings are fundamental data structures in programming languages, used to represent text. They can be declared and initialized using literals, constructors, or by converting character arrays. String manipulation often creates new objects due to immutability.

String objects and literals differ in memory allocation and comparison behavior. Understanding these differences, along with concepts like the string pool and interning, is crucial for optimizing memory usage and performance in string-heavy applications.

String Fundamentals

String declaration and initialization

Top images from around the web for String declaration and initialization
Top images from around the web for String declaration and initialization
  • String literals enclosed in double quotes "Hello, World!" or single quotes 'Hello, World!' in some languages
  • String constructor using the new keyword new String("Hello") creates object in heap memory
  • Character arrays converted to strings using methods like String.valueOf() (Java)
  • String concatenation joins strings with + operator or concat() method ("Hello" + "World")
  • String formatting with printf() or format() methods for complex string construction
  • String interpolation embeds expressions directly in string literals (f"Value: {variable}" in Python)

String literals vs objects

  • String literals stored in string pool for memory efficiency with duplicate values
  • String objects created with new keyword stored in heap memory, always create new instance
  • Comparison using == operator compares references for objects, values for literals
  • Intern() method adds string objects to string pool for optimization

Immutability of strings

  • Immutability means strings cannot be changed after creation, ensuring thread safety and security
  • String manipulation creates new string objects, leaving original unchanged
  • StringBuilder and StringBuffer provide mutable alternatives for efficient string manipulation

Memory allocation for strings

  • String pool (constant pool) optimizes memory usage for string literals
  • Heap memory stores string objects created with new keyword
  • Stack memory holds references to string objects
  • Garbage collection automatically manages memory for unused strings
  • String interning stores only one copy of each distinct string value


© 2025 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.

© 2025 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Glossary