Groovy String.copyValueOf
Create a string from a character array or a portion of one.
A simple example
String.copyValueOf
- Start with Characters a, b, c
- Do this Copy just the middle character
- Result b
Syntax
public static String copyValueOf(char[] data, int offset, int count)
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovySave digits from a reader
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[] code = "PK12".toCharArray()
println String.copyValueOf(code, 2, 2)
12
The final argument is a count of units.
Copy a complete label
A label reader supplies an entire character array to the application. Save the whole array as display text rather than accidentally selecting only a slice of the scanned label.
char[] tag = "Tea".toCharArray()
println String.copyValueOf(tag)
Tea
The result contains all units in the array.
Read a parcel sorting code
The depot scans a parcel marked NC-17. Copy the last two characters into a clean buffer for a numeric display. What does the copied field contain?
What to watch for
The last range argument is a count. Check that offset plus count fits the array.