Showing posts with label StringBuffer class. Show all posts
Showing posts with label StringBuffer class. Show all posts

StringBuffer class Methods in Java Part - II

java.lang.StringBuffer

A thread-safe, mutable sequence of characters. A string buffer is like a String but can be modified. At any point in time, it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

Some methods of StringBuffer class


indexOf(String str, int fromIndex)It returns the index within this string of the first occurrence of the specified substring, starting at the specified index.


insert()Inserts the string representation of the Object (like boolean, int, char, etc) argument into this character sequence.


insert(int index, char[] str, int offset, int len)It inserts the string representation of a subarray of the str array argument into this sequence. 


insert(int dstOffset, CharSequence s, int start, int end)It inserts a subsequence of the specified CharSequence into this sequence.


lastIndexOf(String str)It returns the index within this string of the last occurrence of the specified substring.


lastIndexOf(String str, int fromIndex): It returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.


length(): It returns the length of this character sequence.


offsetByCodePoints()It returns the index within this sequence that is offset from the given index by codePointOffset code points.


replace()It replaces the characters in a substring of this sequence with characters in the specified String.


reverse()It replace this character sequence by the reverse of the sequence.


setCharAt()The character at the specified index is set to ch.


setLength()It sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument.


subSequence()It returns a CharSequence that is a subsequence of this sequence.


substring(int start)It returns a new String that contains a subsequence of characters currently contained in this character sequence.


substring(int start, int end)It returns a new String that contains a subsequence of characters currently contained in this sequence.


toString()It returns a string containing the characters in this sequence in the same order as this sequence.


trimToSize()It attempts to reduce the storage used for the character sequence.


Some more Methods of StringBuffer


StringBuffer trimToSize() in Java

trimToSize(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

void java.lang.StringBuffer.trimToSize()

This method attempts to reduce the storage used for the character sequence. If the buffer is larger than necessary to hold its current sequence of characters, then it may be resized to become more space-efficient.

Approach

Java

public class TrimToSize {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        System.out.println("Capacity = " + 
str.capacity() + " Length = " + str.length());
        str.trimToSize();

        System.out.println("Capacity = " + 
str.capacity() + " Length = " + str.length());
    }
}


Output:

Capacity = 27 Length = 11 Capacity = 11 Length = 11


StringBuffer toString() in Java

toString(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

String java.lang.StringBuffer.toString()

This method returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.

Parameters: NA

Returns: a string consisting of exactly this sequence of characters.

For Example:

StringBuffer str = new StringBuffer("Hello World")

str.toString() = > It returns Hello World.

Approach

Java

public class ToString {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        System.out.println(str.toString());
    }
}

Output:

Hello World

StringBuffer substring() range in Java

substring(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

String java.lang.StringBuffer.substring(int start, int end)

This method takes two arguments of type int as its parameters. This method returns a new String that contains a subsequence of characters currently contained in this sequence. The substring begins at the specified start and extends to the character at index end - 1.

Parameters: Two parameters are required for this method.

start: The beginning index, inclusive.

end: The ending index, exclusive.

Returns: The new string.

Throws:

StringIndexOutOfBoundsException - if start or end is negative or greater than length(), or start is greater than end.

For Example:

StringBuffer str = new StringBuffer("Hello World")

int start = 2, end = 7

str.substring(start,end) = > It returns llo W.

Approach 1: When the indexes are in the range.

Java

public class SubstringRange {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int start = 2, end = 7;
        System.out.println(str.substring(start, end));
    }
}

Output:

llo W


Approach 2: When the indexes are out of range.

Java

public class SubstringRange {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int start = 8, end = 7;
        System.out.println(str.substring(start, end));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 8, end 7, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:1066) at java.base/java.lang.StringBuffer.substring(StringBuffer.java:519)


StringBuffer substring() in Java

substring(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

String java.lang.StringBuffer.substring(int start)

This method takes one argument of type int as its parameter. This method returns a new String that contains a subsequence of characters currently contained in this character sequence. The substring begins at the specified index and extends to the end of this sequence.

Parameters: One parameter is required for this method.

start: The beginning index, inclusive.

Returns: The new string.

Throws:

StringIndexOutOfBoundsException - if start is less than zero, or greater than the length of this object.

For Example:

StringBuffer str = new StringBuffer("Hello World")

int start = 4

str.substring(start) = > It returns o World.

Approach 1: When the index is in the range.

Java

public class Substring {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int start = 4;
        System.out.println(str.substring(start));
    }
}

