StringBuffer append() char array len in Java

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

Syntax:

StringBuffer java.lang.StringBuffer.append(char[] str, int offset, int len)

This method takes three arguments, one of type char array and the other two are of type int as its parameters. This method appends the string representation of a subarray of the char array argument to this sequence. Characters of the char array str, starting at index offset, are appended, in order, to the contents of this sequence. The length of this sequence increases by the value of len. 

Parameters: Three parameters are required for this method.

str: the characters to be appended.

offset: the index of the first char to append.

len: the number of chars to append.

Returns: a reference to this object.

Throws:

IndexOutOfBoundsException - if offset < 0 or len < 0or offset+len > str.length.

For Example:

StringBuffer str = new StringBuffer("Hello World")

char arr1[] = { 'r', 'a', 'm' }

int offset = 0

int len = 2

str.append(arr,offset,len) = > It returns Hello Worldra.

Approach 1: When no exceptions.

Java

public class AppendStringBufferArraylen {
    public static void main(String[] args) {
        StringBuffer str = new StringBuffer("Hello World");
        // append the char array offset value
        char arr1[] = { 'r''a''m' };
        int offset = 0;
        int len = 2;
        str.append(arr1, offset, len);
        System.out.println(str);

    }
}

Output:

Hello Worldra


Approach 2: IndexOutOfBoundsException

Java

public class AppendStringBufferArraylen {
    public static void main(String[] args) {
        StringBuffer str = new StringBuffer("Hello World");
        // append the char array offset value
        char arr1[] = { 'r''a''m' };
        int offset = 3;
        int len = 2;
        str.append(arr1, offset, len);
        System.out.println(str);

    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: start 3, end 5, length 3 at java.base/java.lang.AbstractStringBuilder.checkRange(AbstractStringBuilder.java:1794) at java.base/java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:734) at java.base/java.lang.StringBuffer.append(StringBuffer.java:404)


No comments:

Post a Comment