InterviewPitch
Groovy interview questions

Groovy Interview Questions with Answers

Most Asked Groovy Interview Questions for Software Engineer Roles

100+ QuestionsDetailed AnswersCode ExamplesUpdated for 2026

Introduction

Groovy is a dynamic language for the JVM that brings the best of scripting and object‑oriented programming with seamless Java integration. This page collects the most frequently asked Groovy interview questions – from basic syntax and closures to metaprogramming, AST transformations, and build automation – essential for any developer working with Grails, Gradle, or enterprise Java environments.

Why Groovy?

  • Dynamic and static typing – choose what fits
  • Closures and functional programming features
  • Metaprogramming and runtime extensions
  • Seamless interoperability with Java
  • Popular in build tools (Gradle) and frameworks (Grails)
  • Concise syntax that boosts productivity

Most Asked Groovy Interview Questions

Beginner
1. What is Groovy and what are its key features?

Groovy is an object-oriented programming language for the Java platform. It integrates seamlessly with Java and adds dynamic features, closures, and a concise syntax.

  • Dynamic and static typing: Optional types
  • Closures: First-class functions
  • Metaprogramming: Runtime modification
  • Builders: Domain-specific languages
  • Seamless Java integration
groovy
// Hello World in Groovy
println "Hello, World!"
Beginner
2. What are Data Types in Groovy?

Groovy supports Java's primitive and reference types plus dynamic typing with def. It also adds big decimals, ranges, and GStrings.

  • def: Dynamic type
  • Primitives: int, float, boolean
  • Objects: String, List, Map
  • BigDecimal: For precise arithmetic
  • Range: 1..10
groovy
// Data Types in Groovy
def age = 25
def salary = 50000.50
def pi = 3.14159265358979
def grade = 'A' as char
def isActive = true
def name = "Alice"
def price = 99.99

println "Age: $age"
println "Salary: $salary"
println "Pi: $pi"
println "Grade: $grade"
println "Active: $isActive"
println "Name: $name"
println "Price: $price"
Beginner
3. What are Variables and Constants in Groovy?

Variables are declared with def for dynamic typing, or explicit types. Constants use final.

  • def: Dynamic variable
  • Type: String name
  • final: Constant
  • Multiple assignment: (x, y) = [1, 2]
  • Scope: script, class, method
groovy
// Variables and Constants in Groovy
def x = 10
final double PI = 3.14159
def val = 3.14
def str = "Hello"
def counter = 0

println "x = $x"
println "PI = $PI"
println "val = $val"
println "str = $str"
println "counter = $counter"
Beginner
4. What are Lists and Ranges in Groovy?

Lists are ordered collections. Ranges represent a sequence of values.

  • List: def list = [1, 2, 3]
  • Range: 1..10
  • Operations: <<, plus, minus
  • Negative indexing: list[-1]
  • Spread: *list
groovy
// Lists and Ranges in Groovy
def list = [1, 2, 3, 4, 5]
println list[0]
println list[2]

def range = 1..10
println range.toList()

// List operations
list << 6
list += [7, 8]
println list

// 2D list
def matrix = [[1,2,3], [4,5,6], [7,8,9]]
println matrix[1][1]
Beginner
5. What are Maps in Groovy?

Maps are key-value stores. Keys can be strings or any object.

  • Definition: [key: value]
  • Access: map.key or map['key']
  • Iteration: each
  • Remove: remove
  • Default value: withDefault
groovy
// Maps in Groovy
def scores = [
    Alice: 95,
    Bob: 87,
    Carol: 92
]

println "Alice: ${scores.Alice}"
println "Bob: ${scores['Bob']}"

scores.Dave = 88

if (scores.containsKey('Eve')) {
    println "Eve: ${scores.Eve}"
} else {
    println "Eve not found"
}

scores.each { key, value ->
    println "$key: $value"
}

scores.remove('Bob')
println scores
Beginner
6. What are Closures in Groovy?

Closures are anonymous blocks of code that can be assigned, passed, and executed.

  • Syntax: { x -> x * x }
  • Implicit parameter: it
  • Currying: curry()
  • Delegation: delegate
  • Collection methods: collect, findAll
groovy
// Closures in Groovy
def square = { x -> x * x }
println square(5)

def multiply = { x, y -> x * y }
println multiply(3, 4)

def applyToEach = { list, closure ->
    list.collect(closure)
}
def result = applyToEach([1,2,3,4], square)
println result

// Currying
def add = { a, b -> a + b }
def addFive = add.curry(5)
println addFive(10)
Beginner
7. What are Classes and Objects in Groovy?

Classes in Groovy are like Java classes but with a more concise syntax and automatic getters/setters.

  • Class: class Person { String name }
  • Constructor: Named arguments
  • Methods: As usual
  • Properties: Access via dot
  • GroovyBeans: Implicit properties
groovy
// Classes and Objects in Groovy
class Person {
    String name
    int age
    String email
}

def p1 = new Person(name: "Alice", age: 25, email: "alice@email.com")
println p1.name
println p1.age

class Rectangle {
    double width
    double height
    
    double area() { width * height }
    double perimeter() { 2 * (width + height) }
}

def rect = new Rectangle(width: 4.0, height: 6.0)
println "Area: ${rect.area()}"
println "Perimeter: ${rect.perimeter()}"
Intermediate
8. What are Traits in Groovy?

Traits are reusable units of behavior, like interfaces with default implementations.

  • Declaration: trait Logger { void log(String) }
  • Implementation: class MyClass implements Logger
  • Multiple traits: Can implement multiple
  • State: Can have fields
  • Composition: Compose behaviors
groovy
// Traits in Groovy
trait Logger {
    void log(String msg) {
        println "[LOG] $msg"
    }
}

class UserService implements Logger {
    void createUser(String name) {
        log "Creating user: $name"
        println "User created: $name"
    }
}

def service = new UserService()
service.createUser("Alice")
Intermediate
9. How does Inheritance work in Groovy?

Inheritance is similar to Java: single inheritance with extends.

  • extends: Inherit from superclass
  • @Override: Optional annotation
  • super: Call superclass methods
  • Abstract classes: abstract
  • Interfaces: implements
groovy
// Inheritance in Groovy
class Animal {
    String name
    void speak() { println "Animal speaks" }
}

class Dog extends Animal {
    @Override
    void speak() { println "Woof!" }
}

class Cat extends Animal {
    @Override
    void speak() { println "Meow!" }
}

def animals = [new Dog(name: "Rex"), new Cat(name: "Whiskers")]
animals.each { it.speak() }
Intermediate
10. What are Abstract Classes and Interfaces in Groovy?

Abstract classes and interfaces define contracts and partial implementations.

  • Abstract class: abstract class
  • Interface: interface
  • Multiple interfaces: implements A, B
  • Abstract methods: No body
  • Default implementations: Traits
groovy
// Abstract Classes and Interfaces
interface Flyable {
    void fly()
}

