Stringbuffer in Java
Stringbuffer in Java
String in Java
• String class represents character strings, we can instantiate String by two ways.
• String str = "abc"; or String str = new String ("abc");
• String is immutable in Java, so it’s easy to share it across different threads or
functions.
• When we create a String using double quotes, it first looks for the String with
the same value in the JVM string pool, if found it returns the reference else it
creates the String object and then places it in the String pool. This way JVM
saves a lot of space by using the same String in different threads. But if a new
operator is used, it explicitly creates a new String in the heap memory.
• + operator is overloaded for String and used to concatenate two Strings.
Although internally it uses StringBuffer to perform this action.
• String overrides equals() and hashCode() methods, two Strings are equal only if
they have the same characters in the same order. Note that equals() method is
case sensitive, so if you are not looking for case sensitive checks, you should use
equalsIgnoreCase() method.
• A String represents a string in the UTF-16 format
• String is a final class with all the fields as final except “private int hash”. This
field contains the hashCode() function value and created only when the
hashCode() method is called and then cached in this field. Furthermore, the
hash is generated using final fields of String class with some calculations, so
every time hashCode() method is called, it will result in the same output. For
the caller, it’s like calculations are happening every time but internally it’s
cached in the hash field.
StringBuffer class in Java
• StringBuffer is a peer class of String that provides
much of the functionality of strings. String
represents fixed-length, immutable character
sequences while StringBuffer represents growable
and writable character sequences.
• StringBuffer may have characters and substrings
inserted in the middle or appended to the end.
It will automatically grow to make room for such
additions and often has more characters
preallocated than are actually needed, to allow
room for growth.
Compare String with StringBuffer class
Factors String StringBuffer
package Java.lang.String Java.lang.StringBufer
Class type Final Final
Modifiable Not allowed Allowed
Constructors String(); String(byte[] bytes); String(byte[] StringBuffer()
bytes, Charset charset); String(byte[] bytes, StringBuffer(String str)
int offset, int length) ;String(byte[] bytes,
int offset, int length, Charset charset);
StringBuffer(int capacity)
String(byte[] bytes, int offset, int length,
String charsetName); String(byte[] bytes,
String charsetName); String(char[] value);
String(char[] value, int offset, int count);
String(int[] codePoints, int offset, int
count); String(String original);
String(StringBuffer buffer)
Length of the Fixed once created Flexible length that can be modified
String in terms of both length and content.
StringBuffer append(boolean b)
Appends the string representation of the boolean argument to the sequence.
StringBuffer append(char c)
Appends the string representation of the char argument to this sequence.
StringBuffer append(char[] str)
Appends the string representation of the char array argument to this sequence.
StringBuffer append(char[] str, int offset, int len)
Appends the string representation of a subarray of the char array argument to this sequence.
StringBuffer append(CharSequence s)
Appends the specified CharSequence to this sequence.
StringBuffer append(CharSequence s, int start, int end)
Appends a subsequence of the specified CharSequence to this sequence.
StringBuffer append(double d)
Appends the string representation of the double argument to this sequence.
StringBuffer append(float f)
Appends the string representation of the float argument to this sequence.
StringBuffer append(int i)
Appends the string representation of the int argument to this sequence.
StringBuffer append(long lng)
Appends the string representation of the long argument to this sequence.
StringBuffer append(Object obj)
Appends the string representation of the Object argument.
StringBuffer append(String str)
Appends the specified string to this character sequence.
StringBuffer append(StringBuffer sb)
Appends the specified StringBuffer to this sequence.
Example
public class Test
{
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Test");
sb.append(" String Buffer");
System.out.println(sb);
StringBuffer sb2 = new StringBuffer("pi = ");
sb2.append(3.14159f);
System.out.println(sb2); // output is "pi = 3.14159"
}
}
Output
Test String Buffer
pi = 3.14159
StringBuffer appendCodePoint()
Modifier and Type Method and Description
StringBuffer appendCodePoint(int codePoint)
Appends the string representation of the codePoint argument to this sequence.
// Java praogram to illustrate the
// java.lang.StringBuffer.appendCodePoint(int cp)
import java.lang.*;
public class Geeks {
public static void main(String[] args)
{
StringBuffer sbf = new StringBuffer("Geeksforgeeks");
System.out.println("String buffer = " + sbf);
// Here it appends the CodePoint as String to the string buffer
sbf.appendCodePoint(65);
System.out.println("After appending CodePoint is = " + sbf);
}
}
Output:
String buffer = Geeksforgeeks
After appending CodePoint is = GeeksforgeeksA
StringBuffer methods in Java
Modifier Method and Description
and Type
int capacity()
Returns the current capacity. The
capacity is the amount of storage available for newly
inserted characters, beyond which an allocation will occur.
char charAt(int index)
Returns the char value in this sequence at the specified index. The first char value is
at index 0, the next at index 1, and so on, as in array indexing.The index argument
must be greater than or equal to 0, and less than the length of this sequence.
If the char value specified by the index is a surrogate, the surrogate value is
returned.
int codePointAt(int index)
Returns the character (Unicode code point) at the specified index. The index refers
to char values (Unicode code units) and ranges from 0 to length() - 1.If
the char value specified at the given index is in the high-surrogate range, the
following index is less than the length of this sequence, and the char value at the
following index is in the low-surrogate range, then the supplementary code point
corresponding to this surrogate pair is returned. Otherwise, the char value at the
given index is returned.
StringBuffer methods in Java
Modifier Method and Description
and Type
int codePointBefore(int index)
Returns the character (Unicode code point) before the specified index. The index
refers to char values (Unicode code units) and ranges from 1 to length().If
the char value at (index - 1) is in the low-surrogate range, (index - 2) is not
negative, and the char value at (index - 2) is in the high-surrogate range, then the
supplementary code point value of the surrogate pair is returned. If the char value
at index - 1 is an unpaired low-surrogate or a high-surrogate, the surrogate value is
returned.
int codePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the specified text range of this sequence.
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str = "JAVA";
System.out.println("String = " + str); // codepoint before index 1 i.e J
int retval = str.codePointBefore(1); // prints character before index1 in string
System.out.println("Character(unicode point) = " + retval);
}
}
String = JAVA
Character(unicode point) = 74
Methods in StringBuffer class in Java
1) length( ) and capacity( ): The length of a StringBuffer can be
found by the length( ) method, while the total allocated
capacity can be found by the capacity( ) method.
Code Example:
import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer(“JavaForSECS");
int p = s.length();
int q = s.capacity();
System.out.println("Length of string JavaForSECS =" + p);
System.out.println("Capacity of string JavaForSECS =" + q);
}
}
Output:
Length of string JavaForSECS=11
Capacity of string JavaForSECS=27
StringBuffer append() in Java
Modifier and Type Method and Description
int length()
Returns the length (character count).
int offsetByCodePoints(int index, int codePointOffset)
Returns the index within this sequence that is offset from the
given index by codePointOffset code points.
StringBuffer replace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters in the
specified String.
StringBuffer reverse()
Causes this character sequence to be replaced by the reverse of the sequence.
If there are any surrogate pairs included in the sequence, these are treated as
single characters for the reverse operation. Thus, the order of the high-low
surrogates is never reversed. Let n be the character length of this character
sequence (not the length in char values) just prior to execution of
the reverse method. Then the character at index k in the new character
sequence is equal to the character at index n-k-1 in the old character
sequence.Note that the reverse operation may result in producing surrogate
pairs that were unpaired low-surrogates and high-surrogates before the
operation. For example, reversing "\uDC00\uD800" produces "\uD800\uDC00"
which is a valid surrogate pair.
StringBuffer in Java
Modifier and Type Method and Description