CharArrayWriter append(CharSequence, int, int) in Java

append(CharSequence, int, int): This method is available in the java.io.CharArrayWriter class of Java.

Syntax:

CharArrayWriter java.io.CharArrayWriter.append(CharSequence csq, int start, int end)

This method takes three arguments. This method appends a subsequence of the specified character sequence to this writer.

Parameters: Three parameters are required for this method.

csq: The character sequence from which a subsequence will be appended. If csq is null, then characters will be appended as if csq contained the four characters "null".

start: The index of the first character in the subsequence.

end: The index of the character following the last character in the subsequence.

Returns: This writer.

Throws:

IndexOutOfBoundsException - If start or end is negative, the start is greater than the end, or end is greater than csq.length().

Approach 1: When no exception

Java

import java.io.CharArrayWriter;
import java.io.IOException;

public class CharArrayWriterappend3 {
    public static void main(String[] args) throws IOException {
        CharArrayWriter charArrayWriter = new CharArrayWriter();

        char cbuf[] = { 'a', 'b', 'c', 'd' };
        charArrayWriter.write(cbuf);

        CharSequence csq = "ABCD";
        int start = 1, end = 3;
        charArrayWriter.append(csq, start, end);

        System.out.println(charArrayWriter.toString());
        charArrayWriter.close();
    }
}

Output:

abcdBC


Approach 2: IndexOutOfBoundsException 

Java

import java.io.CharArrayWriter;
import java.io.IOException;

public class CharArrayWriterappend3 {
    public static void main(String[] args) throws IOException {
        CharArrayWriter charArrayWriter = new CharArrayWriter();

        char cbuf[] = { 'a', 'b', 'c', 'd' };
        charArrayWriter.write(cbuf);

        CharSequence csq = "ABCD";
        int start = -1, end = 3;
        charArrayWriter.append(csq, start, end);

        System.out.println(charArrayWriter.toString());
        charArrayWriter.close();
    }
}

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin -1, end 3, length 4 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3734) at java.base/java.lang.String.substring(String.java:1903) at java.base/java.lang.String.subSequence(String.java:1942) at java.base/java.io.CharArrayWriter.append(CharArrayWriter.java:215)


No comments:

Post a Comment