Charset encode() String in Java

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

Syntax:

ByteBuffer java.nio.charset.Charset.encode(String str)

This method takes one argument of type String as its parameter. This method is a Convenience method that encodes a string into bytes in this charset.

Parameters: One parameter is required for this method.

str: The string to be encoded.

Returns: A byte buffer containing the encoded characters.

For Example:

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

String str = "Hello"

cs.encode(str) = > It returns [72, 101, 108, 108, 111].

Approach

Java

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

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

     Charset cs = Charset.forName("UTF-8");
     String str = "Hello";
     System.out.println(Arrays.toString(cs.encode(str).array()));
    }
}

Output:

[72, 101, 108, 108, 111]

No comments:

Post a Comment