Strings in Java are a sequence of characters, commonly used for storing and manipulating text. The String
class is one of the most commonly used classes in Java and is a part of the java.lang
package. Unlike some other programming languages, Java strings are immutable, meaning that once a string is created, it cannot be changed.
1. Creating Strings
There are two primary ways to create strings in Java:
- Using String Literals
- Using the
new
Keyword
Example:
// Using String Literal
String greeting = "Hello, World!";
// Using the new Keyword
String welcome = new String("Welcome to Java!");
In the first example, the string is created using a string literal, which is the most common way to create strings. The second example demonstrates creating a string using the new
keyword, which explicitly allocates memory for the string.
2. String Immutability
As mentioned earlier, strings in Java are immutable. Once a String
object is created, it cannot be modified. Any operation that alters a string actually creates a new String
object with the modified value.
Example:
String original = "Java";
String modified = original.concat(" Programming");
System.out.println(original); // Outputs "Java"
System.out.println(modified); // Outputs "Java Programming"
In this example, the concat()
method does not change the original string but creates a new string with the combined value.
3. String Methods
The String
class provides numerous methods for performing operations on strings. Here are some of the most commonly used string methods:
length()
: Returns the length of the string.charAt(int index)
: Returns the character at the specified index.substring(int beginIndex, int endIndex)
: Returns a new string that is a substring of the original string.toLowerCase()
andtoUpperCase()
: Converts the string to lowercase or uppercase.trim()
: Removes any leading and trailing whitespace from the string.indexOf(String str)
: Returns the index of the first occurrence of the specified substring.replace(char oldChar, char newChar)
: Replaces all occurrences of a specified character with a new character.
Example:
String message = "Hello, Java!";
System.out.println("Length: " + message.length()); // Outputs 12
System.out.println("Character at index 1: " + message.charAt(1)); // Outputs e
System.out.println("Substring: " + message.substring(7)); // Outputs Java!
System.out.println("Lowercase: " + message.toLowerCase()); // Outputs hello, java!
System.out.println("Uppercase: " + message.toUpperCase()); // Outputs HELLO, JAVA!
System.out.println("Index of 'Java': " + message.indexOf("Java")); // Outputs 7
System.out.println("Replace 'Java' with 'World': " + message.replace("Java", "World")); // Outputs Hello, World!
4. String Concatenation
String concatenation is the process of joining two or more strings together. In Java, you can concatenate strings using the +
operator or the concat()
method.
Example:
String firstName = "John";
String lastName = "Doe";
// Using + Operator
String fullName = firstName + " " + lastName;
System.out.println(fullName); // Outputs John Doe
// Using concat() Method
String fullNameConcat = firstName.concat(" ").concat(lastName);
System.out.println(fullNameConcat); // Outputs John Doe
5. String Comparison
Java provides several methods to compare strings:
equals(String anotherString)
: Compares the content of two strings for equality.equalsIgnoreCase(String anotherString)
: Compares the content of two strings for equality, ignoring case.compareTo(String anotherString)
: Compares two strings lexicographically.
Example:
String str1 = "Hello";
String str2 = "hello";
System.out.println(str1.equals(str2)); // Outputs false
System.out.println(str1.equalsIgnoreCase(str2)); // Outputs true
System.out.println(str1.compareTo(str2)); // Outputs a negative value (because "H" is lexicographically less than "h")
6. StringBuilder and StringBuffer
For situations where you need to perform multiple modifications on a string, it’s more efficient to use StringBuilder
or StringBuffer
. These classes provide mutable sequences of characters.
StringBuilder
: Used for creating mutable strings. It is not thread-safe, meaning it is faster but not synchronized.StringBuffer
: Similar toStringBuilder
but is thread-safe, meaning it is synchronized.
Example:
StringBuilder sb = new StringBuilder("Hello");
sb.append(", World!");
System.out.println(sb); // Outputs Hello, World!
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(", Java!");
System.out.println(sbf); // Outputs Hello, Java!
In this example, StringBuilder
and StringBuffer
allow modifications to the string without creating new objects.
7. String Pool
Java optimizes memory usage by storing string literals in a special memory area called the “String Pool.” If a string literal already exists in the pool, the JVM will return a reference to the existing string instead of creating a new one. This mechanism ensures that string literals are reused, reducing memory consumption.
String str1 = "Java";
String str2 = "Java";
System.out.println(str1 == str2); // Outputs true (Both refer to the same string in the pool)
In this example, str1
and str2
refer to the same object in the string pool, so the ==
operator returns true
.
Summary
Strings in Java are a fundamental aspect of the language, used extensively for storing and manipulating text. While strings are immutable, the String
class offers a rich set of methods to perform various operations on strings. For more complex or frequent modifications, StringBuilder
and StringBuffer
provide mutable alternatives. Understanding how to effectively use strings is key to writing efficient and readable Java programs.