Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

Groovy vs Java

Compare Groovy and Java side by side: boilerplate, default imports, public by default, properties, equality, closures, GStrings and the few places Java code behaves differently.

If you already know Java, Groovy will feel familiar within an hour. The surprises are few but important. This lesson lists them in one place: what Groovy lets you leave out, what it does differently, and the traps for Java programmers. Keep it as a reference as you work through the next chapters.

If you are new to both languages, do not worry about memorising everything. Treat this as a map: each difference is taught in depth in a later lesson.

The same program in both languages

A Java program that greets people:

Java Java: the verbose version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The Groovy version needs no class, no main, no import, no types:

GROOVY
['Ada', 'Linus', 'Grace'].each { println "Hello, $it!" }

Both print three greeting lines. Groovy gets there through a handful of defaults, described next.

What you may leave out

Java requires Groovy
; at the end of statements Optional
Class and main for a program Optional (scripts)
import java.util.*, java.io.*, java.net.*, java.lang.* and a few more Imported automatically (also groovy.lang.*, groovy.util.*, java.math.BigDecimal, java.math.BigInteger)
public Everything is public by default
Parentheses on method calls Often optional: println 'hi'
return at the end of a method Optional: the last expression is returned
Checked exceptions Not enforced; you may catch or ignore
Getters and setters Generated for properties
Type declarations Optional with def

Differences that change behavior

1. == means equals()

In Java == compares references for objects. In Groovy == calls equals() (or compareTo() for Comparable values), and the method is() checks identity:

GROOVY
def a = new String('x')
def b = new String('x')
assert a == b        // true: same content
assert !a.is(b)      // true: different objects

This removes one of Java's most frequent beginner bugs.

2. Strings come in several flavors

Single quotes make a plain Java String. Double quotes make a GString when they contain $ expressions:

GROOVY
def name = 'Ada'
println 'Hello, $name'     // prints: Hello, $name
println "Hello, $name"     // prints: Hello, Ada

See Strings and GStrings for the full story.

3. Numbers default to BigDecimal for decimals

The literal 1.1 is a BigDecimal, not a double. That makes money-like arithmetic exact: 0.1 + 0.2 gives 0.3. Use 1.1d for a double. See Numbers and Math.

4. Dynamic dispatch

Java chooses which overloaded method to call from the declared types at compile time. Groovy chooses from the runtime types:

Java Java stand-in: compile-time overload choice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In Groovy, who(x) with Object x = 'hello' calls the String overload. This is called multi-methods and is a core part of how Groovy works.

5. Properties and field access

Writing person.name in Groovy calls getName() when it exists. Inside the class, this.name reads the field directly. See Classes and Properties.

6. Truth

Groovy applies "Groovy truth" in conditions: empty strings, empty collections, zero and null are false:

GROOVY
if ([]) { println 'never' } else { println 'empty list is false' }

See Control Flow and Truth.

7. Safe navigation, Elvis and spread operators

Operators such as ?., ?: and *. remove null checks and loops. They are covered in Operators.

8. Closures versus lambdas

Groovy closures can read and modify local variables from the enclosing scope and have a configurable delegate. Java lambdas can only capture effectively final variables. See Closures.

Where Java code breaks in Groovy

Because Groovy is almost a superset of Java, some Java syntax is different:

  • Array initializers: int[] a = {1, 2, 3}; is not allowed (braces mean a closure). Write int[] a = [1, 2, 3] or new int[] {1, 2, 3} (the latter is supported in Groovy 3 and later).
  • Classic for(;;) loops work, but the Java 5 for (x : xs) colon form and for (x in xs) both work too.
  • Inner class creation and some generics checks behave slightly differently, and generics are not checked at run time.
  • Lambdas: Groovy 3+ supports Java lambda syntax x -> x + 1, but closure rules apply to what they capture.
  • Default visibility: members you do not mark are public, and fields without a modifier become properties.
  • Semicolon-less line breaks: a line ending with an operator continues; a line starting with an operator may not. Put the operator at the end of the first line.

A line that starts with + other after a complete statement is a new statement in Groovy: def total = a followed by a new line + b does not add. Place the + at the end of the previous line.

What Groovy shares with Java

It is just as important to remember what stays the same:

  • Same JVM, same garbage collector, same threads, same libraries.
  • Classes, interfaces, packages, generics (at compile time), annotations and enums.
  • try/catch/finally, switch, while, and the ternary operator.
  • The standard library: java.util, java.time, java.nio, and so on.

That is why Groovy is considered a gentle step for Java developers. You can port a Java class by renaming .java to .groovy and then deleting boilerplate step by step.

A Java-to-Groovy refactoring

Here is a small Java stand-in with the style Groovy removes: a bean with getters and a manual string.

Java Java: a bean with boilerplate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In Groovy the same idea is:

GROOVY
@groovy.transform.Canonical
class Person {
    String name
    int age
}

def p = new Person('Ada', 36)
println p
println "$p.name is $p.age"

@Canonical generates the constructor, toString, equals and hashCode; the properties generate getters. You will study this in AST Transformations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does == do on two objects in Groovy?

    Groovy's == means logical equality. Use a.is(b) to test whether two references point to the same object.
  2. 2. What is the type of the literal 3.14 in Groovy?

    Decimal literals are BigDecimal by default; add a suffix like d to get a double.
  3. 3. Which of these is NOT imported automatically in Groovy?

    Groovy imports java.lang, java.util, java.io, java.net, groovy.lang, groovy.util, BigDecimal and BigInteger by default. java.time needs an explicit import.
  4. 4. How does Groovy choose between overloaded methods?

    Groovy uses dynamic dispatch (multi-methods), so the runtime type of each argument decides.
  5. 5. Which line is an unsafe way to continue an expression onto the next line?

    A new line starting with an operator may be parsed as a separate statement. End the first line with the operator instead.

Summary

  • Groovy drops semicolons, boilerplate, public, getters/setters and (optionally) types.
  • == is equality, is() is identity; decimals are BigDecimal; double-quoted strings can interpolate.
  • Method dispatch uses runtime types.
  • A few Java syntaxes (array braces, line starting with an operator) need care.
  • Everything on the JVM remains available.

Next: Syntax Basics