class Point {
int x , y
Point ( int x , int y ) {
this . x = x
this . y = y
}
String toString () {
return "{$x $y}"
}
}
def p = new Point ( 1 , 2 )
// Groovy offers several ways to format strings. Here's how to print
// an instance of our Point class.
println "struct1: $p"
// To include field names, we can use the toString() method
println "struct2: ${p.toString()}"
// To print the type of a value, use the `class` property
println "type: ${p.class}"
// Formatting booleans is straightforward
println "bool: ${true}"
// There are many options for formatting integers
println "int: ${123}"
// This prints a binary representation
println "bin: ${Integer.toBinaryString(14)}"
// This prints the character corresponding to the given integer
println "char: ${(char)33}"
// For hex encoding
println "hex: ${Integer.toHexString(456)}"
// For basic decimal formatting of floats, use String.format()
println "float1: ${String.format('%.6f', 78.9)}"
// For scientific notation
println "float2: ${String.format('%.6e', 123400000.0)}"
println "float3: ${String.format('%.6E', 123400000.0)}"
// For basic string printing
println "str1: \"string\""
// To double-quote strings
println "str2: ${'" string "'.inspect()}"
// To print a hexadecimal representation of a string
println "str3: ${'hex this'.bytes.encodeHex()}"
// To print a representation of a reference, use `System.identityHashCode()`
println "pointer: ${System.identityHashCode(p)}"
// When formatting numbers, you can control the width and precision
println "width1: |${String.format('%6d', 12)}|${String.format('%6d', 345)}|"
// For floats, you can restrict the decimal precision
println "width2: |${String.format('%6.2f', 1.2)}|${String.format('%6.2f', 3.45)}|"
// To left-justify, use the `-` flag
println "width3: |${String.format('%-6.2f', 1.2)}|${String.format('%-6.2f', 3.45)}|"
// You can also control width when formatting strings
println "width4: |${String.format('%6s', 'foo')}|${String.format('%6s', 'b')}|"
// To left-justify strings, use the `-` flag
println "width5: |${String.format('%-6s', 'foo')}|${String.format('%-6s', 'b')}|"
// GString (Groovy's interpolated string) can be used to format and return a string
def s = "sprintf: a ${'string'}"
println s
// To print to standard error
System . err . println "io: an error"