Output:

o World


Approach 2: When the index is in the range.

Java

public class Substring {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int start = 15;
        System.out.println(str.substring(start));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 15, end 11, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:1066) at java.base/java.lang.StringBuffer.substring(StringBuffer.java:519) at java.base/java.lang.StringBuffer.substring(StringBuffer.java:501)


StringBuffer subSequence() in Java

subSequence(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

CharSequence java.lang.StringBuffer.subSequence(int start, int end)

This method takes two arguments of type int as its parameters. This method returns a CharSequence that is a subsequence of this sequence. The subsequence starts with the char value at the specified index and ends with the char value at index end - 1.

Parameters: Two parameters are required for this method.

start: the start index, inclusive.

end: the end index, exclusive.

Returns: the specified subsequence.

Throws:

StringIndexOutOfBoundsException - if start or end is negative, if the end is greater than length(), or if start is greater than the end.

For Example:

StringBuffer str = new StringBuffer("Hello World")

int start = 3, end = 8

str.subSequence(start,end) = > It returns lo Wo.

Approach 1: When the indexes are in the range.

Java

public class SubSequence {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int start = 3, end = 8;
        System.out.println(str.subSequence(start, end));
    }
}

Output:

lo Wo


Approach 2: When the indexes are out of range.

Java

public class SubSequence {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int start = 10, end = 8;
        System.out.println(str.subSequence(start, end));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 10, end 8, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:1066) at java.base/java.lang.StringBuffer.subSequence(StringBuffer.java:510)


StringBuffer setLength() in Java

setLength(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

void java.lang.StringBuffer.setLength(int newLength)

This method takes one argument of type int as its parameter. This method sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument. If the newLength argument is less than the current length, the length is changed to the specified length.

Note: The newLength argument must be greater than or equal to 0.

Parameters: One parameter is required for this method.

newLength: the new length.

Throws:

StringIndexOutOfBoundsException - if the newLength argument is negative.

Approach 1: When the newLength is positive.

Java

public class SetLength {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello");

        int newLength = 100;
        str.setLength(newLength);

        System.out.println(str.length());
    }
}

Output:

100


Approach 2: When the newLength is negative.

Java

public class SetLength {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello");

        int newLength = -1;
        str.setLength(newLength);

        System.out.println(str.length());
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.base/java.lang.AbstractStringBuilder.setLength(AbstractStringBuilder.java:319) at java.base/java.lang.StringBuffer.setLength(StringBuffer.java:228)


StringBuffer setCharAt() in Java

setCharAt(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

void java.lang.StringBuffer.setCharAt(int index, char ch)

This method takes two arguments, one of type int and another of type char as its parameters. The character at the specified index is set to ch. This sequence is altered to represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index.

Note: The index argument must be greater than or equal to 0, and less than the length of this sequence.

Parameters: Two parameters are required for this method.

index: the index of the character to modify.

ch: the new character.

Throws:

StringIndexOutOfBoundsException - if index is negative or greater than or equal to length().

Approach 1: When the index is in the range.

Java

public class SetCharAt {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int index = 2;
        char ch = 'X';
        str.setCharAt(index, ch);

        System.out.println(str);
    }
}

Output:

HeXlo World


Approach 2: When the index is out of range.

Java

public class SetCharAt {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int index = 15;
        char ch = 'X';
        str.setCharAt(index, ch);

