
Java Strings in Java
In Java, strings are objects that represent a sequence of characters. The String
class in Java is part of the java.lang
package, and it provides a variety of methods to manipulate and work with string values.
1. Creating Strings in Java
In Java, you can create strings in two ways:
String Literal:
Using double quotes (" "
), a string is created as a literal and stored in a string pool (interned).String str1 = "Hello, World!";
Using the
new
Keyword:
You can also create a new string explicitly using thenew
keyword, which will create a new object on the heap, even if the same value exists in the string pool.String str2 = new String("Hello, World!");
2. String Immutability
Strings in Java are immutable, which means that once a String
object is created, its value cannot be changed. If you perform any operation that modifies a string (like appending, replacing, etc.), a new String
object is created, and the original string remains unchanged.
String str = "Hello";str = str.concat(", World!"); // A new string is createdSystem.out.println(str); // Output: Hello, World!
3. String Pool
In Java, string literals are stored in a special memory area called the string pool (also known as the string constant pool). When you create a string literal, Java checks if that exact string already exists in the pool. If it does, it returns a reference to the existing string object, making string handling more efficient.
String str1 = "Hello";String str2 = "Hello"; // Points to the same object in the string poolSystem.out.println(str1 == str2); // Output: true
4. String Methods in Java
The String
class provides a variety of useful methods for manipulating strings. Some of the common methods are listed below:
Commonly Used String Methods
length()
Returns the length of the string (i.e., the number of characters).String str = "Hello";int length = str.length(); // Output: 5
charAt(int index)
Returns the character at the specified index.String str = "Hello";char ch = str.charAt(1); // Output: e
substring(int start, int end)
Returns a new string that is a substring of the original string, starting from thestart
index and ending before theend
index.String str = "Hello, World!";String substr = str.substring(7, 12); // Output: World
indexOf(String str)
Returns the index of the first occurrence of the substring.String str = "Hello, World!";int index = str.indexOf("World"); // Output: 7
equals(String anotherString)
Compares the string with another string for equality.String str1 = "Hello";String str2 = "hello";boolean isEqual = str1.equals(str2); // Output: false
equalsIgnoreCase(String anotherString)
Compares the string with another string, ignoring case considerations.String str1 = "Hello";String str2 = "hello";boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // Output: true
toLowerCase()
Converts all characters in the string to lowercase.String str = "HELLO";String lower = str.toLowerCase(); // Output: hello
toUpperCase()
Converts all characters in the string to uppercase.String str = "hello";String upper = str.toUpperCase(); // Output: HELLO
trim()
Removes leading and trailing spaces from the string.String str = " Hello ";String trimmed = str.trim(); // Output: Hello
replace(char oldChar, char newChar)
Replaces all occurrences of a character with another character.String str = "Hello";String replaced = str.replace('e', 'a'); // Output: Hallo
split(String regex)
Splits the string into an array of substrings based on the specified regular expression.String str = "apple,banana,cherry";String[] fruits = str.split(",");for (String fruit : fruits) { System.out.println(fruit);}// Output:// apple// banana// cherry
contains(String sequence)
Checks if the string contains the specified sequence of characters.String str = "Hello, World!";boolean contains = str.contains("World"); // Output: true
startsWith(String prefix)
Checks if the string starts with the specified prefix.String str = "Hello, World!";boolean startsWith = str.startsWith("Hello"); // Output: true
endsWith(String suffix)
Checks if the string ends with the specified suffix.String str = "Hello, World!";boolean endsWith = str.endsWith("World!"); // Output: true
toCharArray()
Converts the string into a character array.String str = "Hello";char[] chars = str.toCharArray();for (char c : chars) { System.out.print(c + " "); // Output: H e l l o}
valueOf(Object obj)
Converts an object to its string representation.int num = 123;String str = String.valueOf(num); // Output: 123
5. String Concatenation
You can concatenate strings using the +
operator or the concat()
method.
Using +
Operator:
String str1 = "Hello";String str2 = "World";String result = str1 + ", " + str2 + "!"; // Output: Hello, World!
Using concat()
Method:
String str1 = "Hello";String str2 = "World";String result = str1.concat(", ").concat(str2).concat("!"); // Output: Hello, World!
6. StringBuilder and StringBuffer
Since strings are immutable, frequent modifications can be inefficient because new String
objects are created every time a string is modified. To address this issue, Java provides StringBuilder
and StringBuffer
classes, which are mutable and allow for more efficient string manipulation.
StringBuilder
: Used when thread synchronization is not required.StringBuffer
: Similar toStringBuilder
, but it is thread-safe.
Example of StringBuilder
:
StringBuilder sb = new StringBuilder("Hello");sb.append(", World!");System.out.println(sb.toString()); // Output: Hello, World!
7. String Formatting
Java also provides the String.format()
method for formatting strings, similar to printf-style formatting in C.
String formatted = String.format("The value of pi is approximately: %.2f", Math.PI);System.out.println(formatted); // Output: The value of pi is approximately: 3.14
Summary
String objects in Java are immutable.
String methods allow you to manipulate and perform operations like trimming, replacing, splitting, and comparing strings.
Use StringBuilder or StringBuffer for efficient string manipulation when modifying the string frequently.
The String class provides a rich set of methods for handling strings, making Java a powerful language for text processing.
Let me know if you need further clarification or examples on any specific method!