String ,String Buffer& String Buileder
String ,String Buffer& String Buileder
In
Java, strings are immutable, meaning once created, their content cannot be changed once created.
1. Using Character Array / ArrayList - Strings can be created by initializing a character array. For example:
2. Using the String Class - The String class creates immutable strings. Once a string is created, its content cannot be
modified. Operations like concatenation or changing the case of a string will create a new string object.
String literal
String s = “GeeksforGeeks”;
3. StringBuffer Class - The StringBuffer class creates mutable strings and is thread-safe. It is suitable for
multithreaded environments where multiple threads might access the same string object.
4. StringBuilder Class - The StringBuilder class is similar to StringBuffer but is not thread-safe. It is used in single-
threaded environments to avoid the performance overhead of synchronization.
Here, we explore some key methods provided by the String class in Java along with examples.
charAt() : The charAt() method returns the character at a specified index. Index starts from 0 (like arrays).
str.substring(start): Returns the substring from the start index to the end of the string.
str.substring(start, end) : Returns the substring from the start index to the end - 1 index.
Example:
import java.io.*;
class GFG {
System.out.println(str.length());
System.out.println(str.charAt(3));
System.out.println(str.substring(2));
System.out.println(str.substring(2, 4));
Output
eks
ek
When strings are created using literals, Java optimizes memory usage by storing them in a String Pool. If two string
literals have the same content, they share the same memory location in the pool. However, when strings are created
using the new keyword, they are stored in the heap memory, and each object gets a separate memory allocation,
even if they have the same content.
import java.io.*;
class GFG {
String s1 = "geek";
String s2 = "geek";
if (s1 == s2)
System.out.println("Yes");
else
System.out.println("No");
if (s1 == s3)
System.out.println("Yes");
else
System.out.println("No");
Output
Yes
No
contains() Method : The contains() method checks if a specific sequence of characters exists within a string. It
returns true if the sequence is found, otherwise false.
import java.io.*;
class GFG {
String s1 = "geeksforgeeks";
String s2 = "geeks";
// Check if s1 contains s2
System.out.println(s1.contains(s2));
Output
true
equals() Method : The equals() method compares two strings for equality based on their content. It is case-sensitive.
import java.io.*;
class GFG {
String s1 = "GeeksforGeeks";
String s2 = "GeeksforGeeks";
Output
true
import java.io.*;
class GFG {
String s1 = "geeksforgeeks";
String s2 = "for";
// Compare s1 and s2
if (res == 0)
System.out.println("Same");
System.out.println("s1 Greater");
else
System.out.println("s1 Smaller");
Output
s1 Greater
indexOf() Method : The indexOf() method returns the starting index of the first occurrence of a specified substring
within the string. If the substring is not found, it returns -1.
import java.io.*;
class GFG {
public static void main (String[] args) {
String s1 = "geeksforgeeks";
String s2 = "geek";
System.out.println(s1.indexOf(s2));
}
Output
0
String Concatenation : String concatenation is the process of joining two or more strings to form a single combined
string. In Java, there are multiple ways to achieve string concatenation, including using the + operator and
the concat() method.
import java.io.*;
class GFG {
String s1 = "geeks";
String s2 = s1;
// Concatenating "forgeeks" to s1
s1 = s1 + "forgeeks"; // OR s1 = s1.concat("forgeeks");
System.out.println(s1);
System.out.println(s1 == s2);
Output
geeksforgeeks
false
String Methods
"GeeksforGeeks".length(); // returns 13
2. Char charAt(int i): Returns the character at ith index.
3. String substring (int i): Return the substring from the ith index character to end.
4. String substring (int i, int j): Returns the substring from i to j-1 index.
5. String concat( String str): Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
6. int indexOf (String s): Returns the index within the string of the first occurrence of the specified string.
7. int indexOf (String s, int i): Returns the index within the string of the first occurrence of the specified string,
starting at the specified index.
8. Int lastIndexOf( String s): Returns the index within the string of the last occurrence of the specified string.
9. boolean equals( Object otherObj): Compares this string to the specified object.
10. boolean equalsIgnoreCase (String anotherString): Compares string to another string, ignoring case
considerations.
// strings to be compared
// strings to be compared
Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase).
13. String toLowerCase(): Converts all the characters in the String to lower case.
14. String toUpperCase(): Converts all the characters in the String to upper case.
15. String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not affect
whitespaces in the middle.
16. String replace (char oldChar, char newChar): Returns new string by replacing all occurrences
of oldChar with newChar.
String s1 = “feeksforfeeks“;
StringBuilder: StringBuilder is a class in Java that represents a mutable sequence of characters. Unlike the String
class, which creates immutable sequences, StringBuilder allows modification of its contents without creating new
objects. It is specifically designed for use in single-threaded environments, as it does not provide thread safety.
StringBuilder is a faster alternative to StringBuffer when thread synchronization is not required. Its functions are very
similar to those of the StringBuffer class, making it a straightforward option for mutable string manipulation.
StringBuffer: StringBuffer is a class in Java that also represents a mutable sequence of characters. However, unlike
StringBuilder, it provides thread safety by ensuring synchronization. This makes StringBuffer a suitable choice for
multi-threaded environments where multiple threads may access or modify the string concurrently. Although it has
slightly more overhead than StringBuilder due to synchronization, it ensures reliable operation in concurrent
scenarios. StringBuffer is often used when both mutability and thread safety are essential.
Recommendatio
Preferred for single-threaded programs. Used when thread safety is required.
n
class GfG
String s1 = "geeks";
String s2 = s1;
s1 = s1 + "forgeeks";
if(s1 == s2)
System.out.println("Same");
else
System.out.println("Not Same");
// as it is mutable in nature
sb1 = sb1.append("forgeeks");
if(sb1 == sb2)
System.out.println("Same");
else
System.out.println("Not Same");
Output
Not Same
Same
1. length():
The length() method is used to determine the number of characters in a sequence. It returns the length of
the sequence represented by the object. For example, if you call length() on a StringBuilder object, it will
return the number of characters currently stored in it.
2. charAt(index):
This method is used to fetch the character present at a specific index in the sequence. The index should be
between 0 and length()-1. For instance, if the string is "Geeks", charAt(1) will return 'e'.
3. indexOf(str):
The indexOf() method searches for the first occurrence of a specified substring within the sequence. If the
substring exists, the method returns the index of its first occurrence; otherwise, it returns -1.
4. indexOf(str, fromIndex):
This is a variation of the indexOf() method, which starts searching for the substring from a specified index. If
the substring is found, it returns the index of the first occurrence; otherwise, it returns -1.
5. lastIndexOf(str):
This method searches for the last occurrence of a specified substring within the sequence. If the substring
exists, it returns the index of its last occurrence; otherwise, it returns -1.
6. lastIndexOf(str, fromIndex):
Similar to lastIndexOf(str), this method begins the search from the specified fromIndex and moves backward
to find the last occurrence of the substring.
7. compareTo(sb):
The compareTo() method compares two sequences lexicographically. It returns 0 if the sequences are equal,
a positive value if the current sequence is greater, and a negative value if it is smaller.
8. substring(beginIndex):
This method returns a new sequence starting from the specified beginIndex to the end of the sequence.
9. substring(beginIndex, endIndex):
This variation of substring() allows you to specify both the starting and ending indices. It returns a new
sequence starting at beginIndex and ending at endIndex - 1.
10. chars():
The chars() method provides a stream of integer values representing the characters in the sequence.
1. append(x):
The append() method adds the specified data to the end of the sequence. This data can be of various types,
such as boolean, int, char, String, float, or Object. For example, you can append "World" to "Hello"
using append().
2. insert(offset, x):
This method allows you to insert data at a specified offset position in the sequence. For instance, you can
insert "Java" at index 4 in the string "GeeksFor" to make it "GeeksJavaFor".
3. setCharAt(index, c):
The setCharAt() method modifies the character at the specified index in the sequence. For example, you can
change the first character of "Geeks" to 'T', resulting in "Teeks".
4. reverse():
The reverse() method reverses the characters in the sequence. For instance, applying reverse() on "Geeks"
will give "skeeG".
5. deleteCharAt(index):
This method removes the character at the specified index in the sequence. For example, deleting the
character at index 3 in "Geeks" will result in "Gees".
6. delete(start, end):
This method removes all characters from the specified start index to end-1. For instance, deleting characters
from index 1 to 4 in "Geeks" will result in "Gs".
7. capacity():
The capacity() method returns the current storage capacity of the sequence. It indicates how much data can
be stored before the sequence needs to resize itself.
class GfG
sb.reverse();
System.out.println(sb);
// Appending to sb
sb.append("efg");
System.out.println(sb);
// with h
sb.setCharAt(1, 'h');
System.out.println(sb);
sb.delete(0, 2);
System.out.println(sb);
// Inserts "efg" at 1
sb.insert(1, "efg");
System.out.println(sb);
Output
abcd
abcdefg
ahcdefg
cdefg
cefgdefg