Groovy Interview Questions and Answers

Groovy Interview Questions and Answers

Last updated on 13th Oct 2020, Blog, Interview Question

About author

Lakshana (Sr Technical Manager )

He is Highly Experienced in Respective Technical Domain with 6+ Years, Also He is a Respective Technical Trainer for Past 5 Years & Share's This Important Articles For us.

(5.0) | 16897 Ratings 2227

Groovy is an object-oriented programming language which is based on the Java platform. It is Java syntax compatible and is from the Apache family of software. It is both static and dynamic language and is similar to Python, Ruby or Perl. Groovy can be used both as a programming language and as a scripting language. It is compatible with JVM bytecode and communicates well with Java code and libraries. The syntax is similar to Java in terms that both use curly brackets. It supports functions such as closures, multiline strings formats and expressions embedded strings. Groovy’ s main power lies in AST transformations which are triggered through annotations.

Most of the valid Java files can also work with Groovy files. It is true that these two languages are similar but Groovy code is more compact, as it does not need many elements that Java needs. Because of this similarity, Groovy is easy to learn for Java programmers if they start with familiar Java syntax first and then keep on acquiring Groovy programming concepts and syntax.

1. What is Groovy?

Ans:

Groovy is an object-oriented programming language for JVM (Java Virtual Machines). It is used to combine Java modules, to write Java applications and to extend existing Java applications.

2. Why use Groovy?

Ans:

  • For Java programmers, it provides familiar syntax
  • It has a rich stock of Java Libraries
  • It easily integrates with your existing infrastructure like Servlet Containers, App Servers, Loads of databases with JDBC drivers,
  • Completely Object Oriented
  • It possesses reusable and assignable pieces of code
  • Operators can be overloaded
  • Literal declaration for maps, arrays, ranges, and regular expressions
  • It has efficient object navigation

3. What are the limitations of Groovy?

Ans:

  • Groovy can be slower
  • Groovy might need lots of memory
  • Groovy startup time requires improvement
  • It requires Java knowledge
  • It takes some time to get used to like New Syntax, closures, default typing,
  • Documentation is thin

4. How Scripts are run in Groovy?

Ans:

Groovy supports plain script; it does not require a class declaration. At the front of the script, imports are supported in the same way that they can be at the front of a class. In Groovy, you have to use word def to declare a function outside of a class.

5. What are some features Groovy JDK offers?

Ans:

Groovy has added new methods compare to an old version like

Various array types and object streams with newly Groovy oriented methods

like Object.every(), Object.each() etc. and also include new features like “String BufferedReader.getText()” and “InputStream.eachLine(Closure)”.

6. What is the role of closure and listeners in Groovy?

Ans:

Groovy does not support anonymous inner classes; it is possible to determine action listeners inline through the means of closures. In Groovy, listeners closure are used as a ListenerAdapter where only one method of interest is overridden.

7. How can you add stuff to the classpath when running things in groovy or groovy?

Ans:

You can add things to your $CLASSPATH environment variable. Another possibility is to build a .groovy/lib directory in your home directory and append whatever jars you want to be available by default.

8.What is the license for Groovy?

Ans:

Groovy depends at runtime on the ASM library as well as Java 1.4 and the Groovy jar.

9. What is ExpandoMetaClass in Groovy?

Ans:

ExpandoMetaClass is used to add methods, properties, static methods, and constructors. Expando class does not inherit by default; you have to call ExpandoMetaClass.enableGlobally().

10. How Groovy string is expressed?

Ans:

The groovy string is referred to as a G-string.

  • It is surrounded by double quotes, for regular strings it uses single quotes
  • It may contain Groovy Expressions noted in ${}
  • Square bracket syntax may be applied like charAt(i)

11. How could you retrieve a single value from the database using Groovy?

Ans:

To recover a single value from the database you can use the command

  • row = sql.firstRow (‘select columnA, column from tableName’)
  • println “Row: columnA = $ {row.columnA} and column = ${row.columnB}”

12. How can you query in Groovy?

Ans:

