Groovy
println 'Welcome to Online IDE!'
println 'Start coding in Groovy...'

Press Run or Ctrl ↵ to execute main.groovy.
Type program input here while it runs.

Groovy

Online Groovy

main.groovy runs as a script with Groovy 6.0 on Java 17. Code at the top level runs from top to bottom, with no class or main method needed, and every JDK class is available.

Try it above

How Groovy runs here

Versions
Groovy 6.0 on Java 17
Run
groovy main.groovy
Limits per run
512 MB memory, 15 s of CPU time on half a core, 2 MB of output
Time
Up to 10 minutes a run (30 on a paid plan); waits 2 minutes for input (5 on a paid plan)
Sandbox
Each run gets its own Linux sandbox with no network access. Text files your program writes next to your code open as new tabs.

A Groovy script that reads input

This main.groovy reads people into maps with collect, then finds the oldest and sorts by name:

Groovy
def reader = System.in.newReader()
print 'How many people? '
int n = reader.readLine() as int
def people = (1..n).collect {
    print "Name and age of person $it: "
    def (name, age) = reader.readLine().tokenize()
    [name: name, age: age as int]
}
println "Oldest: ${people.max { it.age }.name}"
println "Average age: ${people.sum { it.age } / n}"
people.sort { it.name }.each { println "${it.name.padRight(6)} ${it.age}" }
Terminal
$ groovy main.groovy
How many people? 3
Name and age of person 1: Asha 34
Name and age of person 2: Ben 29
Name and age of person 3: Chen 41
Oldest: Chen
Average age: 34.6666666667
Asha   34
Ben    29
Chen   41

The average is a BigDecimal: dividing integers with / in Groovy gives a decimal, not a whole number. Use intdiv for integer division.

Reading input in Groovy

  • System.in.newReader() gives a reader; call readLine() on the same reader each time.
  • Convert with as int or toInteger(); tokenize() splits a line on spaces.
  • Arguments from Run settings are in args.

Errors you’ll see

  • “groovy.lang.MissingPropertyException: No such property: totl for class: main” A variable that isn’t defined, often a typo. Groovy finds these when the line runs, not before.
  • “java.lang.NumberFormatException: For input string: "abc"” as int got text that isn’t a number. The trace shows main.groovy and the line.

Questions

Which Groovy version is this?

Groovy 6.0 on Java 17.

Can I use @Grab?

No. There’s no network during a run, so dependencies can’t be downloaded. The Groovy runtime and the JDK are available.

Does Java code run as Groovy?

Most Java code is valid Groovy, so a class with a main method works too. The Java playground runs real javac if you need it.