100 Top Groovy Job Interview Questions and Answers

Groovy Interview Questions with answers::-

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

2. Why use Groovy?

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

3. Define What is the limitation of Groovy?

  • 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?
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 does Groovy JDK offers?
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?
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 you can add stuff to the classpath when running things in groovy or groovy?
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. Define What is the license for Groovy?
Groovy depend at runtime on the ASM library as well as Java 1.4 and the Groovy jar.

9. What is ExpandoMetaClass in Groovy?
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?
The groovy string is referred to 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)

GROOVY Questions pdf free download::

11. How could you retrieve a single value from the database using Groovy?
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 you can query in Groovy?
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. Define How you can build AST (Abstract Syntax Trees) in Groovy from string?
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 you can include a groovy script in another groovy?
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?
Groovysh is a command line application that enables easy access to evaluate Groovy expressions, define classes and run experiments.

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

  1. Type definitions (classes, interfaces, enums, annotations)
  2. Fields and properties definitions
  3. Methods definitions

17. What are Bitwise Operators in Groovy?
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?

  • 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?
Grape is a JAR dependency manager included into Groovy. It allows you to add quickly 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?
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?
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?
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.

GROOVY Faqs::

GROOVY ON GRAILS INTERVIEW QUESTIONS FOR INTERVIEWERS:-

1. what is Grails?
Grails is an open source web application framework that uses the Groovy and Java as a programming language, this framework use another framework like Spring, Hibernate, SiteMesh and have 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).

2. What is ORM?
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.

3. What is Gorm?
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.

4. what is the command to create a new application in grails?
grails create-app “the name of your app”

5. what is the command to run a grails application?
grails run-app

6. what is the command to create a domain class?
grails create-domain-class “package” +” name of your domain class”

7. what is the command to create a controller?
grails create-controller “package” +” name of your domain class”

8. what are the default environments in grails?
Development, Test And Production

9. what is the command to generate a war file?
grails war

10. what is the command to run your application in a different environment that development?
grails -Dgrails.env=test run-app

what is the command to run your application in a different port than 8080?
grails -Dserver.port=9090 run-app

what is the command to do static scaffolding of a controller?
grails generate-controller “package”+” domain class”

what is the command to do static scaffolding of the view of a domain?
grails generate-views “package”+” domain class”

what is the command to generate the static scaffolding of the controllers and views of a domain class?
grails generate-all “package”+” domain class”

what is the command to generate the static scaffolding of the controllers and views of all your domain classes?
grails generate-all “*”

what is the command to stop your application?
grails stop-app

what is the command to test your application?
grails test-app

what is the command to test your application for unit test only?
grails test-app –unit

what is the command to test your application for integration test only?
grails test-app –integration

what is the command to rerun test in your application?
grails test-app –rerun

what is the command to see your grails version?
grails -version

what is the command to create the unit test of a domain class?
grails create-unit-test “package”+” domain class”

what is the command to create the integration test of a domain class?
grails create-integration-test “package”+” domain class”

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

where do you set up your DB, hibernate version and environments?
DataSource.groovy

where do you set up your dependency manager, your repositories, dependencies, and plugins?
BuildConfing.groovy

what is the difference between BuildConfig.groovy and Config.groovy?
that Config includes configuration needed to run your application and BuildConfig include configuration to build and deploy your application.

what do you have to do if you don’t want that a property of your domain is mapped to the DB?
in your domain class:
static transient[cant save this’]

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

could you give me an example of metaprogramming in grails?
The dynamic finders in the domains class.

what type of looking is by default in grails optimistic or pessimist looking?
optimistic looking
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.

What is pessimistic locking?
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.

how do you use pessimist looking in a domain class?

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
}
}

What method do you use to check if any field of an object has been modified.
isDirty
getDirtyPropertyNames : to get names of modified fields.

What are the dynamic finders?
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
how do you Configuring Eager Fetching in a domain class?
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
}
}

What is the configuration file to define URL pattern and its controller and action name?
grails-app/conf/UrlMappings.groovy.

How do you secure your grails application?
Use Grails Filter

How can I turn on logging for hibernating in order to see SQL statements, input parameters, and output results?
Edit your Config.groovy file. Find the line with:
hibernate = “off”

and replace it with:
hibernate.SQL=” trace, stdout”
hibernate.type=”trace,stdout”

