Java Strings
In Java, a String
is a sequence of characters and is one of the most commonly used data types. Strings are objects in Java, representing text and are part of the java.lang
package. Java provides a wide range of methods to manipulate and work with strings, making them versatile and powerful.
Key Concepts of Strings in Java
Immutability: Strings in Java are immutable, meaning once a string is created, it cannot be changed. Any operation that alters a string actually creates a new string object in memory rather than modifying the original string.
String Pool: Java optimizes memory usage by storing string literals in a special memory area called the String Pool. When a string is created using double quotes (
" "
), Java first checks if the same literal is already in the pool. If it exists, it returns a reference to the existing object; otherwise, it adds the new string to the pool.String Class: Strings in Java are instances of the
String
class, which provides various methods for string manipulation, comparison, and conversion.
Creating Strings in Java
There are two ways to create strings in Java:
- String Literal: Using double quotes, which automatically places the string in the String Pool.
String str1 = "Hello";
- Using the
new
Keyword: This creates a new string object in the heap, even if the same string already exists in the pool.
String str2 = new String("Hello");
Common String Methods
Here are some commonly used methods of the String
class:
Length: Returns the length (number of characters) of the string.
String str = "Hello"; int length = str.length(); // Output: 5
Concatenation: Combines two strings using the
concat
method or the+
operator.String str1 = "Hello"; String str2 = " World"; String result = str1.concat(str2); // Output: "Hello World" String result2 = str1 + str2; // Output: "Hello World"
charAt(): Returns the character at a specified index.
String str = "Hello"; char ch = str.charAt(1); // Output: 'e'
substring(): Extracts a substring from the string.
String str = "Hello World"; String subStr = str.substring(6); // Output: "World" String subStr2 = str.substring(0, 5); // Output: "Hello"
toUpperCase() and toLowerCase(): Converts the string to uppercase or lowercase.
String str = "Hello"; String upper = str.toUpperCase(); // Output: "HELLO" String lower = str.toLowerCase(); // Output: "hello"
equals(): Compares two strings for equality. Use
equals()
to compare strings, not==
, which checks for reference equality.String str1 = "Hello"; String str2 = "Hello"; boolean isEqual = str1.equals(str2); // Output: true
replace(): Replaces occurrences of a character or substring with another character or substring.
String str = "Hello"; String replacedStr = str.replace('e', 'a'); // Output: "Hallo"
contains(): Checks if the string contains a particular sequence of characters.
String str = "Hello World"; boolean contains = str.contains("World"); // Output: true
split(): Splits the string based on a specified delimiter and returns an array of substrings.
String str = "Apple,Banana,Cherry"; String[] fruits = str.split(","); // Output: ["Apple", "Banana", "Cherry"]
Example Program with String Methods
Here’s a simple program that demonstrates a few commonly used string methods:
public class StringExample {
public static void main(String[] args) {
String str = "Hello World";
// Length of the string
System.out.println("Length: " + str.length());
// Extract a substring
System.out.println("Substring: " + str.substring(6));
// Convert to uppercase
System.out.println("Uppercase: " + str.toUpperCase());
// Check if the string contains "World"
System.out.println("Contains 'World': " + str.contains("World"));
// Replace 'l' with 'x'
System.out.println("Replaced: " + str.replace('l', 'x'));
// Splitting the string by space
String[] words = str.split(" ");
for (String word : words) {
System.out.println(word);
}
}
}
Output
Length: 11
Substring: World
Uppercase: HELLO WORLD
Contains 'World': true
Replaced: Hexxo Worxd
Hello
World
String Immutability in Detail
As mentioned earlier, strings in Java are immutable. This means once a string object is created, its internal state cannot be changed. Any method that seems to modify a string (such as concat
, replace
, etc.) actually creates a new string object with the modified value.
String str = "Hello";
str.concat(" World"); // This does not modify `str`
System.out.println(str); // Output: "Hello"
To modify the original string, you would need to assign the result to a new variable or the same variable:
str = str.concat(" World"); // Now `str` holds "Hello World"
System.out.println(str); // Output: "Hello World"
String vs StringBuilder vs StringBuffer
- String: Immutable and stored in the String Pool. Any modification creates a new string.
- StringBuilder: Mutable, meaning it can be modified without creating new objects. It is not thread-safe but offers better performance when used in a single-threaded environment.
- StringBuffer: Mutable like
StringBuilder
, but it is thread-safe, meaning it can be used in a multithreaded environment. However, it is slower thanStringBuilder
.
Example of StringBuilder:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb.toString()); // Output: "Hello World"
Summary
- Java
String
is a sequence of characters, stored as an object. - Strings are immutable, meaning their content cannot be changed once created.
- The
String
class provides various methods for string manipulation, such aslength()
,substring()
,concat()
,replace()
, etc. - Use
StringBuilder
orStringBuffer
if you need to modify strings frequently, as they are mutable.
Understanding how to effectively work with strings is essential for mastering Java programming, as they are used extensively in various applications.