Groovy 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"
Syntax
public String()
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyDecode a classroom code
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.
byte[] bytes = [65, 50] as byte[]
println new String(bytes, java.nio.charset.StandardCharsets.UTF_8)
A2
Two ASCII bytes carry the room identifier.
Capture a scanner 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.
char[] scan = "BX".toCharArray()
def saved = new String(scan)
scan[0] = (char) 67
println saved
BX
Reusing the array leaves the saved text intact.
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.