In Java, strings are objects that represent sequences of characters. The Java language provides special support for strings through the String
class in the java.lang
package.
Creating Strings
There are two main ways to create strings in Java:
- String literals (stored in string pool):
String str1 = "Hello World";
- Using new keyword (creates new object in heap memory):
String str2 = new String("Hello World");
Important String Methods
Java's String
class provides many useful methods:
Basic Methods
String s = "Hello";
int length = s.length(); // 5
char c = s.charAt(1); // 'e'
String sub = s.substring(1, 3); // "el"
Comparison Methods
String s1 = "Hello";
String s2 = "hello";
boolean equal = s1.equals(s2); // false
boolean equalIgnoreCase = s1.equalsIgnoreCase(s2); // true
int compare = s1.compareTo(s2); // negative number (H < h)
Searching Methods
String s = "Hello World";
int index = s.indexOf('o'); // 4
int lastIndex = s.lastIndexOf('o'); // 7
boolean contains = s.contains("World"); // true
Modification Methods
String s = " Hello World ";
String trimmed = s.trim(); // "Hello World"
String replaced = s.replace('l', 'L'); // " HeLLo WorLd "
String upper = s.toUpperCase(); // " HELLO WORLD "
String lower = s.toLowerCase(); // " hello world "
Splitting and Joining
String s = "apple,banana,orange";
String[] fruits = s.split(","); // ["apple", "banana", "orange"]
String joined = String.join("-", fruits); // "apple-banana-orange"
String Immutability
Strings in Java are immutable - once created, their values cannot be changed. Operations that appear to modify strings actually create new string objects.
String s = "hello";
s.concat(" world"); // Doesn't change s
s = s.concat(" world"); // Now s refers to new string "hello world"
StringBuilder and StringBuffer
For mutable sequences of characters, Java provides:
-
StringBuilder
(faster, not thread-safe) -
StringBuffer
(thread-safe, slower)
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies the existing object
String result = sb.toString(); // "Hello World"
String Formatting
Java provides several ways to format strings:
String formatted = String.format("Name: %s, Age: %d", "Alice", 25);
// "Name: Alice, Age: 25"
Important Notes
- Use
equals()
to compare string contents, not==
(which compares references) - Strings are stored in UTF-16 encoding
- Java performs string interning for literals to save memory
- For heavy string manipulation, prefer
StringBuilder
over concatenation with+
Top comments (0)