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 ImmutabilityLink to this section
Strings in Java are immutable, which means once a string object is created, its value cannot be changed.
tip
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
Comparing StringsLink to this section
Java provides two ways to compare strings.
- == compares references (memory location)
- equals() compares actual content
warning
Which package contains the String class?
Introduction to Strings in Java
- Create two strings using literals and check whether they refer to the same object.
- Create strings using new keyword and compare them using == and equals().
- Demonstrate string immutability with an example.
- Write a program that compares two user-input strings.
- Explain the role of the String Constant Pool in memory optimization.