abstract class Vehicle {
    abstract void start()
}

class Car extends Vehicle implements Flyable {
    @Override
    void start() { println "Car engine starts" }
    @Override
    void fly() { println "Car cannot fly" }
}

def car = new Car()
car.start()
car.fly()
Beginner
11. What are Strings and GStrings in Groovy?

Groovy has Java strings plus GStrings for interpolation.

  • String: 'Hello'
  • GString: "Hello $name"
  • Triple quotes: Multi-line
  • Slashy strings: /regex/
  • Methods: reverse, padLeft
groovy
// String and GString
def name = "Alice"
def greeting = "Hello, $name"
println greeting

// Triple-quoted strings
def multiline = """This is
a multi-line
string"""
println multiline

// Slashy string (regex friendly)
def regex = /\d+/
println regex

// String methods
def str = "Groovy"
println str.toUpperCase()
println str.reverse()
println str.padLeft(10, '*')
Intermediate
12. What are the Elvis, Safe Navigation, and Spread Operators?

These operators simplify null checks and collection manipulations.

  • Elvis: ?: (if null, use default)
  • Safe navigation: ?.
  • Spread: *. (spread-dot)
  • Spread list: [*list]
  • Method spread: *.method()
groovy
// Operators: Elvis, Safe Navigation, Spread
def user = null
def name = user?.name ?: "Guest"
println name

def list = [1, 2, 3]
def sum = list*.toInteger().sum()
println sum

// Spread operator
def nums = [1,2,3,4]
def newList = [0, *nums, 5]
println newList
Intermediate
13. How do you use Regular Expressions in Groovy?

Regex is supported via slashy strings and the =~ and ==~ operators.

  • Pattern: ~//
  • Find: =~
  • Match: ==~
  • Replace: replaceAll
  • Matcher: matcher.group
groovy
// Regular Expressions
def text = "The quick brown fox"
def pattern = ~/\b\w{3}\b/
def matches = (text =~ pattern).collect()
println matches

// Find and replace
def replaced = text.replaceAll(/quick/, "slow")
println replaced

// Matcher
def matcher = (text =~ /(\w+)/)
while (matcher.find()) {
    println matcher.group(1)
}
Intermediate
14. How does Exception Handling work in Groovy?

Groovy uses Java-style try-catch-finally but can also use try as an expression.

  • try-catch: As in Java
  • finally: Cleanup
  • Multiple catch: Catch specific types
  • Throw: throw new Exception()
  • Optional throws: Not required
groovy
// Exception Handling
try {
    def result = 10 / 0
} catch (ArithmeticException e) {
    println "Division by zero: ${e.message}"
} finally {
    println "Finally block"
}

// Custom exception
class ValidationException extends Exception {
    ValidationException(String msg) { super(msg) }
}

try {
    throw new ValidationException("Invalid data")
} catch (ValidationException e) {
    println e.message
}
Intermediate
15. How do you perform File I/O in Groovy?

Groovy adds convenience methods to File and Reader/Writer.

  • read/write: withReader, withWriter
  • Text property: file.text
  • Each line: eachLine
  • Binary: bytes property
  • Delete: delete()
groovy
// File I/O
def file = new File("example.txt")

// Write
file.withWriter { writer ->
    writer.writeLine "Hello, World!"
}

// Read
file.withReader { reader ->
    reader.eachLine { line ->
        println "Read: $line"
    }
}

// Using text property
def content = file.text
println content

// Delete
file.delete()
Intermediate
16. How do you work with JSON in Groovy?

Groovy provides JsonOutput and JsonSlurper for JSON handling.

  • Serialize: JsonOutput.toJson()
  • Pretty: JsonOutput.prettyPrint()
  • Parse: JsonSlurper().parseText()
  • Builder: JsonBuilder
  • Streaming: JsonSlurper handles large data
groovy
// JSON in Groovy
import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def data = [
    name: "Alice",
    age: 25,
    email: "alice@email.com"
]

def json = JsonOutput.toJson(data)
println json

def pretty = JsonOutput.prettyPrint(json)
println pretty

// Parse JSON
def slurper = new JsonSlurper()
def parsed = slurper.parseText(json)
println parsed.name
Intermediate
17. How do you handle XML in Groovy?

Groovy offers XmlSlurper and XmlParser for reading, and MarkupBuilder for writing.

  • Parse: new XmlSlurper().parseText(xml)
  • Access: GPath expressions
  • Build: MarkupBuilder
  • Namespaces: Support
  • Streaming: XmlSlurper is efficient
groovy
// XML with Groovy
import groovy.xml.MarkupBuilder
import groovy.xml.XmlSlurper

def writer = new StringWriter()
def builder = new MarkupBuilder(writer)

builder.person(id: 1) {
    name "Alice"
    age 25
    email "alice@email.com"
}

def xml = writer.toString()
println xml

// Parse XML
def root = new XmlSlurper().parseText(xml)
println root.name.text()
println root.@id
Intermediate
18. What are Builders in Groovy?

Builders are DSLs for constructing complex structures (XML, JSON, UI).

  • MarkupBuilder: XML/HTML
  • JsonBuilder: JSON
  • SwingBuilder: UI
  • AntBuilder: Ant tasks
  • ObjectGraphBuilder: Object graphs
groovy
// Builders in Groovy (MarkupBuilder, JsonOutput)
import groovy.json.JsonBuilder
import groovy.xml.MarkupBuilder

// JSON builder
def jsonBuilder = new JsonBuilder()
jsonBuilder {
    person {
        name "Bob"
        age 30
        email "bob@email.com"
    }
}
println jsonBuilder.toPrettyString()

// MarkupBuilder (XML)
def sw = new StringWriter()
def xmlBuilder = new MarkupBuilder(sw)
xmlBuilder.books {
    book(id: 1) {
        title "Groovy in Action"
        author "Dierk König"
    }
}
println sw.toString()
Advanced
19. How do you use Groovy SQL?

groovy.sql.Sql simplifies JDBC interactions with closures and data sets.

  • Connection: Sql.newInstance()
  • Query: rows(), eachRow()
  • Execute: execute()
  • Transaction: withTransaction()
  • Batch: withBatch()
groovy
// Groovy SQL (simplified)
import groovy.sql.Sql

def url = "jdbc:h2:mem:test"
def sql = Sql.newInstance(url, "org.h2.Driver")

sql.execute "CREATE TABLE users (id INT, name VARCHAR)"
sql.execute "INSERT INTO users VALUES (1, 'Alice')"

def rows = sql.rows("SELECT * FROM users")
rows.each { println "$it.id: $it.name" }

// Using withTransaction
sql.withTransaction {
    sql.execute "INSERT INTO users VALUES (2, 'Bob')"
}

sql.close()
Advanced
20. How do you make HTTP requests in Groovy?

