A named mapping between sequences of sixteen-bit Unicode code units and sequences of bytes. This class defines methods for creating decoders and encoders and for retrieving the various names associated with a charset. Instances of this class are immutable.

This class also defines static methods for testing whether a particular charset is supported, for locating charset instances by name, and for constructing a map that contains every charset for which support is available in the current Java virtual machine. Support for new charsets can be added via the service-provider interface defined in the java.nio.charset.spi.CharsetProvider class.

All of the methods defined in this class are safe for use by multiple concurrent threads.

Charset names

Charsets are named by strings composed of the following characters:

  • The uppercase letters 'A' through 'Z' ('\u0041' through '\u005a'),
  • The lowercase letters 'a' through 'z' ('\u0061' through '\u007a'),
  • The digits '0' through '9' ('\u0030' through '\u0039'),
  • The dash character '-' ('\u002d'HYPHEN-MINUS),
  • The period character '.' ('\u002e'FULL STOP),
  • The colon character ':' ('\u003a'COLON), and
  • The underscore character '_' ('\u005f'LOW LINE).
A charset name must begin with either a letter or a digit. The empty string is not a legal charset name. Charset names are not case-sensitive; that is, case is always ignored when comparing charset names. Charset names generally follow the conventions documented in
RFC 2278: IANA Charset Registration Procedures.

Every charset has a canonical name and may also have one or more aliases. The canonical name is returned by the name method of this class. Canonical names are, by convention, usually in upper case. The aliases of a charset are returned by the aliases method.

Some charsets have an historical name that is defined for compatibility with previous versions of the Java platform. A charset's historical name is either its canonical name or one of its aliases. The historical name is returned by the getEncoding() methods of the InputStreamReader and OutputStreamWriter classes.

If a charset listed in the IANA Charset Registry is supported by an implementation of the Java platform then its canonical name must be the name listed in the registry. Many charsets are given more than one name in the registry, in which case the registry identifies one of the names as MIME-preferred. If a charset has more than one registry name then its canonical name must be the MIME-preferred name and the other names in the registry must be valid aliases. If a supported charset is not listed in the IANA registry then its canonical name must begin with one of the strings "X-" or "x-".

The IANA charset registry does change over time, and so the canonical name and the aliases of a particular charset may also change over time. To ensure compatibility it is recommended that no alias ever be removed from a charset, and that if the canonical name of a charset is changed then its previous canonical name be made into an alias.

Standard charsets

Every implementation of the Java platform is required to support the following standard charsets. Consult the release documentation for your implementation to see if any other charsets are supported. The behavior of such optional charsets may differ between implementations.

Charset

Description

US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
ISO-8859-1   ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
UTF-8 Eight-bit UCS Transformation Format
UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order
UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order
UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark

The UTF-8 charset is specified by RFC 2279; the transformation format upon which it is based is specified in Amendment 2 of ISO 10646-1 and is also described in the Unicode Standard.

The UTF-16 charsets are specified by RFC 2781; the transformation formats upon which they are based are specified in Amendment 1 of ISO 10646-1 and are also described in the Unicode Standard.

The UTF-16 charsets use sixteen-bit quantities and are therefore sensitive to byte order. In these encodings the byte order of a stream may be indicated by an initial byte-order mark represented by the Unicode character '\uFEFF'. Byte-order marks are handled as follows:

In any case, when a byte-order mark is read at the beginning of a decoding operation it is omitted from the resulting sequence of characters. Byte order marks occuring after the first element of an input sequence are not omitted since the same code is used to represent ZERO-WIDTH NON-BREAKING SPACE.

Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets. The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system.

Terminology

The name of this class is taken from the terms used in RFC 2278. In that document a charset is defined as the combination of a coded character set and a character-encoding scheme.

A coded character set is a mapping between a set of abstract characters and a set of integers. US-ASCII, ISO 8859-1, JIS X 0201, and full Unicode, which is the same as ISO 10646-1, are examples of coded character sets.

