Charset encode() in Java

encode(): This method is available in java.nio.charset.Charset class of Java.

Syntax:

ByteBuffer java.nio.charset.Charset.encode(CharBuffer cb)

This method takes one argument of type CharBuffer as its parameter. This method is a convenient method that encodes Unicode characters into bytes in this charset.

Parameters: One parameter is required for this method.

cb: The char buffer to be encoded.

Returns: A byte buffer containing the encoded characters.

For Example:

Charset cs = Charset.forName("UTF-8")

char array[] = { '1', '2', '3', '4' }

CharBuffer cb = CharBuffer.wrap(array)

cs.encode(cb) = > It returns [49, 50, 51, 52].

Approach

Java

import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;

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

      Charset cs = Charset.forName("UTF-8");

      char array[] = { '1''2''3''4' };
      CharBuffer cb = CharBuffer.wrap(array);
      System.out.println(Arrays.toString(cs.encode(cb).array()));
    }
}

Output:

[49, 50, 51, 52]

No comments:

Post a Comment