String

  • String literal: A string Literal in Java is basically a sequence of characters from the source character set.
  • String literals initialised are an object of this String class.

💡 While printing an object, Java compiler implicitly calls toString() method.

String Memory Management

String Constant Pool

Special memory area in which string literals are stored

String Initialization using literals

Creating a String literal → JVM checks the String Constant Pool.

  • Exists => Points to the same 'literal'
  • Doesn't Exist => New instance created

String Initialization using new

String str = new String(); //null
String str = new String("Kya challa?")

New object created irrespective of whether the literal already exists or not

Immutability

String in Java is an Immutable Class.

Benefits

The main benefits of immutability come in case of multi-threaded applications, functional programming and high-security systems.

  • Thead safety
  • Predictable behavior
  • Enhanced security: ensures that sensitive data cannot be modified after its created preventing unintended or malicious change.
  • Caching:
    • Immutable objects can be safely shared across different parts of program.
    • Hashcodes for hash-based structures can be precomputed and cached - since they won't change
  • Works well with Functional Programming
    • Immutability is one of the principles of functional programming
    • Immutable objects ensure that functions don't modify anything outside their scope

  • String Pooling: Memory management using string pool is only possible because strings are immutable.

null vs empty String

String getSome;
String getMose = "";

Both of them are not the same. "" is a literal and has a reference pointing to it in the String constant pool, while getSome has no value/reference in it so its null → default value for String.


Children
  1. String Buffer
  2. String Builder
  3. String Comparison

Backlinks