Introduction to Strings

In Java, a String is a sequence of characters enclosed in double quotes (""). It is one of the most commonly used data types for handling text. Strings in Java are objects, even though they can be declared like primitive types.

Syntax

Example

Declaring and Initializing Strings

In Java, you can create strings in multiple ways:

Using String Literals

  • When you create a String using double quotes (""), Java checks the String Pool (a special memory area inside the heap).
  • If the String already exists in the pool, the new variable (str2) will refer to the same object instead of creating a new one.
  • This saves memory and makes the program more efficient.

Using the new Keyword

  • The new keyword forces Java to create a new object in the heap, even if the same string already exists in the pool.
  • Each new String("Java") creates a separate object in memory, meaning str3 and str4 are different objects.

String Literal vs new Keyword in Java

Feature String Literal ("") new Keyword
Memory Location Stored in String Pool Stored in Heap Memory
Object Creation Reuses existing object (if available) Always creates a new object
Performance Faster (because of String Pool) Slower (creates a new object)
Recommended? Yes, for efficiency Only if a separate object is required

Immutable Nature of Strings

Strings in Java are immutable, meaning once created, they cannot be changed. Every modification creates a new object in memory.

If you need a mutable string, you can use StringBuilder or StringBuffer.