StringBuilder append() char array len in Java

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

Syntax:

StringBuilder java.lang.StringBuilder.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.

Note: 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 < 0 or offset+len > str.length.

For Example:

StringBuilder str = new StringBuilder("HELLO")

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

int offset = 0

int len = 2

str.append(arr1, offset, len) = > It returns HELLOra.

Approach 1: When the index is in the range.

Java

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

        StringBuilder str = new StringBuilder("HELLO");
        // 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:

HELLOra


Approach 2: When the index is out of range.

Java

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

        StringBuilder str = new StringBuilder("HELLO");
        // append the char array offset value
        char arr1[] = { 'r''a''m' };
        int offset = -1;
        int len = 2;
        str.append(arr1, offset, len);
        System.out.println(str);
    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: start -1, end 1, 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.StringBuilder.append(StringBuilder.java:227)


No comments:

Post a Comment