Use HttpURLConnection or third-party libraries. Groovy simplifies with with and closures.

  • GET: new URL(url).text
  • POST: Set request method and send payload
  • Headers: setRequestProperty
  • JSON: Send/receive JSON
  • Authentication: Basic auth with headers
groovy
// HTTP Client with Groovy (using HttpURLConnection)
def url = new URL("https://jsonplaceholder.typicode.com/posts/1")
def conn = url.openConnection()
conn.requestMethod = "GET"

if (conn.responseCode == 200) {
    def content = conn.content.text
    println content
} else {
    println "Error: ${conn.responseCode}"
}

// POST request
def postUrl = new URL("https://jsonplaceholder.typicode.com/posts")
def postConn = postUrl.openConnection()
postConn.requestMethod = "POST"
postConn.doOutput = true
postConn.setRequestProperty("Content-Type", "application/json")

def payload = '{"title":"Groovy","body":"Hello","userId":1}'
postConn.outputStream.withWriter { writer ->
    writer.write(payload)
}

if (postConn.responseCode == 201) {
    def response = postConn.content.text
    println response
}
Advanced
21. What is Metaprogramming with ExpandoMetaClass?

ExpandoMetaClass allows adding methods and properties at runtime.

  • Add method: String.metaClass.reverseWords = { ... }
  • Add property: Integer.metaClass.doubleValue
  • Override: Override existing methods
  • Constructor: metaClass.constructor = { ... }
  • Static methods: metaClass.'static'
groovy
// Metaprogramming with ExpandoMetaClass
String.metaClass.reverseWords = { ->
    delegate.split(' ').reverse().join(' ')
}

def msg = "Hello World"
println msg.reverseWords()

// Add property
Integer.metaClass.doubleValue = { -> delegate * 2 }
println 5.doubleValue()
Advanced
22. What are methodMissing and propertyMissing?

These are dynamic dispatch methods that handle calls to missing methods/properties.

  • methodMissing: Called when an undefined method is invoked
  • propertyMissing: Called for undefined properties
  • Return: Can return a value or throw exception
  • Dynamic behavior: Implement flexible APIs
  • Example: Building DSLs
groovy
// methodMissing and propertyMissing
class Dynamic {
    def propertyMissing(String name) { "Property $name not found" }
    def methodMissing(String name, args) { "Method $name called with $args" }
}

def d = new Dynamic()
println d.someProp
println d.someMethod(1,2,3)
Intermediate
23. What are Groovy JDK enhancements?

Groovy adds many methods to Java classes (e.g., List.sum(), String.truncate()).

  • List: sum, average, max
  • String: center, truncate, reverse
  • Map: subMap, each
  • Number: times, upto
  • File: eachLine, withReader
groovy
// Groovy JDK enhancements
def list = [1, 2, 3, 4]
println list.sum()
println list.average()
println list.max()
println list.min()

def text = "Groovy"
println text.center(10)
println text.truncate(3)

def map = [a:1, b:2]
println map.subMap(['a'])
Intermediate
24. How do Ranges and Switch work together?

Ranges can be used in switch statements for flexible condition matching.

  • Range: 1..10
  • Switch: switch(age) { case 0..17: ... }
  • Case: Values can be ranges, lists, regex
  • Fallthrough: Use break
  • Default: default case
groovy
// Ranges and Switch
def range = 1..10
range.each { println it }

// Switch with ranges
def age = 25
switch (age) {
    case 0..17: println "Minor"; break
    case 18..64: println "Adult"; break
    default: println "Senior"
}
Beginner
25. What is Groovy Truth?

Groovy evaluates any object to a boolean in conditions: collections, strings, numbers, etc.

  • null: false
  • Non-null: true
  • Empty list/map: false
  • Empty string: false
  • Zero number: false
groovy
// Groovy Truth (coercion to boolean)
def list = []
if (list) println "Non-empty" else println "Empty"

def map = [:]
if (map) println "Non-empty" else println "Empty"

def num = 0
if (num) println "Non-zero" else println "Zero"

def str = ""
if (str) println "Non-empty" else println "Empty"
Beginner
26. How does String Interpolation work?

GStrings (double-quoted strings) evaluate embedded expressions.

  • {expression}: Evaluated at runtime
  • Single quotes: No interpolation
  • Triple quotes: Multi-line, can be GString
  • Escape: \$ to escape
  • Lazy evaluation: Re-evaluated when used
groovy
// Groovy Interpolation with Strings
def x = 10
def y = 20
def sum = "Sum: ${x + y}"
println sum

// Triple single quotes (no interpolation)
def raw = '''This is a raw string: $x'''
println raw

// Interpolation in GString
def groovy = "Groovy"
def result = "I love $groovy"
println result
Intermediate
27. How do you work with Dates and Times?

Groovy enhances Date and also supports Java 8 time API.

  • Date: new Date()
  • Add days: date + 5
  • Format: date.format('yyyy-MM-dd')
  • Java Time: LocalDateTime.now()
  • Parsing: LocalDateTime.parse()
groovy
// Working with Dates and Times
import java.time.*

def now = LocalDateTime.now()
println now

def future = now.plusDays(5)
println future

def formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
println now.format(formatter)

// Groovy Date enhancements (legacy)
def date = new Date()
println date[Calendar.YEAR]
Intermediate
28. What are collect, find, each?

These are collection iteration methods.

  • collect: Transform each element
  • find: Find first matching element
  • findAll: Find all matching
  • each: Iterate with side effects
  • any, every: Test conditions
groovy
// Collect, Find, Each
def nums = [1,2,3,4,5]
def doubled = nums.collect { it * 2 }
println doubled

def even = nums.findAll { it % 2 == 0 }
println even

def firstEven = nums.find { it % 2 == 0 }
println firstEven

nums.each { println "Number: $it" }
Intermediate
29. What are groupBy and countBy?

Group and count collections by a key.

  • groupBy: Returns a map of grouped elements
  • countBy: Returns a map of counts
  • Closure: The grouping key
  • Use cases: Data analysis
  • Performance: Efficient
groovy
// GroupBy and CountBy
def people = [
    [name:"Alice", age:25, city:"NYC"],
    [name:"Bob", age:30, city:"LA"],
    [name:"Carol", age:25, city:"NYC"]
]

def byCity = people.groupBy { it.city }
byCity.each { city, list -> println "$city: $list" }

def byAge = people.countBy { it.age }
println byAge
Intermediate
30. What is inject (reduce)?

inject accumulates a value through iteration.

  • Syntax: list.inject(initial) { acc, val -> ... }
  • Sum: inject(0) { acc, val -> acc + val }
  • Product: inject(1) { acc, val -> acc * val }
  • Complex reductions: Build maps, strings
  • Alternative: fold in other languages
groovy
// Inject (reduce)
def numbers = 1..5
def product = numbers.inject(1) { acc, val -> acc * val }
println product

def sum = numbers.inject(0) { acc, val -> acc + val }
println sum
Advanced
31. What are AST Transformations?

