Java Java7

StandardCharsets Class (NIO)

StandardCharsets Class (NIO)

StandardCharsets Class (NIO)

StandardCharsets is a utility class introduced in Java 7 that provides constants for standard character sets like UTF-8, ASCII, and ISO-8859-1.

How it Works

Before Java 7, developers used strings like "UTF-8", which required handling UnsupportedEncodingException. StandardCharsets constants are of type Charset and do not require exception handling.

Java Example

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

public class CharsetExample {
    public static void main(String[] args) {
        byte[] bytes = "Hello".getBytes(StandardCharsets.UTF_8);
        System.out.println(Arrays.toString(bytes));
    }
}

Output

[72, 101, 108, 108, 111]

Key Points

  • Type-safe charset constants
  • Avoids magic strings for encoding
  • No need for UnsupportedEncodingException
  • Includes UTF_8, UTF_16, US_ASCII, etc.
Topics: Java Java7
← Newer Post Older Post →