Strings in Java
A String represents text in Java. We use strings for names, messages, file paths, and many other values. A String object is immutable: its character sequence cannot be changed after the object is created.
Why Do We Need This?
A program may trim spaces from a name, compare two messages, or build a sentence from several values. Understanding strings helps us do these tasks without confusing a new result with a change to the original object.
Main Ideas
| Concept | What it means |
|---|---|
| String | Stores an immutable character sequence |
| StringBuilder | Builds and changes text without synchronization |
| StringBuffer | Offers synchronized methods for mutable text |
| equals() | Compares String contents |
| String pool | Supports sharing of interned strings |
Simple Working Example
Run this program on its own. All required imports and classes are included.
public class HelloWorld {
public static void main(String[] args) {
String name = "Meera";
String greeting = "Hello, " + name;
System.out.println(greeting);
System.out.println(name.equals("Meera"));
System.out.println(name.toUpperCase(java.util.Locale.ROOT));
System.out.println(name);
}
}Output
Hello, Meera
true
MEERA
MeeratoUpperCase returns a result without changing name. equals compares the text. The == operator instead checks whether two references point to the same object.
Topics in This Section
- String Class
- StringBuffer
- StringBuilder
- String Methods
- Immutable vs Mutable Strings
- How many ways to create String in Java
- String Pool
Easy Way to Remember
Choose String for text values. Consider StringBuilder when building text through many changes. Choose synchronization according to how the data is shared.
See you in next page....??