AST transformations are compile-time annotations that modify the abstract syntax tree.

  • @ToString, @Canonical
  • @Singleton, @Immutable
  • @Delegate, @Lazy
  • @Builder, @Newify
  • @CompileStatic, @TypeChecked
groovy
// Custom Annotations and AST Transformations
import groovy.transform.*

@ToString
class Product {
    String name
    double price
}

@Canonical
class User {
    String name
    int age
}

def p = new Product(name: "Laptop", price: 999.99)
println p

def u = new User("Alice", 25)
println u
Advanced
32. What is GroovyShell and GroovyScriptEngine?

They evaluate Groovy code dynamically.

  • GroovyShell: Simple evaluation
  • Binding: Pass variables
  • GroovyScriptEngine: Script reloading
  • Use cases: Scripting, DSLs
  • Compile: Can compile to classes
groovy
// Groovy Console and Script
// Evaluate dynamic script
def script = "return 3 + 4"
def result = new GroovyShell().evaluate(script)
println result

// Binding
def binding = new Binding()
binding.setVariable("x", 10)
def shell = new GroovyShell(binding)
println shell.evaluate("x * 2")
Advanced
33. What is Groovy Category?

use block allows adding methods to a class temporarily.

  • Category class: Contains static methods
  • use(Category): Enables those methods in scope
  • First parameter: The target type
  • Example: String.reverse()
  • Limited scope: Only within use block
groovy
// Groovy Categories
class StringExtensions {
    static String reverse(String self) { self.reverse() }
}

use (StringExtensions) {
    def msg = "Hello"
    println msg.reverse()
}
Advanced
34. How do you handle XML Namespaces?

Use XmlSlurper with namespace support.

  • ns: Access with 'ns:tag'
  • Namespace declarations: declareNamespace
  • GPath: root.'ns:tag'
  • Attributes: @attr
  • Deep search: '**'
groovy
// Groovy XML Slurper with Namespace
def xml = '''
<ns:book xmlns:ns="http://example.org">
    <ns:title>Groovy</ns:title>
</ns:book>
'''

def books = new XmlSlurper().parseText(xml)
println books.'ns:title'.text()
Advanced
35. What is Grape (dependency management)?

@Grab annotations allow easy dependency fetching.

  • @Grab: Download and import jars
  • Group/artifact/version: @Grab('group:artifact:version')
  • Automatic: Grape handles transitive deps
  • Repositories: Maven central, custom
  • Use case: Scripts and prototypes
groovy
// Groovy Grape (Dependency Management)
@Grab('org.apache.commons:commons-lang3:3.12.0')
import org.apache.commons.lang3.StringUtils

println StringUtils.capitalize("groovy")
Advanced
36. What is ObservableList in Groovy?

An observable collection that fires property change events when modified.

  • ObservableList: List with listeners
  • PropertyChangeListener: Detect changes
  • Use cases: UI binding, reactive programming
  • Add/remove: Events fired
  • Integration: Swing, JavaFX
groovy
// Groovy Observable List
import groovy.util.ObservableList

def list = new ObservableList([1,2,3])
list.addPropertyChangeListener { evt ->
    println "Change: ${evt.propertyName} old=${evt.oldValue} new=${evt.newValue}"
}
list << 4
Advanced
37. What is BeanBuilder in Groovy?

A builder for creating Spring-like beans.

  • BeanBuilder: Builds bean definitions
  • beans: Closure with bean definitions
  • ApplicationContext: Created automatically
  • Dependency injection: Set properties
  • Use case: Spring integration
groovy
// Groovy BeanBuilder
import groovy.util.BeanBuilder

def builder = new BeanBuilder()
def bean = builder.beans {
    person(Person) {
        name = "Alice"
        age = 25
    }
}
def context = builder.createApplicationContext()
def p = context.getBean("person")
println p.name
Advanced
38. How does Groovy integrate with Java?

Seamless: Groovy compiles to Java bytecode, can call Java code and vice versa.

  • Java classes: Can be used directly
  • Java libraries: Import as usual
  • Interface: Groovy classes implement Java interfaces
  • Annotations: Use Java annotations
  • Tooling: Maven/Gradle integration
groovy
// Groovy with Java Interop
import java.util.ArrayList

def list = new ArrayList()
list.add(1)
list.add(2)
println list

// Using Java libraries seamlessly
import java.util.concurrent.Executors
def executor = Executors.newFixedThreadPool(2)
executor.submit { println "Thread" }
executor.shutdown()
Intermediate
39. What is Power Assert in Groovy?

Power assert provides detailed diagnostic information when an assertion fails.

  • assert: Evaluates expression
  • Failure: Shows the values of each sub-expression
  • Useful: For testing and debugging
  • Example: assert list.size() == 2
  • Output: Detailed failure reason
groovy
// Groovy Power Assert
def list = [1,2,3]
assert list.size() == 3
assert list.contains(2)

// Power assert shows detailed info on failure
try {
    assert list.size() == 2
} catch (AssertionError e) {
    println e.message
}
Intermediate
40. How do you use File GDK enhancements?

Groovy adds many file-handling methods to File.

  • eachFileRecurse: Traverse directories
  • withReader/Writer: Auto-close
  • copyTo: Copy file
  • text: Read/write entire file
  • bytes: Binary content
groovy
// Groovy GDK File Enhancements
import groovy.io.FileType

def dir = new File(".")
dir.eachFileRecurse(FileType.FILES) { file ->
    println "File: $file.name"
}

// Copy
new File("source.txt").withReader { r ->
    new File("dest.txt").withWriter { w ->
        w << r
    }
}
Intermediate
41. What is ConfigSlurper?

A tool for parsing configuration files in Groovy syntax.

  • parse: Convert config text to a ConfigObject
  • Nested: Support for nested structures
  • Environment: Environment-specific overrides
  • Types: Can return any type
  • Use case: Application configuration
groovy
// Groovy ConfigSlurper
import groovy.util.ConfigSlurper

def configText = '''
app {
    name = "MyApp"
    version = "1.0"
}
'''
def config = new ConfigSlurper().parse(configText)
println config.app.name
Advanced
42. How to use Eval with variables?

Eval is a shortcut for evaluating code with variables.

  • Eval.me: Evaluate code
  • Binding: Pass variables via map
  • Example: Eval.me('a', 3, 'a*2')
  • Script: Longer scripts
  • Performance: Not for production critical
groovy
// Groovy Eval with variables
def binding = new Binding()
binding.setVariable("a", 5)
binding.setVariable("b", 3)
def shell = new GroovyShell(binding)
println shell.evaluate("a + b")
Advanced
43. What is @Singleton AST transformation?

Ensures only one instance of the class is created.

  • @Singleton: Annotate class
  • Lazy: Lazy or eager instantiation
  • Thread-safe: Safe by default
  • Access: instance property
  • Use case: Shared resources
groovy
// Groovy AST Transforms (Singleton)
import groovy.transform.Singleton