A character-encoding scheme is a mapping between a coded character set and a set of octet (eight-bit byte) sequences. UTF-8, UCS-2, UTF-16, ISO 2022, and EUC are examples of character-encoding schemes. Encoding schemes are often associated with a particular coded character set; UTF-8, for example, is used only to encode Unicode. Some schemes, however, are associated with multiple character sets; EUC, for example, can be used to encode characters in a variety of Asian character sets.

When a coded character set is used exclusively with a single character-encoding scheme then the corresponding charset is usually named for the character set; otherwise a charset is usually named for the encoding scheme and, possibly, the locale of the character sets that it supports. Hence US-ASCII is the name of the charset for US-ASCII while EUC-JP is the name of the charset that encodes the JIS X 0201, JIS X 0208, and JIS X 0212 character sets.

The native character encoding of the Java programming language is UTF-16. A charset in the Java platform therefore defines a mapping between sequences of sixteen-bit UTF-16 code units and sequences of bytes.

@author
Mark Reinhold
@author
JSR-51 Expert Group
@version
1.47, 04/08/19
@since
1.4
Returns a set containing this charset's aliases.

Return
An immutable set of this charset's aliases
Constructs a sorted map from canonical charset names to charset objects.

The map returned by this method will have one entry for each charset for which support is available in the current Java virtual machine. If two or more supported charsets have the same canonical name then the resulting map will contain just one of them; which one it will contain is not specified.

The invocation of this method, and the subsequent use of the resulting map, may cause time-consuming disk or network I/O operations to occur. This method is provided for applications that need to enumerate all of the available charsets, for example to allow user charset selection. This method is not used by the forName method, which instead employs an efficient incremental lookup algorithm.

This method may return different results at different times if new charset providers are dynamically made available to the current Java virtual machine. In the absence of such changes, the charsets returned by this method are exactly those that can be retrieved via the forName method.

Return
An immutable, case-insensitive map from canonical charset names to charset objects
Tells whether or not this charset supports encoding.

Nearly all charsets support encoding. The primary exceptions are special-purpose auto-detect charsets whose decoders can determine which of several possible encoding schemes is in use by examining the input byte sequence. Such charsets do not support encoding because there is no way to determine which encoding should be used on output. Implementations of such charsets should override this method to return false.

Return
true if, and only if, this charset supports encoding
Compares this charset to another.

Charsets are ordered by their canonical names, without regard to case.

Parameters
that The charset to which this charset is to be compared
Return
A negative integer, zero, or a positive integer as this charset is less than, equal to, or greater than the specified charset
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive. The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

Finally, the implementer must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

Parameters
othe Object to be compared.
Return
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Throws
ClassCastExceptionif the specified object's type prevents it from being compared to this Object.
Tells whether or not this charset contains the given charset.

A charset C is said to contain a charset D if, and only if, every character representable in D is also representable in C. If this relationship holds then it is guaranteed that every string that can be encoded in D can also be encoded in C without performing any replacements.

That C contains D does not imply that each character representable in C by a particular byte sequence is represented in D by the same byte sequence, although sometimes this is the case.

Every charset contains itself.

This method computes an approximation of the containment relation: If it returns true then the given charset is known to be contained by this charset; if it returns false, however, then it is not necessarily the case that the given charset is not contained in this charset.

Return
true if, and only if, the given charset is contained in this charset
Convenience method that decodes bytes in this charset into Unicode characters.

An invocation of this method upon a charset cs returns the same result as the expression

     cs.newDecoder()
       .onMalformedInput(CodingErrorAction.REPLACE)
       .onUnmappableCharacter(CodingErrorAction.REPLACE)
       .decode(bb); 
except that it is potentially more efficient because it can cache decoders between successive invocations.

This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement byte array. In order to detect such sequences, use the method directly.

