Categories

Nov 12, 2019 in DevOps

Q: Differences Between Java And Groovy?

1 Answer

Nov 12, 2019
Groovy tries to be as natural as possible for Java developers. Here are all the major

differences between Java and Groovy.

-Default imports

In Groovy all these packages and classes are imported by default, i.e. Developers do not

have to use an explicit import statement to use them:

java.io.*

java.lang.*

java.math.BigDecimal

java.math.BigInteger

java.net.*

java.util.*

groovy.lang.*

groovy.util.*

-Multi-methods

14/71

In Groovy, the methods which will be invoked are chosen at runtime. This is called runtime

dispatch or multi-methods. It means that the method will be chosen based on the types of

the arguments at runtime. In Java, this is the opposite: methods are chosen at compile

time, based on the declared types.

-Array initializers

In Groovy, the { … } block is reserved for closures. That means that you cannot create

array literals with this syntax:

int[] arraySyntex = { 6, 3, 1}

You actually have to use:

int[] arraySyntex = [1,2,3]

-ARM blocks

ARM (Automatic Resource Management) block from Java 7 are not supported in Groovy.

Instead, Groovy provides various methods relying on closures, which have the same effect

while being more idiomatic.

-GStrings

As double-quoted string literals are interpreted as GString values, Groovy may fail with

compile error or produce subtly different code if a class with String literal containing a

dollar character is compiled with Groovy and Java compiler.

While typically, Groovy will auto-cast between GString and String if an API declares

the type of a parameter, beware of Java APIs that accept an Object parameter and then

check the actual type.

-String and Character literals

Singly-quoted literals in Groovy are used for String , and double-quoted result

in String or GString , depending whether there is interpolation in the literal.

assert 'c'.getClass()==String

assert "c".getClass()==String

assert "c${1}".getClass() in GString

Groovy will automatically cast a single-character String to char only when assigning to

a variable of type char . When calling methods with arguments of type char we need to

either cast explicitly or make sure the value has been cast in advance
Click here to read more about DevOps
Click here to read more about Insurance

Related questions

Madanswer
Aug 8 in DevOps
Nov 12, 2019 in DevOps
Nov 12, 2019 in DevOps
...