How do you render a domain object as XML or JSON?
render Book.list(object) as JSON
render Book.get(object) as XML

How do you access servlet attributes from the controller?
servletContext
servletContext is available in controller.

What is a javascript tag in GSP?
Includes JavaScript libraries and scripts as well as providing a shorthand for inline JavaScript.

What is the name of the config file to define database connection properties?
grails-app/conf/DataSource.groovy.

What is the command to refresh dependencies?
grails refresh-dependencies

What option do you use to create a war file for a specific environment?
-Dgrails.env
Example : grails -Dgrails.env=dev war

By default services in grail is singleton or prototype
Singleton.

what is the command to create a service in grails?
grails create-service “package”+” service name”

what is the command to create a tag library in grails?
grails create-tag-library+ “package”+” name”

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

how do you inject a service in your controller?
def taskService

how render a template in a view in grails?

use the tag:

how you can load preload data when startup your application?
using Boostrap.groovy

how to use dynamic scaffolding in your app?

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

what is a template in grails?
it’s a reusable part of a view that can be used to render a small part of a view.

what is a grails plugin?
it’s a bundle/set of functionality to the desired propose that can be installed in your grails application.

how you can use a tag library in your view?
<g:” your tag library name” />

what is the command to compile your grails application?
grails compile

what is the difference between User.findByName() and User.findAllByName() in the dynamic finders?
That Findbyname Return The First Result And Findallbyname Return A List With All The Results

how you can map directly a domain class to a specific table in your DB?
in your domain class:
class Person {

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

how you can map directly a property of a domain class to a specific column in the table of your DB?
class Person {
String firstName
static mapping = {
table ‘people’
firstName column: ‘First_Name’ ///this is the mapping of the column in the table
}
}

what is SiteMesh?
It’s an HTML templating framework

how you can validate your domain classes against invalid data?
using: static constraints{ }

how you can have control over the way grails mapping the URLs in your application?
in “conf/UrlMappings.groovy” you can customize how grails map the URLs in your application

what is the command to run your app in a custom environment?
grails -Dgrails.env=” your custom environment” run-app

how you can use a namespace different than “g: ” to render your tag library in your views?
using the line in your tag library:
static namespace = “your custom namespace”

what are the different options to “dbCreate” inside a data source of an environment?
‘create’, ‘create-drop’, ‘update’, ‘validate’ and ‘ null ‘

what happens with the DB if you have ‘create’ in the option “dbCreate” of your data source?
Drops the existing schemaCreates the schema on startup, dropping existing tables, indexes, etc. first.

what happens with the DB if you have ‘create-drop’ in the option “dbCreate” of your data source?
Same as create, but also drops the tables when the application shuts down cleanly.

what happens with the DB if you have ‘update’ in the option “dbCreate” of your data source?
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).

what happens with the DB if you have ‘validate’ in the option “dbCreate” of your data source?
Makes no changes to your database. Compares the configuration with the existing database schema and reports warnings.

what happens with the DB if you have ‘nothing/null’ in the option “dbCreate” of your data source?
Does nothing with your database

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?
Flash

What annotation is used for unit testing of grails controller
grails.test.mixin.TestFor

how you can create a One-to-many relationship in GORM?

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

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

class Article {
}

how you can create a bidirectional relationships in GORM?
using:
static belongsTo = User

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

how you can create One-to-One relationship in GORM?

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]
}

how you can create Many-to-Many relationship in Gorm?
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]
}

What is the use of flush option in safe operation of a domain?
Saves the row immediately without any delay.
Example

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

how can you install a plug-in in your grails application?
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”
}

How can you made a all the method of a service in grails be transactional?
with the anotation @Transactional above the class’s name

Example:
import grails.transaction.*

@Transactional
class CountryService {

}

how you can made a method of a service be transactional?
with the anotation @Transactional above the method’s name of the service

Example:
import grails.transaction.Transactional

class BookService {

@Transactional
def updateBook() {
// …
}

}

how you can make a method not transactional if the whole class was marked as transactional?
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()
}
}

What is another way to make a transaction method that not use the @Transactional annotation in grails?
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()
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Comment

Name *

Website

 

© 2017 Interview Questions and Answers – Tutorials – Developed by Interview Questions Tutorials