String Basics
What is a String?
In Java, a String is an object that represents a sequence of characters. Unlike primitive data types, Strings are immutable, which means once a String is created, its content cannot be changed. When you perform operations that seem to modify a String, you're actually creating a new String object.
String Creation and Initialization
There are multiple ways to create a String in Java:
// Using string literal
String str1 = "Hello, LabEx!";
// Using String constructor
String str2 = new String("Welcome");
// Creating an empty string
String emptyStr = "";
String Immutability
The immutability of Strings is a key characteristic in Java:
String original = "Hello";
String modified = original.toUpperCase(); // Creates a new String
System.out.println(original); // Still "Hello"
System.out.println(modified); // "HELLO"
String Comparison
Comparing Strings requires special methods:
graph TD
A[String Comparison] --> B[equals()]
A --> C[equalsIgnoreCase()]
A --> D[compareTo()]
Comparison Methods
Method |
Description |
Example |
equals() |
Compares content |
"hello".equals("Hello") is false |
equalsIgnoreCase() |
Compares content ignoring case |
"hello".equalsIgnoreCase("Hello") is true |
compareTo() |
Lexicographically compares Strings |
"apple".compareTo("banana") is negative |
Memory Considerations
Java uses a String Pool to optimize memory usage for String literals:
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s3)); // true
Common String Methods
String text = " LabEx Programming ";
text.length(); // Returns string length
text.trim(); // Removes leading/trailing whitespaces
text.toLowerCase(); // Converts to lowercase
text.toUpperCase(); // Converts to uppercase
text.substring(1, 5); // Extracts a portion of the string
Best Practices
- Prefer String literals over constructor
- Use
equals()
for content comparison
- Be aware of memory implications
- Use
StringBuilder
for frequent string modifications