C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: Variants of the String constructor exist. One constructs based on a range of bytes (specified by a start and offset).
Charset: A Charset is an optional argument. If your String contains a specific encoding of chars, please use a Charset.
Java program that uses String constructor
public class Program {
public static void main(String[] args) {
// These are the ASCII values for lowercase A, B and C.
byte[] array = { 97, 98, 99 };
String result = new String(array);
System.out.println(result);
}
}
Output
abc
No argument: With no argument, we use the system's default charset to convert the String to a byte array.
String argument: Here a Charset is used based on the name provided. We test this with US-ASCII which supports 7-bit chars.
Arrays.toString: The example uses Array.toString to "pretty-print" the arrays to the Console output.
Java program that uses getBytes
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class Program {
public static void main(String[] args) throws UnsupportedEncodingException {
// The string we want to convert.
String letters = "abc";
System.out.println(letters);
// Use default charset.
byte[] valuesDefault = letters.getBytes();
// ... Use Arrays.toString to display our byte array.
System.out.println(Arrays.toString(valuesDefault));
// Specify US-ASCII char set directly.
byte[] valuesAscii = letters.getBytes("US-ASCII");
System.out.println(Arrays.toString(valuesAscii));
}
}
Output
abc
[97, 98, 99]
[97, 98, 99]