Constants in Groovy

Our code example demonstrates the use of constants. Here’s the full source code.

// Declaring a constant value.
final String s = "constant"

void main() {
    println(s)
}

// A constant statement can appear anywhere a var statement can.
final int n = 500000000

// Constant expressions perform arithmetic with arbitrary precision.
final double d = 3e20 / n
println(d)

// A numeric constant has no type until it’s given one, such as by an explicit conversion.
println(d as long)

// A number can be given a type by using it in a context that requires one, such as a variable assignment or function call.
// For example, here Math.sin expects a double.

println(Math.sin(n))

main()

To run the program, save the code in a .groovy file and use groovy to execute it.

$ groovy constants.groovy
constant
6.0E11
600000000000
-0.28470407323754404

Now that we can run basic Groovy programs, let’s learn more about the language.