CharArrayWriter write(String, int, int) in Java

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

Syntax:

void java.io.CharArrayWriter.write(String str, int off, int len)

This method takes three arguments. This method writes a portion of a string to the buffer.

Parameters: Three parameters are required for this method.

str: String to be written from.

off: Offset from which to start reading characters.

len: Number of characters to be written.

Throws:

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

Approach 1: When no exception

Java

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

public class CharArrayWriterwrite3 {
    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 = 3;
        String str = "HELLO";
        charArrayWriter.write(str, off, len);

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

Output:

abcdELL


Approach 2: IndexOutOfBoundsException 

Java

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

public class CharArrayWriterwrite3 {
    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 = 3;
        String str = "HELLO";
        charArrayWriter.write(str, off, len);

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

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin -1, end 2, length 5 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3734) at java.base/java.lang.String.getChars(String.java:873) at java.base/java.io.CharArrayWriter.write(CharArrayWriter.java:133)


No comments:

Post a Comment