@Singleton
class Config {
    String env = "production"
}

def c1 = Config.instance
def c2 = Config.instance
println c1.is(c2) // true
Beginner
44. What is a Tuple in Groovy?

Tuple is an immutable list of values, used for lightweight structures.

  • Tuple: new Tuple(1, "Hello")
  • Indexed: tuple[0]
  • Immutable: Cannot change
  • Use cases: Multiple return values
  • Comparison: Comparable
groovy
// Groovy Tuple
def t = new Tuple(1, "Hello", 3.14)
println t[0]
println t[1]
println t.size
Intermediate
45. What is Named Arguments and Map Coercion?

You can pass named arguments to constructors and methods, and coerce maps to objects.

  • Named args: new Person(name:"Alice", age:25)
  • Map coercion: map as Person
  • Default constructor: Requires no-arg constructor
  • Properties: Set via named arguments
  • Validation: Optional
groovy
// Groovy Named Arguments and Map Coercion
class Person {
    String name
    int age
}

def p = new Person(name: "Alice", age: 25)
println p

def map = [name: "Bob", age: 30]
def p2 = map as Person
println p2
Intermediate
46. What are Default Parameter Values in Groovy?

Methods and closures can have default values for parameters.

  • def greet(String name = "Guest")
  • Optional parameters: Must be at the end
  • Closures: Can also use defaults
  • Overload: Reduces overloaded methods
  • Use case: Convenient APIs
groovy
// Groovy Default Parameter Values
def greet(String name = "Guest") {
    println "Hello, $name"
}

greet()
greet("Alice")
Advanced
47. What is @Mixin and why is it deprecated?

@Mixin was used to mix in methods from other classes; replaced by traits.

  • @Mixin: Mix in class methods
  • Deprecated: Use traits instead
  • State: Could cause issues
  • Traits: More robust
  • Migration: Convert to traits
groovy
// Groovy Mixed-in Types (using @Mixin) – deprecated but still
class MyMixin {
    def extraMethod() { "extra" }
}

@Mixin(MyMixin)
class MyClass { }

def obj = new MyClass()
println obj.extraMethod()
Intermediate
48. What is Automatic Resource Management (ARM)?

Groovy's with methods automatically close resources.

  • withReader, withWriter
  • withOutputStream, withInputStream
  • Closure: Resource is closed after
  • Exception safe: Closes even on error
  • Use case: File and stream handling
groovy
// Groovy with Automatic Resource Management (ARM)
new File("test.txt").withWriter { writer ->
    writer.writeLine "Hello"
}

// Or using withCloseable for any AutoCloseable
def reader = new StringReader("sample")
reader.withReader { r ->
    println r.text
}
Beginner
49. How do you define Enums in Groovy?

Enums are defined like Java but with Groovy enhancements.

  • enum: enum Color { RED, GREEN }
  • Methods: Can add methods
  • Switch: Use enums in switch
  • Properties: Can have fields
  • Iteration: values()
groovy
// Groovy Enumeration
enum Color {
    RED, GREEN, BLUE
}

def c = Color.GREEN
println c
switch (c) {
    case Color.RED: println "red"; break
    case Color.GREEN: println "green"; break
    default: println "other"
}
Intermediate
50. How do you use Thread.start in Groovy?

Groovy adds a start method to Thread.

  • Thread.start: Creates and starts a thread
  • Closure: Code to run
  • Thread.startDaemon: Daemon thread
  • Simplified: No need to extend Thread
  • Use case: Background tasks
groovy
// Groovy Thread.start
Thread.start {
    println "Thread running"
}
sleep 1000
Advanced
51. What is GPars for concurrency?

GPars provides parallel collections, actors, and dataflow concurrency.

  • GParsPool: Parallel operations
  • collectParallel: Parallel map
  • Actors: Message-passing
  • Dataflow: Dataflow variables
  • Integration: Easy to use
groovy
// Groovy with GPars (concurrency)
@Grab('org.codehaus.gpars:gpars:1.2.1')
import groovyx.gpars.GParsPool

def list = [1,2,3,4,5]
GParsPool.withPool {
    def result = list.collectParallel { it * it }
    println result
}
Advanced
52. What is Timeout (TimedCache) in Groovy?

A simple cache with expiration.

  • Timeout: Cache with TTL
  • put: Store value
  • get: Retrieve, null if expired
  • Use case: Temporary caching
  • Cleanup: Automatic eviction
groovy
// Groovy TimedCache
import groovy.util.Timeout

def cache = new Timeout(1000) // 1 second
cache.put("key", "value")
println cache.get("key")
sleep 1500
println cache.get("key") // null
Advanced
53. What is Observable pattern in Groovy?

Observable collections and maps notify listeners of changes.

  • ObservableList, ObservableMap
  • PropertyChangeListener
  • Events: Element added, removed, changed
  • Use case: UI data binding
  • Threading: Not thread-safe
groovy
// Groovy Observe pattern
import groovy.util.ObservableList
import groovy.util.ObservableMap

def list = new ObservableList([1,2])
list.addPropertyChangeListener { e ->
    println "Change: $e"
}
list << 3
Advanced
54. How do you escape HTML/XML in Groovy?

Use Apache Commons Text or built-in methods.

  • StringEscapeUtils: From commons-text
  • escapeHtml4, escapeXml
  • Groovy: No built-in, use libraries
  • Security: Prevent XSS
  • Example: StringEscapeUtils.escapeHtml4(text)
groovy
// Groovy StringEscapeUtils
@Grab('org.apache.commons:commons-text:1.9')
import org.apache.commons.text.StringEscapeUtils

def html = "<div>Hello</div>"
def escaped = StringEscapeUtils.escapeHtml4(html)
println escaped
Advanced
55. How do you add properties at runtime?

Via metaClass or using @Delegate.

  • metaClass: Add property
  • Property access: obj.metaClass.prop = value
  • Getter/Setter: Can be overridden
  • Dynamic: Runtime addition
  • Caution: Can affect performance
groovy
// Groovy Bean Property access via metaClass
class User {
    String name
}

def u = new User()
u.metaClass.email = "alice@email.com"
println u.email
Advanced
56. What is Interceptable for AOP?

Implement Interceptable to intercept method calls.

  • Interceptable: Interface for interception
  • beforeInvoke: Called before method
  • afterInvoke: Called after
  • Use case: Logging, validation
  • Alternative: invokeMethod
groovy
// Groovy Interceptable (AOP)
import groovy.lang.Interceptable

class MyInterceptor implements Interceptable {
    def beforeInvoke(String name, Object[] args) {
        println "Before $name"
    }
}

class Test {
    def method() { "test" }
}

def t = new Test()
t.metaClass.invokeMethod = { String name, args ->
    println "Intercepting $name"
    def original = delegate.metaClass.getMetaMethod(name, args)
    original?.invoke(delegate, args)
}
println t.method()
Advanced
57. How to use JMX with Groovy?

