Conversion to from bytes

suggest change

To encode a string into a byte array, you can simply use the String#getBytes() method, with one of the standard character sets available on any Java runtime:

byte[] bytes = "test".getBytes(StandardCharsets.UTF_8);

and to decode:

String testString = new String(bytes, StandardCharsets.UTF_8);

you can further simplify the call by using a static import:

import static java.nio.charset.StandardCharsets.UTF_8;
...
byte[] bytes = "test".getBytes(UTF_8);

For less common character sets you can indicate the character set with a string:

byte[] bytes = "test".getBytes("UTF-8");

and the reverse:

String testString = new String (bytes, "UTF-8");

this does however mean that you have to handle the checked UnsupportedCharsetException.


The following call will use the default character set. The default character set is platform specific and generally differs between Windows, Mac and Linux platforms.

byte[] bytes = "test".getBytes();

and the reverse:

String testString = new String(bytes);

Note that invalid characters and bytes may be replaced or skipped by these methods. For more control - for instance for validating input - you’re encouraged to use the CharsetEncoder and CharsetDecoder classes.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Strings:
* Conversion to from bytes

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap