JavaStrings in Java

Introduction to Strings in Java

Understand what strings are in Java, how they are created, why they are immutable, and how Java manages strings in memory.

Introduction to Strings in JavaLink to this section

In Java, a String is a sequence of characters. Strings are widely used to store and manipulate text such as names, messages, and user input.

Java provides a built-in String class in the java.lang package, so no import is required.

Creating Strings in JavaLink to this section

There are two common ways to create a string in Java.

note

String literals are stored in a special memory area called the String Constant Pool.

String ImmutabilityLink to this section

Strings in Java are immutable, which means once a string object is created, its value cannot be changed.

tip

Immutability makes strings thread-safe and secure.

String Constant Pool (SCP)Link to this section

The String Constant Pool is a memory area inside the heap where Java stores string literals.

If the same string literal already exists, Java reuses it instead of creating a new object.

note

Both variables refer to the same object in memory.

Comparing StringsLink to this section

Java provides two ways to compare strings.

  1. == compares references (memory location)
  2. equals() compares actual content

warning

Always use equals() when comparing string content.
Introduction to Strings in Java
Question 1 of 5

Which package contains the String class?

Introduction to Strings in Java

medium
  1. Create two strings using literals and check whether they refer to the same object.
  2. Create strings using new keyword and compare them using == and equals().
  3. Demonstrate string immutability with an example.
  4. Write a program that compares two user-input strings.
  5. Explain the role of the String Constant Pool in memory optimization.