Groovy simplifies JMX by using dynamic MBeans.

  • MBeanServer: Platform MBeanServer
  • ObjectName: Unique name
  • registerMBean: Register object
  • Access attributes: getAttribute
  • Use case: Monitoring and management
groovy
// Groovy with JMX
import javax.management.*

def server = ManagementFactory.platformMBeanServer
def name = ObjectName.getInstance("com.example:type=Hello")
server.registerMBean(new Object() { def sayHi() { "Hi" } }, name)
println server.getAttribute(name, "SayHi")
Intermediate
58. What are BigInteger and BigDecimal in Groovy?

Groovy uses BigInteger and BigDecimal for arbitrary precision numbers.

  • BigInteger: Large integers
  • BigDecimal: High-precision decimals
  • Operators: Supports arithmetic
  • Performance: Slower but accurate
  • Use cases: Financial calculations
groovy
// Groovy Data Types: BigInteger, BigDecimal
def bigInt = new BigInteger("12345678901234567890")
def bigDec = new BigDecimal("12345.6789")
println bigInt + 100
println bigDec + 0.001
Beginner
59. How do you work with char and boolean?

Chars and booleans are primitive-like but can be objects.

  • char: 'A' as char or 'A'
  • boolean: true / false
  • Autoboxing: Can use Character, Boolean
  • Operations: Logical and comparison
  • Groovy Truth: Works as expected
groovy
// Groovy Char and Boolean handling
def flag = true
def ch = 'A'
if (flag) println "Yes"
println ch.toLowerCase()
Intermediate
60. What are @ToString and @EqualsAndHashCode?

AST transformations that generate these methods automatically.

  • @ToString: Generate toString()
  • @EqualsAndHashCode: Generate equals and hashCode
  • Includes/excludes: Control fields
  • Cache: Can cache hash code
  • Use case: Data classes
groovy
// Groovy using @ToString and @EqualsAndHashCode
import groovy.transform.*

@ToString(includeNames=true)
@EqualsAndHashCode
class Product {
    String name
    double price
}

def p1 = new Product(name: "Apple", price: 1.2)
def p2 = new Product(name: "Apple", price: 1.2)
println p1
println p1 == p2
Intermediate
61. What is @Immutable?

Makes a class immutable – all fields final, no setters.

  • @Immutable: Annotate class
  • Fields: Must be final
  • Constructor: Generated with all fields
  • Thread-safe: Safe for concurrent access
  • Use case: Value objects
groovy
// Groovy with @Immutable
@Immutable
class Point {
    int x, y
}

def p = new Point(1, 2)
// p.x = 3 // immutable
println p
Intermediate
62. What is @Builder?

Generates a builder class for the annotated class.

  • @Builder: Provides builder pattern
  • Fluent: Method chaining
  • Defaults: Optional fields
  • Build method: build()
  • Use case: Constructing complex objects
groovy
// Groovy with @Builder
import groovy.transform.builder.Builder

@Builder
class Person {
    String name
    int age
}

def p = Person.builder().name("Alice").age(25).build()
println p
Intermediate
63. What is @Delegate?

Delegates method calls to a field.

  • @Delegate: Annotate a field
  • Methods: Forwarded to the delegate
  • Interfaces: Implements interfaces of delegate
  • Override: Can override delegated methods
  • Use case: Composition over inheritance
groovy
// Groovy with @Delegate
class Worker {
    def doWork() { "working" }
}

class Employee {
    @Delegate Worker worker = new Worker()
}

def e = new Employee()
println e.doWork()
Intermediate
64. What is @Lazy?

Initializes a property lazily.

  • @Lazy: Delayed initialization
  • Closure: Initialization logic
  • Thread-safe: Safe by default
  • Use case: Expensive resources
  • Performance: Improves startup
groovy
// Groovy with @Lazy
class Heavy {
    def heavy = { println "created"; "heavy" }()
}

def h = new Heavy()
println h.heavy // created only once
Advanced
65. What is @AutoExternalize?

Implements Externalizable for serialization.

  • @AutoExternalize: Generate readExternal/writeExternal
  • Fields: All fields serialized
  • Transient: Can be excluded
  • Use case: Custom serialization
  • Performance: Efficient serialization
groovy
// Groovy @AutoExternalize
import groovy.transform.AutoExternalize

@AutoExternalize
class Data {
    String name
    int age
}

def d = new Data(name: "Alice", age: 25)
def bytes = d.bytes
def d2 = new Data(bytes)
println d2
Advanced
66. What is @CompileStatic?

Enforces static type checking and compilation.

  • @CompileStatic: Annotate class or method
  • Type safety: Checked at compile time
  • Performance: Faster than dynamic
  • Limitations: Some dynamic features unavailable
  • Use case: Performance-critical code
groovy
// Groovy with @CompileStatic
import groovy.transform.CompileStatic

@CompileStatic
def add(int a, int b) { a + b }
println add(3, 4)
Advanced
67. What is @TypeChecked?

Checks types at compile time but retains dynamic behavior.

  • @TypeChecked: Enable type checking
  • Strict: Catches type errors
  • Mix: Can be used with dynamic parts
  • Errors: Compilation errors on type mismatch
  • Use case: Ensuring type safety
groovy
// Groovy with @TypeChecked
import groovy.transform.TypeChecked

@TypeChecked
def multiply(int a, int b) { a * b }
println multiply(3, 4)
Advanced
68. What is @Memoized?

Caches the result of a method based on arguments.

  • @Memoized: Caches results
  • Key: Argument values
  • Cache size: Configurable
  • Thread-safe: Safe for concurrent calls
  • Use case: Expensive computations
groovy
// Groovy with @Memoized
import groovy.transform.Memoized

@Memoized
def fib(n) {
    if (n <= 1) return n
    fib(n-1) + fib(n-2)
}
println fib(40)
Advanced
69. What is @Newify?

Allows creating objects without 'new' keyword.

  • @Newify: Import constructor method
  • Syntax: Person(name:"Alice")
  • Classes: Specify which classes
  • Scope: Class or method level
  • Use case: DSLs
groovy
// Groovy with Newify
import groovy.transform.Newify

@Newify([Person, Address])
class Test {
    def p = Person(name: "Alice")
    def a = Address(city: "NYC")
}

class Person { String name }
class Address { String city }

def t = new Test()
println t.p.name
Intermediate
70. How do you sort in Groovy?

Use sort method with a comparator or closure.

  • sort: Natural ordering
  • Comparator: Custom comparator
  • Closure: sort { a, b -> a <= b }
  • Sort by property: sort { it.name }
  • Reverse: sort().reverse()
groovy
// Groovy with Sort
def list = [4,2,5,1,3]
list.sort()
println list

def strings = ["apple", "Banana", "cherry"]
strings.sort { a, b -> a.toLowerCase() <=> b.toLowerCase() }
println strings
Intermediate
71. How to find duplicates in a list?

