Java String constructors
Create a string from bytes or a character array when data arrives from another API.
A simple example
String constructors
- Start with UTF-8 bytes 65, 66
- Do this Construct text
- Result "AB"
class Main {
public static void main(String[] args) throws Exception {
System.out.println(new String(new byte[]{65, 66}, java.nio.charset.StandardCharsets.UTF_8));
}
}
AB
Syntax
public String()
JDK 21 constructors (15)
public String()
public String(String original)
public String(char[] value)
public String(char[] value, int offset, int count)
public String(int[] codePoints, int offset, int count)
@Deprecated public String(byte[] ascii, int hibyte, int offset, int count)
@Deprecated public String(byte[] ascii, int hibyte)
public String(byte[] bytes, int offset, int length, String charsetName) throws UnsupportedEncodingException
public String(byte[] bytes, int offset, int length, Charset charset)
public String(byte[] bytes, String charsetName) throws UnsupportedEncodingException
public String(byte[] bytes, Charset charset)
public String(byte[] bytes, int offset, int length)
public String(byte[] bytes)
public String(StringBuffer buffer)
public String(StringBuilder builder)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaDecode a parcel label
A scanner or import hands the application encoded data for a printed code. Reconstruct the intended text using the representation in the example and inspect the label that a person will actually read.
class Main {
public static void main(String[] args) throws Exception {
byte[] label = {80, 75, 45, 55};
System.out.println(new String(label, java.nio.charset.StandardCharsets.UTF_8));
}
}
PK-7
The four bytes encode the printed parcel identifier in UTF-8.
Copy a shelf code before reusing the buffer
A scanner reuses its input buffer for the next item. Save the current text before that buffer changes so the label or note already accepted by the application keeps its original contents.
class Main {
public static void main(String[] args) throws Exception {
char[] scan = {'A', '2', '1'};
String shelf = new String(scan);
scan[0] = 'B';
System.out.println(shelf);
}
}
A21
The saved string keeps the original code when the scanner reuses its array.
Count the bytes on a café tag
The word café ends in a precomposed accented character. Trace a UTF-8 round trip. How many bytes carry this label before it is decoded back to the original text?
What to watch for
Choose the charset explicitly for bytes. The historical high-byte constructors are deprecated.