        System.out.println(str);
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 15, length 11 at java.base/java.lang.String.checkIndex(String.java:3693) at java.base/java.lang.AbstractStringBuilder.setCharAt(AbstractStringBuilder.java:533) at java.base/java.lang.StringBuffer.setCharAt(StringBuffer.java:293)


StringBuffer reverse() in Java

reverse(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

StringBuffer java.lang.StringBuffer.reverse()

Causes this character sequence to be replaced by the reverse of the sequence.

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.

Returns: a reference to this object.

For Example:

StringBuffer str = new StringBuffer("Hello World")

str.reverse() = > It returns dlroW olleH.

Approach

Java

public class Reverse {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        System.out.println(str.reverse());
    }
}

Output:

dlroW olleH

StringBuffer replace() in Java

replace(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

StringBuffer java.lang.StringBuffer.replace(int start, int end, String str)

This method takes three arguments, two are of type int and one of type String as its parameters. This method replaces the characters in a substring of this sequence with characters in the specified String.

Note: The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists.

Parameters: Three parameters are required for this method.

start: The beginning index, inclusive.

end: The ending index, exclusive.

str: String that will replace previous contents.

Returns: This object.

Throws:

StringIndexOutOfBoundsException - if start is negative, greater than length(), or greater than end.

For Example:

StringBuffer str = new StringBuffer("Hello World")

int start = 2, end = 7

String str1 = "ABCABC"

str.replace(start, end, str1) = > It returns HeABCABCorld.

Approach 1: When the index is in the range.

Java

public class Replace {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int start = 2, end = 7;
        String str1 = "ABCABC";
        System.out.println(str.replace(start, end, str1));
    }
}

Output:

HeABCABCorld


Approach 2: When the index is out of range.

Java

public class Replace {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int start = -1, end = 7;
        String str1 = "ABCABC";
        System.out.println(str.replace(start, end, str1));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start -1, end 7, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:995) at java.base/java.lang.StringBuffer.replace(StringBuffer.java:491)


StringBuffer offsetByCodePoints() in Java

offsetByCodePoints(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

int java.lang.StringBuffer.offsetByCodePoints(int index, int codePointOffset)

This method takes two arguments of type int as its parameters. This method returns the index within this sequence that is offset from the given index by codePointOffset code points.

Parameters: Two parameters are required for this method.

index: the index to be offset.

codePointOffset: the offset in code points.

Returns: the index within this sequence.

Throws: 

IndexOutOfBoundsException - if index is negative or larger then the length of this sequence, or if codePointOffset is positive and the subsequence starting with index has fewer than codePointOffset code points, or if codePointOffset is negative and the subsequence before index has fewer than the absolute value of codePointOffset code points.

For Example:

StringBuffer str = new StringBuffer("Hello World")

int index = 3

int codePointOffset = 4

str.offsetByCodePoints(index,codePointOffset) = > It returns 7.

Approach 1: When the index is in the range.

Java

public class OffsetByCodePoints {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int index = 3;
        int codePointOffset = 4;
        System.out.println(str.offsetByCodePoints(index, 
codePointOffset));

    }
}

Output:

7


Approach 2: When the index is out of range.

Java

public class OffsetByCodePoints {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int index = -1;
        int codePointOffset = 4;
        System.out.println(str.offsetByCodePoints(index,
 codePointOffset));

    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.lang.AbstractStringBuilder.offsetByCodePoints(AbstractStringBuilder.java:472) at java.base/java.lang.StringBuffer.offsetByCodePoints(StringBuffer.java:273)


StringBuffer length() in Java

length(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

int java.lang.StringBuffer.length()

This method returns the length of this character sequence. The length is the number of 16-bit chars in the sequence.

Parameters: NA

Returns: The number of chars in this sequence.

For Example:

StringBuffer str = new StringBuffer("Hello World")

str.length() = > It returns 11.

Approach

Java

public class Length {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        System.out.println(str.length());

    }
}

Output:

11

StringBuffer lastIndexOf() index in Java

lastIndexOf(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

int java.lang.StringBuffer.lastIndexOf(String str, int fromIndex)

This method takes two arguments, one of type String and another of type int as its parameters. This method returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

Parameters: Two parameters are required for this method.

str: the substring to search for.

fromIndex: the index to start the search from.

Returns: the index of the last occurrence of the specified substring, searching backward from the specified index, or -1 if there is no such occurrence.

For Example:

StringBuffer str = new StringBuffer("Hello World")

String str1 = "l"

int fromIndex = 4

str.lastIndexOf(str1,fromIndex) = > It returns 3.

Approach

Java

public class LastIndexOfindex {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        String str1 = "l";
        int fromIndex = 4;
        System.out.println(str.lastIndexOf(str1, fromIndex));
    }
}

Output:

3

StringBuffer lastIndexOf() in Java

lastIndexOf(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

int java.lang.StringBuffer.lastIndexOf(String str)

This method takes one argument of type String as its parameter. This method returns the index within this string of the last occurrence of the specified substring.

Note: The last occurrence of the empty string "" is considered to occur at the index value this.length().

Parameters: One parameter is required for this method.

str: the substring to search for.

Returns: the index of the last occurrence of the specified substring, or -1 if there is no such occurrence.

For Example:

StringBuffer str = new StringBuffer("Hello World")

String str1 = "l"

str.lastIndexOf(str1) = > It returns 9.

Approach

Java

public class LastIndexOf {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        String str1 = "l";
        System.out.println(str.lastIndexOf(str1));
    }
}

Output:

9