Let see a simple example of how Groovy calls out the query

  • import groovy.sql.sql
  • sql = Sql.newInstance (‘jdbc: jtds: sqlserver://serverName/dbName Class;domain=domainName’’username’’password’’net.sourceforge.jtds.jdbc.driver’)
  • sql.eachRow (‘select * from tableName’) {print “$it.id–${it.firstName} –“ }

13.How can you build AST (Abstract Syntax Trees) in Groovy from string?

Ans:

You can build AST in Groovy from

  • Strings
  • Code
  • From DSL like specification

An AstBuilder object provides an API to build AST from strings of Groovy Source Code. For example

  • List nodes = new AstBuilder (). buildFromString (“” Hello” “)

14. How can you include a groovy script in another groovy?

Ans:

You can include a groovy script with another groovy by using the following code. When putting this code at the top of the script it will bring in the contents of a groovy file.

  • Evaluate(new file(“../tools/Tools.groovy”))

15. What is Groovysh?

Ans:

Groovysh is a command line application that enables easy access to evaluate Groovy expressions, define classes and run experiments.

Subscribe For Free Demo

Error: Contact form not found.

16. Define GroovyDoc comment?

Ans:

Like multiline comments, GroovyDoc comments are multiline but it starts with a /** and ends with */. Those comments are related with

  • Type definitions (classes, interfaces, enums, annotations)
  • Fields and properties definitions
  • Methods definitions

17. What are Bitwise Operators in Groovy?

Ans:

Bitwise operators can be implemented on a BYTE or an INT and return an INT. Bitwise operators offer 4 bitwise operators

  • &: bitwise “and”
  • I: bitwise “or”
  • A: bitwise “xor”
  • ~: bitwise negation

18. Explain the differences between Groovy and Java?

Ans:

  • All the packages and classes in Groovy is imported by default, you do not have to use the import statement explicitly
  • Unlike Java where the methods are chosen at compile time, the methods in the Groovy are chosen based on the types of arguments at runtime
  • In {…} block is reserved for closures, which means that you cannot build array literals with this syntax
  • Like in Java, omitting a modifier on a field does not result in a package private field
  • Automatic Resource Management or ARM block from Java 7 are not supported in Groovy
  • Java 8 lambdas are more or less considered as anonymous inner classes, and Groovy does not support that syntax

19. Define the role of Grape dependency in Groovy?

Ans:

Grape is a JAR dependency manager included into Groovy. It allows you to quickly add maven repository dependencies to your classpath, making scripting easier. The simplest use is adding an annotation to your script.

20. What does the JsonSlurper class indicate?

Ans:

The JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as lists, maps, and primitive types like double, Boolean, string and Integer.

21. When “propertyMissing (String)” method is called?

Ans:

The “propertyMissing (String)” method is called when no getter method for a given property can be detected by the Groovy runtime.

22. Define What relational operators are used for in Groovy?

Ans:

Relational operators allow you to compare between objects, to check whether the two objects are different or same or if one is less than, greater than or equal to others.

23. What are Grails?

Ans:

Grails is an open source web application framework that uses Groovy and Java as a programming language, this framework uses another framework like Spring, Hibernate, SiteMesh and has an embedded H2 database, Tomcat server and ORM(GORM). this framework follows some design patterns like Model View Controller(MVC), Convention Over Configuration(CoC), Don’t repeat yourself(DRY) and runs over the Java Virtual Machine(JVM).

24. What is ORM?

Ans:

It means object-relational mapping, A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.

It’s a library or framework that help you to map/convert your models in to tables in your database, It’s like a mediator or an intermediate that avoid that you have to write SQL code and allows you to interact with the DB using a programming language like groovy without have to worry about writing SQL code or what kind of database are you using, you can switch from MySQL to Oracle DB modifying only 4 lines of code, an example of what is an ORM It’s the Hibernate Framework.

25. What is GORM?

Ans:

GORM is Grails’ object relational mapping (ORM) implementation. Under the hood, it uses Hibernate (a very popular and flexible open source ORM solution) and thanks to the dynamic nature of Groovy with its static and dynamic typing, along with the convention of Grails, there is far less configuration involved in creating Grails domain classes.

26. What is the command to create a new application in grails?

Ans:

  • grails create-app “the name of your app”

27. What is the command to run a grails application?

Ans:

  • grails run-app

28. What is the command to create a domain class?

Ans:

  • grails create-domain-class “package” +” name of your domain class”

29. What is the command to create a controller?

Ans:

  • grails create-controller “package” +” name of your domain class”

30. What are the default environments in grails?

Ans:

Development, Test And Production

Course Curriculum

Get Practical Oriented Groovy Training & Build Your Skills to Next Level

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

31. What is the command to generate a war file?

Ans:

grails war

32. What is the command to run your application in a different environment than development?

Ans:

  • grails -Dgrails.env=test run-app

33. What is the command to run your application in a different port than 8080?

Ans:

  • grails -Dserver.port=9090 run-app

34.What is the command to do static scaffolding of a controller?

Ans:

  • grails generate-controller “package”+” domain class”

35.What is the command to do static scaffolding of the view of a domain?

Ans:

  • grails generate-views “package”+” domain class”

36.What is the command to generate the static scaffolding of the controllers and views of a domain class?

Ans:

  • grails generate-all “package”+” domain class”

37.What is the command to generate the static scaffolding of the controllers and views of all your domain classes?

Ans:

  • grails generate-all “*”

38.What is the command to stop your application?

Ans:

  • grails stop-app

39.What is the command to test your application?

Ans:

  • grails test-app

40.What is the command to test your application for unit test only?

Ans:

  • grails test-app –unit

41.What is the command to test your application for integration test only?

Ans:

  • grails test-app –integration

42.What is the command to rerun a test in your application?

Ans:

  • grails test-app –rerun

43.What is the command to see your grails version?

Ans:

  • grails -version

44.What is the command to create the unit test of a domain class?

Ans:

  • grails create-unit-test “package”+” domain class”

45.What is the command to create the integration test of a domain class?

Ans:

  • grails create-integration-test “package”+” domain class”

46.What is data binding?

Ans:

It’s the act of binding incoming request parameters on to the properties of an object.

47.Where do you set up your DB, hibernate version and environments?

Ans:

DataSource.groovy

48.Where do you set up your dependency manager, your repositories, dependencies, and plugins?

Ans:

BuildConfing.groovy

49.What is the difference between BuildConfig.groovy and Config.groovy?

Ans:

Config includes configuration needed to run your application and BuildConfig includes configuration to build and deploy your application.

50.What do you have to do if you don’t want that a property of your domain is mapped to the DB?

Ans:

In your domain class:

static transient[can’t save this’]

Course Curriculum

Learn Hands-On Practical Groovy Programming Course By MNC Trainers

Weekday / Weekend BatchesSee Batch Details

51.What is metaprogramming?

Ans:

It’s the groovy ability to add new methods or variables to classes dynamically at run time, and without touching the code.

52.Could you give me an example of metaprogramming in grails?

Ans:

The dynamic finders in the domains class.

53.What type of looking is by default in grails optimistic or pessimist looking?

Ans:

Optimistic locking is a feature of Hibernate which involves storing a version value in a special version column in the database that is incremented after each update.

54.What is pessimistic locking?

Ans:

Locking a row until the current transaction is completed. This has the implication that other read operations will be blocking until the lock is released.

55.How do you use pessimist looking in a domain class?

Ans:

Call “.lock()” method on domain instance.

Example.

  • def airport = Airport.get(10)
  • airport.lock() // lock for update
  • airport.name = “Heathrow”
  • airport.save()
  • or defining in your domain class “version= false”

Example:

  • class Person {
  • static mapping = {
  • version false // here you disability optimist looking
  • autoTimestamp false
  • }
  • }

56.What method do you use to check if any field of an object has been modified.

Ans:

isDirty

getDirtyPropertyNames : to get names of modified fields.

57.What are the dynamic finders?

Ans:

They are the methods auto-generated by grails based on fields of the domain class.

  • Example. class Book {
  • String title
  • Date releaseDate
  • Author author
  • }
  • def book = Book.findByTitle(“The Stand”)
  • book = Book.findByTitleLike(“Harry Pot%”)
  • Associations in GORM are by default lazy or eager?
  • lazy

58.How do you Configure Eager Fetching in a domain class?

Ans:

using:

lazy: false

or

fetch: ‘join’

Example:

  • class Airport {
  • String name
  • static hasMany = [flights: Flight]
  • static mapping = {
  • flights lazy: false //here you configure eager fetching
  • }
  • }
  • class Person {
  • String firstName
  • Pet pet
  • static hasMany = [addresses: Address]
  • static mapping = {
  • addresses lazy: false
  • pet fetch: ‘join’ //this is another way to configure eager fetching
  • }
  • }

59.What is the configuration file to define the URL pattern and its controller and action name?

Ans:

  • grails-app/conf/UrlMappings.groovy.

60.How do you secure your grails application?

Ans:

Use Grails Filter

61.How can I turn on logging for hibernating in order to see SQL statements, input parameters, and output results?

Ans:

Edit your Config.groovy file. Find the line with:

hibernate = “off”

and replace it with:

hibernate.SQL=” trace, stdout”

hibernate.type=”trace,stdout”

62.How do you render a domain object as XML or JSON?

Ans:

render Book.list(object) as JSON

render Book.get(object) as XML

63.How do you access servlet attributes from the controller?

Ans:

servletContext

servletContext is available in the controller.

64.What is a javascript tag in GSP?

Ans:

Includes JavaScript libraries and scripts as well as providing a shorthand for inline JavaScript.

65.What is the name of the config file to define database connection properties?

Ans:

  • grails-app/conf/DataSource.groovy.

66.What is the command to refresh dependencies?

Ans:

grails refresh-dependencies

67.What option do you use to create a war file for a specific environment?

Ans:

  • -Dgrails.env

Example :

  • grails -Dgrails.env=dev war

By default services in grail is singleton or prototype

Singleton.

68.What is the command to create a service in grails?

Ans:

  • grails create-service “package”+” service name”

69.What is the command to create a tag library in grails?

Ans:

  • grails create-tag-library+ “package”+” name”

70.What are the closures in groovy?

Ans:

A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable

Groovy Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

71.How do you inject a service in your controller?

Ans:

def taskService

72.How to render a template in a view in grails?

Ans:

use the tag:

73.How can you load preload data when startup your application?

Ans:

using Boostrap.groovy

74.How to use dynamic scaffolding in your app?

Ans:

In your controller:

def scaffold=true or def scaffold=” the name of your domain class”

75.What is a template in grails?

Ans:

It’s a reusable part of a view that can be used to render a small part of a view.

76.What is a grails plugin?

Ans:

It’s a bundle/set of functionality to the desired purpose that can be installed in your grails application.

77.How can you use a tag library in your view?

Ans:

<g:” your tag library name” />

78.What is the command to compile your grails application?

Ans:

grails compile

79.What is the difference between User.findByName() and User.findAllByName() in the dynamic finders?

Ans:

That Findbyname Return The First Result And Findallbyname Return A List With All The Results

80.How can you map directly a domain class to a specific table in your DB?

Ans:

In your domain class:

  • class Person {
  • static mapping = {
  • table ‘people’///this is the mapping of the domain in the table
  • }
  • }

81.How can you map directly a property of a domain class to a specific column in the table of your DB?

Ans:

  • class Person {
  • String firstName
  • static mapping = {
  • table ‘people’
  • firstName column: ‘First_Name’ ///this is the mapping of the column in the table
  • }
  • }

82.What is SiteMesh?

Ans:

It’s an HTML templating framework

83.How you can validate your domain classes against invalid data?

Ans:

using: static constraints{ }

84.How can you have control over the way grails mapping the URLs in your application?

Ans:

in “conf/UrlMappings.groovy” you can customize how grails map the URLs in your application

85.What is the command to run your app in a custom environment?

Ans:

  • grails -Dgrails.env=” your custom environment” run-app

86.How can you use a namespace different from “g: ” to render your tag library in your views?

Ans:

using the line in your tag library:

static namespace = “your custom namespace”

87.What are the different options to “dbCreate” inside a data source of an environment?

Ans:

‘create’, ‘create-drop’, ‘update’, ‘validate’ and ‘ null ‘

88.What happens with the DB if you have ‘create’ in the option “dbCreate” of your data source?

Ans:

Drops the existing schemaCreates the schema on startup, dropping existing tables, indexes, etc. first.

89.What happens with the DB if you have ‘create-drop’ in the option “dbCreate” of your data source?

Ans:

Same as create, but also drops the tables when the application shuts down cleanly.

90.What happens with the DB if you have ‘update’ in the option “dbCreate” of your data source?

Ans:

Creates missing tables and indexes, and updates the current schema without dropping any tables or data. Note that this can’t properly handle many schema changes like column renames (you’re left with the old column containing the existing data).

91.What happens with the DB if you have ‘validate’ in the option “dbCreate” of your data source?

Ans:

Makes no changes to your database. Compares the configuration with the existing database schema and reports warnings.

92.What happens with the DB if you have ‘nothing/null’ in the option “dbCreate” of your data source?

Ans:

Does nothing with your database

93.What is a new scope available in the grails services which makes sure that a new service will be created for the current and next request only?

Ans:

Flash

94.What annotation is used for unit testing of grails controllers?

Ans:

grails.test.mixin.TestFor

95.How can you create a One-to-many relationship in GORM?

Ans:

We can use static hasMany property at the “one” side:

  • class User {
  • static hasMany = [articles: Article]
  • }
  • class Article {
  • }

96.How can you create a bidirectional relationship in GORM?

Ans:

using:

static belongsTo = User

example:

  • class User {
  • static hasMany = [articles: Article]
  • }
  • class Article {
  • static belongsTo = User
  • }

97.How can you create a One-to-One relationship in GORM?

Ans:

There are two ways of specifying a one-to-one relationship:

First Add an article property and the unique constraint to the User domain:

  • class User {
  • Article article
  • static constraints = {
  • article unique: true
  • }
  • }
  • class Article {
  • static belongsTo = [user: User]
  • }

Second use the hasOne property on the owning (User) side:

  • class User {
  • static hasOne = [article: Article]
  • }
  • class Article {
  • static belongsTo = [user: User]
  • }

98.How can you create a Many-to-Many relationship in Gorm?

Ans:

Many-to-many relationships in Grails can be specified by defining a hasMany property on both sides and having a belongsTo on the owned side:

  • class Tag {
  • static belongsTo = Post
  • static hasMany = [posts: Post]
  • }
  • class Post {
  • static hasMany = [tags: Tag]
  • }

99.What is the use of flush option in safe operation of a domain?

Ans:

Saves the row immediately without any delay.

Example

  • def book = new Book(title:” New Grails Book”)
  • book.save(flush:true)

100.How can you install a plug-in in your grails application?

Ans:

You have to write your plugin inside the plugins Block/closure {} in the BuildConfig.groovy file and you have to specify if your plugin works at run time or compilation time.

Example:

  • plugins {
  • build “:tomcat:7.0.55”
  • compile “:scaffolding:2.1.2”
  • runtime “:jquery:1.11.1”
  • }

101.How can you make all the methods of a service in grails be transactional?

Ans:

With the annotation @Transactional above the class’s name

Example:

  • import grails.transaction.*
  • @Transactional
  • class CountryService {
  • }

102.How can you make a method of a service be transactional?

Ans:

With the annotation @Transactional above the method’s name of the service

Example:

  • import grails.transaction.Transactional
  • class BookService {
  • @Transactional
  • def updateBook() {
  • // …
  • }
  • }

103.How can you make a method not transactional if the whole class was marked as transactional?

Ans:

Using the annotation @NotTransactional above the method’s name in the service

Example:

  • import grails.transaction.Transactional
  • @Transactional
  • class BookService {
  • @NotTransactional
  • def listBooks() {
  • Book.list()
  • }
  • }

104.What is another way to make a transaction method that does not use the @Transactional annotation in grails?

Ans:

Using the “.withTransaction” method

Example:

  • Account.withTransaction { status ->
  • def source = Account.get(params.from)
  • def dest = Account.get(params.to)
  • int amount = params.amount.toInteger()
  • if (source.active) {
  • source.balance -= amount
  • if (dest.active) {
  • dest.amount += amount
  • }
  • else {
  • status.setRollbackOnly()
  • }
  • }
  • }

Are you looking training with Right Jobs?

Contact Us

Popular Courses