In Java, a String is an object that represents a sequence of characters. It is part of the java.lang package and is widely used in Java programming for storing and manipulating text.
A String in Java is immutable, meaning once a String object is created, its value cannot be changed. Any modification to a string results in the creation of a new String object.
Important features of Java Strings
1. Immutability of Strings
Java String objects are immutable. This means that once a String object is created, it cannot be modified. If you perform any operation (like changing a character), a new String object is created.
public class ImmutabilityExample {
public static void main(String[] args) {
String str = "Hello";
str = str + " World"; // Concatenation creates a new String
System.out.println(str); // Output: Hello World
}
}
Explanation: In this example, str was initially “Hello”. After concatenating ” World”, a new String is created, and str now refers to “Hello World”. The original string “Hello” was not changed.
2. String Declaration
A String can be declared using double quotes (” “), which indicates a string literal.
Example:
public class StringDeclarationExample {
public static void main(String[] args) {
String greeting = "Hello, World!";
System.out.println(greeting); // Output: Hello, World!
}
}
In this example, greeting is a String object initialized with the literal “Hello, World!”.
3. String Interning
Java uses string interning to manage memory efficiently. When you create a string using double quotes, Java checks if that string already exists in the string pool. If it exists, it reuses the reference to the existing string object; otherwise, it creates a new string.
Example:
public class StringInterning {
public static void main(String[] args) {
String s1 = "Hi";
String s2 = "Hi";
String s3 = new String("Hi");
// Check if s1 and s2 refer to the same object
System.out.println(s1 == s2); // Output: true (since they're in the string pool)
// Check if s1 and s3 refer to the same object
System.out.println(s1 == s3); // Output: false (s3 is created using new, so it's not interned)
// Interning the string
s3 = s3.intern();
System.out.println(s1 == s3); // Output: true (now s3 refers to the interned string)
}
}
In this example, s1 and s2 are pointing to the same string object in the string pool, while s3 initially refers to a different object created with the new keyword. Calling s3.intern() makes s3 refer to the string in the pool, making the comparison true.
4. String Methods
The String class provides a variety of methods for manipulating and inspecting strings. Below are some common string methods:
Example:
public class StringMethods {
public static void main(String[] args) {
String str = "Hello, World!";
// length() - returns the length of the string
System.out.println("Length: " + str.length()); // Output: 13
// charAt(int index) - returns the character at the specified index
System.out.println("Character at index 4: " + str.charAt(4)); // Output: o
// substring(int start, int end) - extracts a substring from the string
System.out.println("Substring (0, 5): " + str.substring(0, 5)); // Output: Hello
// equals(Object obj) - compares two strings for equality
String str2 = "hello, world!";
System.out.println("Are str and str2 equal? " + str.equals(str2)); // Output: false
// toUpperCase() - converts the string to uppercase
System.out.println("Uppercase: " + str.toUpperCase()); // Output: HELLO, WORLD!
// contains(CharSequence seq) - checks if the string contains a sequence
System.out.println("Contains 'World': " + str.contains("World")); // Output: true
// replace(CharSequence target, CharSequence replacement) - replaces characters
System.out.println("Replaced 'World' with 'Java': " + str.replace("World", "Java")); // Output: Hello, Java!
}
}
5. String Concatenation
Strings in Java can be concatenated using the + operator or using the concat() method. However, when dealing with multiple concatenations, it’s more efficient to use StringBuilder or StringBuffer.
Example with + and concat():
public class StringConcatenation {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
// Using + operator
String result1 = str1 + " " + str2;
System.out.println(result1); // Output: Hello World
// Using concat() method
String result2 = str1.concat(" ").concat(str2);
System.out.println(result2); // Output: Hello World
}
}
In this example, both the + operator and the concat() method concatenate two strings.