Groovy is performing differently than Java In this code

176 views Asked by At

I had a look at this question here. The problem with this question is this line:

Integer i3 = (Integer) -128; /*** Doesn't compile ***/

As some of the answer's say's:

The compiler interprets the - as the two-arg minus operator, i.e. it's trying to subtract 128 from some other number named Integer, but there's no such variable in scope

The answers look correct for me. Now in groovy I tried the same code as such before :

Integer i3 = (Integer) -128; /*** compiles!!! ***/

even this code of line compiles:

Integer i3 = (Integer) -(128); /*** compiles ***/

How does Groovy performing this operation? Does all Jvm languages does this? Whats happening behind the scene's in case of Groovy.

Does this doesn't break Java rule? Bit confused.

For reference I have tagged the working Groovy code here

Thanks in advance.

3

There are 3 answers

0
Brian Roach On BEST ANSWER

Groovy isn't Java.

It doesn't have to follow Java's specification and in this case ... doesn't.

Edit for clarity: I think what's confusing you is that you don't understand that these are two different languages. Both the Groovy compiler and the Java compiler output bytecode from your source code which then runs on the JVM (Java Virtual Machine). The JLS (Java Language Specification) applies to the Java language only. Groovy does not have to adhere to it.

2
Ray Tayek On
Integer i3 = (Integer) -128;
println i3

compiles and runs under groovy 1.8

0
Dan On

How to interpret a minus sign in a piece of code is a function of the compiler, which implements a language definition. It really has no bearing on the runtime system in which the code will actually execute - in this case, the JVM. So different languages can have the same symbols/keywords etc. behave in different ways.