Use unique to remove duplicates or count to find them.

  • unique: Removes duplicates
  • Duplicate detection: findAll { list.count(it) > 1 }.unique()
  • Efficiency: O(n²) for count; use grouping for large lists
  • Group by: groupBy { it }.findAll { it.value.size() > 1 }
  • Use case: Data cleaning
groovy
// Groovy Unique and Duplicates
def list = [1,2,2,3,4,4,5]
def unique = list.unique()
println unique

def duplicates = list.findAll { list.count(it) > 1 }.unique()
println duplicates
Intermediate
72. What is transpose in Groovy?

Transpose flips rows and columns of a matrix.

  • transpose: On list of lists
  • Result: Swapped dimensions
  • Use case: Matrix operations
  • Example: [[1,2],[3,4]].transpose()
  • Length: Assumes uniform sub-lists
groovy
// Groovy Transpose
def matrix = [[1,2], [3,4], [5,6]]
def transposed = matrix.transpose()
println transposed
Intermediate
73. What is collate (chunk) in Groovy?

Splits a collection into smaller chunks.

  • collate: list.collate(size)
  • Partial last chunk: collate(size, false)
  • Use case: Batching
  • Example: (1..10).collate(3)
  • Performance: Efficient
groovy
// Groovy Collate (chunk)
def list = 1..10
def chunks = list.collate(3)
println chunks
Intermediate
74. What is flatten?

Flattens nested structures into a single list.

  • flatten: Removes nesting
  • Deep: Recursively flattens
  • Use case: Processing nested data
  • Example: [[1,2],3].flatten()
  • Performance: Works on depth
groovy
// Groovy InFlatten (deep flatten)
def nested = [1, [2,3], [4, [5,6]]]
def flat = nested.flatten()
println flat
Intermediate
75. What is EnumSet?

A specialized Set for enums, efficient and type-safe.

  • EnumSet: From Java
  • of: EnumSet.of(Size.SMALL)
  • Range: EnumSet.range(Size.SMALL, Size.LARGE)
  • Operations: Set operations
  • Use case: Enum collections
groovy
// Groovy with EnumSet
import java.util.EnumSet

enum Size { SMALL, MEDIUM, LARGE }

def set = EnumSet.of(Size.SMALL, Size.MEDIUM)
println set
Intermediate
76. How to use PriorityQueue?

PriorityQueue implements a priority heap.

  • PriorityQueue: Elements ordered by priority
  • add: Insert
  • poll: Remove highest priority
  • Comparator: Custom ordering
  • Use case: Task scheduling
groovy
// Groovy with PriorityQueue
import java.util.PriorityQueue

def pq = new PriorityQueue()
pq.add(5)
pq.add(1)
pq.add(3)
while (!pq.isEmpty()) {
    println pq.poll()
}
Intermediate
77. How to use Stack?

Stack can be simulated using a List.

  • Stack: LIFO
  • push: list.add(value)
  • pop: list.remove(list.size()-1)
  • peek: list.last()
  • Use case: Undo operations
groovy
// Groovy with Stack
def stack = []
stack.push(1)
stack.push(2)
println stack.pop()
println stack
Intermediate
78. What are Bitwise operators in Groovy?

Groovy supports bitwise operators: &, |, ^, ~.

  • AND: &
  • OR: |
  • XOR: ^
  • Complement: ~
  • Shift: <<, >>, >>>
groovy
// Groovy with Bitwise operators
def a = 5 // 101
def b = 3 // 011
println a & b // 1
println a | b // 7
println a ^ b // 6
println ~a
Beginner
79. How to use Range with for and step?

Iterate over ranges with step.

  • for: for (i in 1..10)
  • step: (1..10).step(2)
  • Exclusive: 0..<5
  • DownTo: 10.downTo(1)
  • times: 5.times
groovy
// Groovy with Range and for each
for (i in 0..<5) {
    println i
}

// Step
(0..10).step(2) { println it }
Intermediate
80. What are any and every?

Test if any/all elements satisfy a predicate.

  • any: list.any { it > 5 }
  • every: list.every { it > 0 }
  • Short-circuit: Stops early
  • Use case: Validation
  • Examples: Checking conditions
groovy
// Groovy with any and every
def list = [1,2,3]
println list.any { it > 2 } // true
println list.every { it > 0 } // true
Intermediate
81. What is findIndexOf?

Returns the index of the first element that matches a condition.

  • findIndexOf: list.findIndexOf { it == 3 }
  • findLastIndexOf: From the end
  • Return: Index or -1
  • Use case: Searching
  • Example: [1,2,3].findIndexOf { it > 1 }
groovy
// Groovy with findIndexOf
def list = [1,2,3,4]
def idx = list.findIndexOf { it == 3 }
println idx
Beginner
82. How to split and tokenize strings?

split uses regex, tokenize uses a delimiter.

  • split: "a,b,c".split(',')
  • tokenize: "a,b,c".tokenize(',')
  • Differences: tokenize ignores empty tokens
  • Use case: Parsing CSV
  • Regex: split(/\s+/)
groovy
// Groovy with split and tokenize
def str = "a,b,c"
def parts = str.split(',')
println parts

def tokens = str.tokenize(',')
println tokens
Intermediate
83. How to find regex matches?

Use =~ or find on matcher.

  • Matcher: (text =~ /\\d+/)
  • find: matcher.find()
  • group: matcher.group()
  • findAll: Get all matches
  • Example: Extract numbers
groovy
// Groovy with Regex Find
def text = "abc123def"
def matcher = (text =~ /\d+/)
if (matcher.find()) {
    println matcher.group()
}
Intermediate
84. How to replace with a closure?

replaceAll can use a closure for dynamic replacement.

  • replaceAll: str.replaceAll(/pattern/) { match -> ... }
  • Dynamic: Based on matched text
  • Use case: Template engines
  • Example: Uppercase matches
  • Performance: Efficient
groovy
// Groovy with replaceAll using closure
def str = "Hello World"
def replaced = str.replaceAll(/o/) { it.toUpperCase() }
println replaced
Advanced
85. What is @BaseScript?

Specifies a custom script base class for Groovy scripts.

  • @BaseScript: Annotates script class
  • Custom methods: Provide utility methods
  • Variables: Can define binding variables
  • Use case: DSLs
  • Example: Logging, configuration
groovy
// Groovy with @BaseScript (script base class)
abstract class ScriptBase extends Script {
    def log(msg) { println "[LOG] $msg" }
}

// In script file:
// @BaseScript ScriptBase base
// log "Hello"
Advanced
86. What is @Field?

Marks a script variable as a field, making it persistent across method calls.

  • @Field: For script-level fields
  • Scope: Belongs to the script instance
  • Use case: Maintaining state in scripts
  • Example: @Field int counter
  • Contrast: Local variables are not fields
groovy
// Groovy with @Field (for class fields in scripts)
import groovy.transform.Field

@Field int counter = 0
def increment() { counter++ }
increment()
println counter
Advanced
87. What is CliBuilder?