Parameters
bbThe byte buffer to be decoded
Return
A char buffer containing the decoded characters
Returns the default charset of this Java virtual machine.

The default charset is determined during virtual-machine startup and typically depends upon the locale and charset of the underlying operating system.

Return
A charset object for the default charset
@since
1.5
Returns this charset's human-readable name for the default locale.

The default implementation of this method simply returns this charset's canonical name. Concrete subclasses of this class may override this method in order to provide a localized display name.

Return
The display name of this charset in the default locale
Returns this charset's human-readable name for the given locale.

The default implementation of this method simply returns this charset's canonical name. Concrete subclasses of this class may override this method in order to provide a localized display name.

Parameters
locale The locale for which the display name is to be retrieved
Return
The display name of this charset in the given locale
Convenience method that encodes Unicode characters into bytes in this charset.

An invocation of this method upon a charset cs returns the same result as the expression

     cs.newEncoder()
       .onMalformedInput(CodingErrorAction.REPLACE)
       .onUnmappableCharacter(CodingErrorAction.REPLACE)
       .encode(bb); 
except that it is potentially more efficient because it can cache encoders between successive invocations.

This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement string. In order to detect such sequences, use the method directly.

Parameters
cbThe char buffer to be encoded
Return
A byte buffer containing the encoded characters
Convenience method that encodes a string into bytes in this charset.

An invocation of this method upon a charset cs returns the same result as the expression

     cs.encode(CharBuffer.wrap(s)); 
Parameters
strThe string to be encoded
Return
A byte buffer containing the encoded characters
Tells whether or not this object is equal to another.

Two charsets are equal if, and only if, they have the same canonical names. A charset is never equal to any other type of object.

Return
true if, and only if, this charset is equal to the given object
Returns a charset object for the named charset.

Parameters
charsetName The name of the requested charset; may be either a canonical name or an alias
Return
A charset object for the named charset
Throws
IllegalCharsetNameException If the given charset name is illegal
UnsupportedCharsetException If no support for the named charset is available in this instance of the Java virtual machine
Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Return
The java.lang.Class object that represents the runtime class of the object. The result is of type {@code Class} where X is the erasure of the static type of the expression on which getClass is called.
Computes a hashcode for this charset.

Return
An integer hashcode
Tells whether or not this charset is registered in the IANA Charset Registry.

Return
true if, and only if, this charset is known by its implementor to be registered with the IANA
Tells whether the named charset is supported.

Parameters
charsetName The name of the requested charset; may be either a canonical name or an alias
Return
true if, and only if, support for the named charset is available in the current Java virtual machine
Throws
IllegalCharsetNameException If the given charset name is illegal
Returns this charset's canonical name.

Return
The canonical name of this charset
Constructs a new decoder for this charset.

Return
A new decoder for this charset
Constructs a new encoder for this charset.

Return
A new encoder for this charset
Throws
UnsupportedOperationException If this charset does not support encoding
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Returns a string describing this charset.

Return
A string describing this charset
Causes current thread to wait until another thread invokes the method or the method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until either another thread invokes the method or the method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor.

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout);
         ... // Perform action appropriate to condition
     }
 
(For more information on this topic, see Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 2000), or Item 50 in Joshua Bloch's "Effective Java Programming Language Guide" (Addison-Wesley, 2001).

If the current thread is interrupted by another thread while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Parameters
timeoutthe maximum time to wait in milliseconds.
Throws
IllegalArgumentExceptionif the value of timeout is negative.
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until another thread invokes the method or the method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by:

 1000000*timeout+nanos

In all other respects, this method does the same thing as the method of one argument. In particular, wait(0, 0) means the same thing as wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

  • Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
  • The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout, nanos);
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Parameters
timeoutthe maximum time to wait in milliseconds.
nanosadditional time, in nanoseconds range 0-999999.
Throws
IllegalArgumentExceptionif the value of timeout is negative or the value of nanos is not in the range 0-999999.
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.