Library contents

Groovy String constructors

Create a string from bytes or a character array when data arrives from another API.

A simple example

String constructors

  1. Start with UTF-8 bytes 65, 66
  2. Do this Construct text
  3. Result "AB"
The constructor interprets those bytes with the specified encoding.

Syntax

Groovy 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.groovy

Decode 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.

From the programbyte[] bytes = [65, 50] as byte[]
ResultA2
Lesson.groovy
byte[] bytes = [65, 50] as byte[]
println new String(bytes, java.nio.charset.StandardCharsets.UTF_8)
Output
A2

Two ASCII bytes carry the room identifier.

Advertisements

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.

From the programchar[] scan = "BX".toCharArray()
ResultBX
Lesson.groovy
char[] scan = "BX".toCharArray()
def saved = new String(scan)
scan[0] = (char) 67
println saved
Output
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?

Givencafé · UTF-8
Worked result5

What to watch for

Choose the charset explicitly for bytes. The historical high-byte constructors are deprecated.

Documentation for String constructors