CharArrayWriter write(char[], int, int) in Java

write(char[], int, int): This method is available in the java.io.CharArrayWriter class of Java.

Syntax:

void java.io.CharArrayWriter.write(char[] c, int off, int len)

This method takes three arguments. This method writes characters to the buffer.

Parameters: Three parameters are required for this method.

c: the data to be written.

off: the start offset in the data.

len: the number of chars that are written.

Returns: NA

Throws:

IndexOutOfBoundsException - If off is negative, or len is negative, or off + len is negative or greater than the length of the given array

Approach 1: When no exception

Java

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

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

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

        int off = 1, len = 2;
        charArrayWriter.write(cbuf, off, len);

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

Output:

abcdbc


Approach 2: IndexOutOfBoundsException

Java

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

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

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

        int off = -1, len = 2;
        charArrayWriter.write(cbuf, off, len);

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

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.io.CharArrayWriter.write(CharArrayWriter.java:102)


No comments:

Post a Comment