A command-line interface builder for parsing options.

  • CliBuilder: Define options
  • parse: Parse arguments
  • Access: options.optName
  • Help: Automatic usage
  • Use case: Script arguments
groovy
// Groovy with CliBuilder (command-line parsing)
import groovy.util.CliBuilder

def cli = new CliBuilder(usage: 'app [options]')
cli.h( longOpt: 'help', 'Show usage' )
cli.n( longOpt: 'name', args: 1, 'Name' )

def options = cli.parse(args)
if (options.h) cli.usage()
if (options.n) println "Hello, ${options.n}"
Advanced
88. What is CompilerConfiguration?

Configures the Groovy compiler, e.g., target directory, classpath.

  • CompilerConfiguration: Set compiler options
  • targetDirectory: Output folder
  • classpath: Additional classpath
  • Use case: Custom compilation
  • Integration: With GroovyShell
groovy
// Groovy with CompilerConfiguration (custom AST)
import org.codehaus.groovy.control.CompilerConfiguration

def config = new CompilerConfiguration()
config.setTargetDirectory('target')
def shell = new GroovyShell(config)
shell.evaluate("println 'Hello'")
Advanced
89. What is ObjectGraphBuilder?

Builds object graphs declaratively.

  • ObjectGraphBuilder: Builder for objects
  • Nodes: root { person(id:1) }
  • Relationships: Parent-child
  • Use case: Test data
  • Example: Constructing complex structures
groovy
// Groovy with ObjectGraphBuilder
import groovy.util.ObjectGraphBuilder

def builder = new ObjectGraphBuilder()
def root = builder.root {
    person(id:1, name:"Alice")
    person(id:2, name:"Bob")
}
root.children.each { println it.name }
Advanced
90. What is AntBuilder?

Allows running Ant tasks from Groovy.

  • AntBuilder: Execute Ant tasks
  • Tasks: ant.echo(message: "Hello")
  • Properties: Set Ant properties
  • Use case: Build automation
  • Integration: With Gradle
groovy
// Groovy with AntBuilder
import groovy.util.AntBuilder

def ant = new AntBuilder()
ant.echo(message: "Hello from Ant")
Advanced
91. What is SwingBuilder?

Builds Swing UI declaratively.

  • SwingBuilder: Construct Swing components
  • Layouts: Panels, buttons, labels
  • Events: Add action listeners
  • Example: frame(title:'Test') { panel { label('Hello') } }
  • Use case: Quick GUI prototypes
groovy
// Groovy with SwingBuilder (UI)
import groovy.swing.SwingBuilder
import javax.swing.*

def swing = new SwingBuilder()
def frame = swing.frame(title:'Test', size:[200,200], visible:true) {
    label(text:'Hello')
}
sleep 2000
frame.dispose()
Advanced
92. How to use @Option for CLI?

Define option fields in a class and use with CliBuilder.

  • @Option: Annotate fields
  • CliBuilder: Parse into object
  • Fields: @Option(shortName='n') String name
  • Usage: cli.parse(args)
  • Benefit: Type safety
groovy
// Groovy with CliBuilder and Option Accessors
// Same as above but using @Option
import groovy.util.Option

class App {
    @Option(shortName='n', longName='name')
    String name
}

def cli = new CliBuilder()
cli.with {
    n longOpt:'name', args:1, 'Name'
}
// ...
Intermediate
93. How to use ResourceBundle?

Use Java's ResourceBundle for i18n.

  • ResourceBundle: Get bundle
  • getString: Retrieve localized string
  • Locale: Specify locale
  • Use case: Internationalization
  • Example: ResourceBundle.getBundle("messages").getString("key")
groovy
// Groovy with ResourceBundle
import java.util.ResourceBundle

def bundle = ResourceBundle.getBundle("messages")
println bundle.getString("greeting")
Intermediate
94. How to parse dates?

Use SimpleDateFormat or Java 8 time.

  • SimpleDateFormat: new SimpleDateFormat("yyyy-MM-dd").parse("2023-01-01")
  • Java Time: LocalDate.parse("2023-01-01")
  • Format: Use pattern
  • Exception: ParseException
  • Use case: Date input parsing
groovy
// Groovy with SimpleDateFormat
import java.text.SimpleDateFormat

def sdf = new SimpleDateFormat("yyyy-MM-dd")
def date = sdf.parse("2023-01-01")
println date
Intermediate
95. How to download a file from URL?

Use URL.text or URL.withInputStream.

  • URL.text: Get content as string
  • Save to file: file << url.text
  • Binary: Use bytes
  • Progress: Use streams
  • Use case: Download resources
groovy
// Groovy with URL Connection and file download
def url = new URL("https://example.com/file.txt")
def file = new File("downloaded.txt")
file << url.text
println "Downloaded"
Advanced
96. How to handle ZIP files?

Use Java's ZipOutputStream and ZipFile.

  • ZipOutputStream: Write to zip
  • ZipFile: Read from zip
  • Groovy: withZipOutputStream
  • Entry: putNextEntry
  • Example: new File("archive.zip").withZipOutputStream { ... }
groovy
// Groovy with Zip file handling
import java.util.zip.*

def zipFile = new File("archive.zip")
zipFile.withZipOutputStream { zos ->
    zos.putNextEntry(new ZipEntry("file.txt"))
    zos << "Hello"
}
Intermediate
97. How to create temporary files?

Use File.createTempFile().

  • createTempFile: Create in temp directory
  • deleteOnExit: Automatic cleanup
  • Read/Write: As regular file
  • Use case: Temporary data
  • Security: Random naming
groovy
// Groovy with temp files
File temp = File.createTempFile("tmp", ".txt")
temp << "Temporary"
println temp.text
temp.deleteOnExit()
Intermediate
98. How to Base64 encode/decode?

Use Java's Base64 utility.

  • Base64.encoder: Encode bytes
  • decoder: Decode
  • String conversion: new String(decoded)
  • Use case: Binary data transfer
  • Example: Authentication headers
groovy
// Groovy with Base64 encoding
import java.util.Base64

def text = "Hello"
def encoded = Base64.encoder.encodeToString(text.bytes)
println encoded
def decoded = new String(Base64.decoder.decode(encoded))
println decoded
Beginner
99. How to generate UUID?

Use UUID.randomUUID().

  • UUID: UUID.randomUUID()
  • Format: Standard 36-char
  • Use case: Unique identifiers
  • Version: Random UUID v4
  • String: uuid.toString()
groovy
// Groovy with UUID
import java.util.UUID

def uuid = UUID.randomUUID()
println uuid
Intermediate
100. How to access System Properties?

Use System.properties.

  • System.properties: All properties
  • Access: System.getProperty("key")
  • Set: System.setProperty("key", "value")
  • Iteration: each on properties
  • Use case: Environment info
groovy
// Groovy with System Properties
System.properties.each { k, v ->
    println "$k = $v"
}