- Dynamic and static typing: Optional types
- Closures: First-class functions
- Metaprogramming: Runtime modification
- Builders: Domain-specific languages
- Seamless Java integration
// Hello World in Groovy
println "Hello, World!"The most asked Groovy interview questions with structured answers — a quick answer, a clear explanation and working code for each. Covers basics for freshers through advanced, scenario and coding questions for experienced developers.
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.
Start here if you are a fresher or switching to Groovy. These fundamentals are asked in almost every first-round and campus interview.
// Hello World in Groovy
println "Hello, World!"How interviewers ask it“Let's start with the basics — how would you explain data types in 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"How interviewers ask it“Let's start with the basics — how would you explain variables and constants in Groovy?”
String name(x, y) = [1, 2]// 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"How interviewers ask it“In simple words, what are lists and ranges? Explain it like you would to a new teammate.”
def list = [1, 2, 3]1..10list[-1]*list// 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]How interviewers ask it“Let's start with the basics — how would you explain maps in Groovy?”
[key: value]map.key or map['key']eachremovewithDefault// 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 scoresHow interviewers ask it“In simple words, what are closures? Explain it like you would to a new teammate.”
{ x -> x * x }itcurry()delegatecollect, findAll// 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)How interviewers ask it“Let's start with the basics — how would you explain classes and objects in Groovy?”
class Person { String name }// 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()}"How interviewers ask it“In simple words, what are strings and GStrings? Explain it like you would to a new teammate.”
'Hello'"Hello $name"/regex/reverse, padLeft// 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, '*')How interviewers ask it“In simple words, what is Groovy truth? Explain it like you would to a new teammate.”
// 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"How interviewers ask it“How does string interpolation work under the hood? Take me through it step by step.”
\$ to escape// 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 resultHow interviewers ask it“Let's start with the basics — how would you explain a tuple in Groovy?”
new Tuple(1, "Hello")tuple[0]// Groovy Tuple
def t = new Tuple(1, "Hello", 3.14)
println t[0]
println t[1]
println t.sizeHow interviewers ask it“Suppose you need to define Enums in Groovy — how do you approach it, and what can go wrong?”
enum Color { RED, GREEN }values()// 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"
}How interviewers ask it“Suppose you need to work with char and boolean in Groovy — how do you approach it, and what can go wrong?”
'A' as char or 'A'true / falseCharacter, Boolean// Groovy Char and Boolean handling
def flag = true
def ch = 'A'
if (flag) println "Yes"
println ch.toLowerCase()How interviewers ask it“How would you use Range with for and step? Walk me through your approach.”
for (i in 1..10)(1..10).step(2)0..<510.downTo(1)5.times {}// Groovy with Range and for each
for (i in 0..<5) {
println i
}
// Step
(0..10).step(2) { println it }How interviewers ask it“How would you split and tokenize strings? Walk me through your approach.”
"a,b,c".split(',')"a,b,c".tokenize(',')split(/\s+/)// Groovy with split and tokenize
def str = "a,b,c"
def parts = str.split(',')
println parts
def tokens = str.tokenize(',')
println tokensHow interviewers ask it“How would you generate UUID? Walk me through your approach.”
UUID.randomUUID()uuid.toString()// Groovy with UUID
import java.util.UUID
def uuid = UUID.randomUUID()
println uuidQuestions for candidates with 1–3 years of experience — the concepts interviewers use to check that you have actually built things with Groovy.
How interviewers ask it“How would you explain traits to a junior engineer, and what do people most often get wrong?”
trait Logger { void log(String) }class MyClass implements Logger// 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")How interviewers ask it“How does inheritance work under the hood? Take me through it step by step.”
abstractimplements// 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() }How interviewers ask it“Walk me through abstract classes and interfaces in Groovy. Where do they come up in real systems?”
abstract classinterfaceimplements A, B// 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()?: (if null, use default)?.*. (spread-dot)[*list]*.method()// 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 newListHow interviewers ask it“How would you use Regular Expressions? Walk me through your approach.”
~//=~==~replaceAllmatcher.group// 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)
}How interviewers ask it“How does exception handling work under the hood? Take me through it step by step.”
throw new Exception()// 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
}How interviewers ask it“How would you perform File I/O? Walk me through your approach.”
withReader, withWriterfile.texteachLinebytes propertydelete()// 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()How interviewers ask it“Suppose you need to work with JSON — how do you approach it, and what can go wrong?”
JsonOutput.toJson()JsonOutput.prettyPrint()JsonSlurper().parseText()JsonBuilderJsonSlurper handles large data// 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.nameHow interviewers ask it“Suppose you need to handle XML in Groovy — how do you approach it, and what can go wrong?”
new XmlSlurper().parseText(xml)MarkupBuilderXmlSlurper is efficient// 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.@idHow interviewers ask it“How would you explain builders to a junior engineer, and what do people most often get wrong?”
// 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()How interviewers ask it“Explain Groovy JDK enhancements in detail — what should a new team member understand about them?”
Groovy adds many methods to Java classes (e.g., List.sum(), String.truncate()).
sum, average, maxcenter, truncate, reversesubMap, eachtimes, uptoeachLine, withReader// 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'])1..10switch(age) { case 0..17: ... }breakdefault case// 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"
}How interviewers ask it“How would you work with Dates and Times? Walk me through your approach.”
new Date()date + 5date.format('yyyy-MM-dd')LocalDateTime.now()LocalDateTime.parse()// 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]// 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" }How interviewers ask it“How would you explain groupBy and countBy to a junior engineer, and what do people most often get wrong?”
// 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 byAgeHow interviewers ask it“How would you explain inject (reduce) to a junior engineer, and what do people most often get wrong?”
list.inject(initial) { acc, val -> ... }inject(0) { acc, val -> acc + val }inject(1) { acc, val -> acc * val }fold in other languages// 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 sumHow interviewers ask it“How would you explain power assert to a junior engineer, and what do people most often get wrong?”
assert list.size() == 2// 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
}How interviewers ask it“Suppose you need to use File GDK enhancements in Groovy — how do you approach it, and what can go wrong?”
// 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
}
}How interviewers ask it“Walk me through ConfigSlurper in Groovy. Where does it come up in real systems?”
// Groovy ConfigSlurper
import groovy.util.ConfigSlurper
def configText = '''
app {
name = "MyApp"
version = "1.0"
}
'''
def config = new ConfigSlurper().parse(configText)
println config.app.nameHow interviewers ask it“How would you explain named arguments and map coercion to a junior engineer, and what do people most often get wrong?”
new Person(name:"Alice", age:25)map as Person// 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 p2How interviewers ask it“Walk me through default parameter values in Groovy. Where do they come up in real systems?”
// Groovy Default Parameter Values
def greet(String name = "Guest") {
println "Hello, $name"
}
greet()
greet("Alice")How interviewers ask it“How would you explain automatic resource management (ARM) to a junior engineer, and what do people most often get wrong?”
// 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
}How interviewers ask it“Suppose you need to use Thread.start in Groovy — how do you approach it, and what can go wrong?”
// Groovy Thread.start
Thread.start {
println "Thread running"
}
sleep 1000How interviewers ask it“Explain BigInteger and BigDecimal in Groovy in detail — what should a new team member understand about them?”
// Groovy Data Types: BigInteger, BigDecimal
def bigInt = new BigInteger("12345678901234567890")
def bigDec = new BigDecimal("12345.6789")
println bigInt + 100
println bigDec + 0.001How interviewers ask it“How would you explain @ToString and @EqualsAndHashCode to a junior engineer, and what do people most often get wrong?”
toString()equals and hashCode// 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 == p2How interviewers ask it“How would you explain @Immutable to a junior engineer, and what do people most often get wrong?”
// Groovy with @Immutable
@Immutable
class Point {
int x, y
}
def p = new Point(1, 2)
// p.x = 3 // immutable
println pHow interviewers ask it“How would you explain @Builder to a junior engineer, and what do people most often get wrong?”
build()// 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 pHow interviewers ask it“Explain @Delegate in Groovy in detail — what should a new team member understand about it?”
// Groovy with @Delegate
class Worker {
def doWork() { "working" }
}
class Employee {
@Delegate Worker worker = new Worker()
}
def e = new Employee()
println e.doWork()How interviewers ask it“Walk me through @Lazy in Groovy. Where does it come up in real systems?”
// Groovy with @Lazy
class Heavy {
def heavy = { println "created"; "heavy" }()
}
def h = new Heavy()
println h.heavy // created only onceHow interviewers ask it“Coding-round task — sort in Groovy. Explain your approach before you write the code.”
sort { a, b -> a <= b }sort { it.name }sort().reverse()// 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 stringsHow interviewers ask it“Can you find duplicates in a list in Groovy? Then walk me through the edge cases you would test.”
findAll { list.count(it) > 1 }.unique()groupBy { it }.findAll { it.value.size() > 1 }// 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 duplicatesHow interviewers ask it“Walk me through transpose in Groovy. Where does it come up in real systems?”
[[1,2],[3,4]].transpose()// Groovy Transpose
def matrix = [[1,2], [3,4], [5,6]]
def transposed = matrix.transpose()
println transposedHow interviewers ask it“How would you explain collate (chunk) to a junior engineer, and what do people most often get wrong?”
list.collate(size)collate(size, false)(1..10).collate(3)// Groovy Collate (chunk)
def list = 1..10
def chunks = list.collate(3)
println chunksHow interviewers ask it“How would you explain flatten to a junior engineer, and what do people most often get wrong?”
[[1,2],3].flatten()// Groovy InFlatten (deep flatten)
def nested = [1, [2,3], [4, [5,6]]]
def flat = nested.flatten()
println flatHow interviewers ask it“Walk me through EnumSet in Groovy. Where does it come up in real systems?”
EnumSet.of(Size.SMALL)EnumSet.range(Size.SMALL, Size.LARGE)// Groovy with EnumSet
import java.util.EnumSet
enum Size { SMALL, MEDIUM, LARGE }
def set = EnumSet.of(Size.SMALL, Size.MEDIUM)
println setHow interviewers ask it“How would you use PriorityQueue? Walk me through your approach.”
// 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()
}How interviewers ask it“Suppose you need to use Stack in Groovy — how do you approach it, and what can go wrong?”
list.add(value)list.remove(list.size()-1)list.last()// Groovy with Stack
def stack = []
stack.push(1)
stack.push(2)
println stack.pop()
println stackHow interviewers ask it“Walk me through bitwise operators in Groovy. Where do they come up in real systems?”
Groovy supports bitwise operators: &, |, ^, ~.
&|^~<<, >>, >>>// 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 ~aHow interviewers ask it“How would you explain any and every to a junior engineer, and what do people most often get wrong?”
list.any { it > 5 }list.every { it > 0 }// Groovy with any and every
def list = [1,2,3]
println list.any { it > 2 } // true
println list.every { it > 0 } // trueHow interviewers ask it“Explain findIndexOf in Groovy in detail — what should a new team member understand about it?”
list.findIndexOf { it == 3 }[1,2,3].findIndexOf { it > 1 }// Groovy with findIndexOf
def list = [1,2,3,4]
def idx = list.findIndexOf { it == 3 }
println idxHow interviewers ask it“Can you find regex matches in Groovy? Then walk me through the edge cases you would test.”
(text =~ /\\d+/)matcher.find()matcher.group()// Groovy with Regex Find
def text = "abc123def"
def matcher = (text =~ /\d+/)
if (matcher.find()) {
println matcher.group()
}How interviewers ask it“How would you replace with a closure? Walk me through your approach.”
str.replaceAll(/pattern/) { match -> ... }// Groovy with replaceAll using closure
def str = "Hello World"
def replaced = str.replaceAll(/o/) { it.toUpperCase() }
println replacedHow interviewers ask it“Suppose you need to use ResourceBundle in Groovy — how do you approach it, and what can go wrong?”
ResourceBundle.getBundle("messages").getString("key")// Groovy with ResourceBundle
import java.util.ResourceBundle
def bundle = ResourceBundle.getBundle("messages")
println bundle.getString("greeting")How interviewers ask it“How would you parse dates? Walk me through your approach.”
new SimpleDateFormat("yyyy-MM-dd").parse("2023-01-01")LocalDate.parse("2023-01-01")// Groovy with SimpleDateFormat
import java.text.SimpleDateFormat
def sdf = new SimpleDateFormat("yyyy-MM-dd")
def date = sdf.parse("2023-01-01")
println dateHow interviewers ask it“How would you download a file from URL? Walk me through your approach.”
file << url.textbytes// 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"How interviewers ask it“How would you create temporary files? Walk me through your approach.”
// Groovy with temp files
File temp = File.createTempFile("tmp", ".txt")
temp << "Temporary"
println temp.text
temp.deleteOnExit()How interviewers ask it“How would you Base64 encode/decode? Walk me through your approach.”
new String(decoded)// 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 decodedHow interviewers ask it“How would you access System Properties? Walk me through your approach.”
System.getProperty("key")System.setProperty("key", "value")each on properties// Groovy with System Properties
System.properties.each { k, v ->
println "$k = $v"
}Senior-level Groovy questions on internals, performance, design and trade-offs — typical for 3, 5 and 7+ years of experience.
How interviewers ask it“How would you use Groovy SQL? Walk me through your approach.”
Sql.newInstance()rows(), eachRow()execute()withTransaction()withBatch()// 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()How interviewers ask it“How would you make HTTP requests? Walk me through your approach.”
new URL(url).textsetRequestProperty// 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
}How interviewers ask it“How would you explain metaprogramming with ExpandoMetaClass to a junior engineer, and what do people most often get wrong?”
String.metaClass.reverseWords = { ... }Integer.metaClass.doubleValuemetaClass.constructor = { ... }metaClass.'static'// 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()How interviewers ask it“How would you explain methodMissing and propertyMissing to a junior engineer, and what do people most often get wrong?”
// 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)How interviewers ask it“Walk me through AST transformations in Groovy. Where do they come up in real systems?”
// 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 uHow interviewers ask it“How would you explain GroovyShell and GroovyScriptEngine to a junior engineer, and what do people most often get wrong?”
// 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")How interviewers ask it“Walk me through Groovy category. Where does it come up in real systems?”
String.reverse()use block// Groovy Categories
class StringExtensions {
static String reverse(String self) { self.reverse() }
}
use (StringExtensions) {
def msg = "Hello"
println msg.reverse()
}How interviewers ask it“How would you handle XML Namespaces? Walk me through your approach.”
'ns:tag'declareNamespaceroot.'ns:tag'@attr'**'// 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()How interviewers ask it“Walk me through grape (dependency management) in Groovy. Where does it come up in real systems?”
@Grab('group:artifact:version')// Groovy Grape (Dependency Management)
@Grab('org.apache.commons:commons-lang3:3.12.0')
import org.apache.commons.lang3.StringUtils
println StringUtils.capitalize("groovy")How interviewers ask it“How would you explain ObservableList to a junior engineer, and what do people most often get wrong?”
// 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 << 4How interviewers ask it“How would you explain BeanBuilder to a junior engineer, and what do people most often get wrong?”
// 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// 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()How interviewers ask it“How would you use Eval with variables? Walk me through your approach.”
Eval.me('a', 3, 'a*2')// 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")How interviewers ask it“How would you explain @Singleton AST transformation to a junior engineer, and what do people most often get wrong?”
instance property// 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// 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()How interviewers ask it“Explain GPars for concurrency in Groovy in detail — what should a new team member understand about it?”
// 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
}How interviewers ask it“Walk me through timeout (TimedCache) in Groovy. Where does it come up in real systems?”
// 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") // nullHow interviewers ask it“Explain observable pattern in Groovy in detail — what should a new team member understand about it?”
// Groovy Observe pattern
import groovy.util.ObservableList
import groovy.util.ObservableMap
def list = new ObservableList([1,2])
list.addPropertyChangeListener { e ->
println "Change: $e"
}
list << 3How interviewers ask it“How would you escape HTML/XML? Walk me through your approach.”
StringEscapeUtils.escapeHtml4(text)// 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 escapedHow interviewers ask it“How would you add properties at runtime? Walk me through your approach.”
obj.metaClass.prop = value// Groovy Bean Property access via metaClass
class User {
String name
}
def u = new User()
u.metaClass.email = "alice@email.com"
println u.emailHow interviewers ask it“How would you explain interceptable for AOP to a junior engineer, and what do people most often get wrong?”
invokeMethod// 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()How interviewers ask it“How would you use JMX? Walk me through your approach.”
getAttribute// 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")How interviewers ask it“Explain @AutoExternalize in Groovy in detail — what should a new team member understand about it?”
// 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 d2How interviewers ask it“Explain @CompileStatic in Groovy in detail — what should a new team member understand about it?”
// Groovy with @CompileStatic
import groovy.transform.CompileStatic
@CompileStatic
def add(int a, int b) { a + b }
println add(3, 4)How interviewers ask it“Explain @TypeChecked in Groovy in detail — what should a new team member understand about it?”
// Groovy with @TypeChecked
import groovy.transform.TypeChecked
@TypeChecked
def multiply(int a, int b) { a * b }
println multiply(3, 4)How interviewers ask it“Walk me through @Memoized in Groovy. Where does it come up in real systems?”
// 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)How interviewers ask it“Walk me through @Newify in Groovy. Where does it come up in real systems?”
Person(name:"Alice")// 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.nameHow interviewers ask it“Walk me through @BaseScript in Groovy. Where does it come up in real systems?”
// 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"How interviewers ask it“How would you explain @Field to a junior engineer, and what do people most often get wrong?”
@Field int counter// Groovy with @Field (for class fields in scripts)
import groovy.transform.Field
@Field int counter = 0
def increment() { counter++ }
increment()
println counterHow interviewers ask it“How would you explain CliBuilder to a junior engineer, and what do people most often get wrong?”
options.optName// 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}"How interviewers ask it“Explain CompilerConfiguration in Groovy in detail — what should a new team member understand about it?”
// 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'")How interviewers ask it“How would you explain ObjectGraphBuilder to a junior engineer, and what do people most often get wrong?”
root { person(id:1) }// 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 }How interviewers ask it“Explain AntBuilder in Groovy in detail — what should a new team member understand about it?”
ant.echo(message: "Hello")// Groovy with AntBuilder
import groovy.util.AntBuilder
def ant = new AntBuilder()
ant.echo(message: "Hello from Ant")How interviewers ask it“How would you explain SwingBuilder to a junior engineer, and what do people most often get wrong?”
frame(title:'Test') { panel { label('Hello') } }// 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()How interviewers ask it“Suppose you need to use @Option for CLI in Groovy — how do you approach it, and what can go wrong?”
@Option(shortName='n') String namecli.parse(args)// 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'
}
// ...How interviewers ask it“How would you handle ZIP files? Walk me through your approach.”
withZipOutputStreamputNextEntrynew File("archive.zip").withZipOutputStream { ... }// 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"
}Multiple-choice questions with instant feedback. Takes about 10 minutes and shows exactly which concepts to revise.
Start the Groovy quiz →