[Monthly 2017/04] Introduction to groovy !! ~ Java grammar / specification comparison ~

Introduction! !!

Yeah! !! Is it no? ?? !! !! ?? !! !! !! !! With that said, I would like to continue learning groovy. (So?) Well, I'm a beginner, so please take a good look at the rudimentary content ww! !! (This is the end of the strange tension ...)

The motivation for learning is to improve Java activity in the future. I want to feel free to try out the library and make tools.

Well, if you do it, you want to do everything from the basics, so this time's content is mostly grasping the language specifications of groovy.

It's my first post, so I'm not very good at it (and I'm fooling around ...) I hope it can be read somehow.

Hello World!!

The introduction is Hello World. First of all, we will start the comparison from here. See Hello World in both languages below.

java


public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello java!!");
    }
}

/*output
Hello java!!
*/

groovy


System.out.println("Hello groovy!!"); //Same as java. But it works.
System.out.println("Hello groovy!!")  //Works without a semicolon.
System.out.println "Hello groovy!!";  // ()Let's stop putting it on.
System.out.println "Hello groovy!!"   // ;Let's stop by the way.
println "Hello groovy!!"              // The groovy.It can be simplified so much.

/*output
Hello groovy!!
Hello groovy!!
Hello groovy!!
Hello groovy!!
Hello groovy!!
*/

You can see the groovy feeling (* I want to call it freedom) just by doing this. There are many ways to write just the output with the println method. What I personally like is that you don't have to write System.out. This alone makes the code look neat.

On the contrary, in java, I can't think of any other way of writing. It may be easier to maintain in a project with a large number of people, Groovy is a good choice for hobbies and creating simple tools.

Type declaration

From here, we will compare variables. Since it is troublesome to output with println one by one, define disp () that outputs variables in the form of [type: value]. Read the code assuming that disp () is defined.

java


/**
 * [Mold:value]Output arguments in the format of
 *
 * @param variable variable
 */
static void disp(Object variable) {
   System.out.println("[ " + variable.getClass().toString() + " : " + variable.toString() + " ]");
}

groovy


/**
 * [Mold:value]Output arguments in the format of
 *
 * @param variable variable
 */
def disp(variable) {
    println "[ " + variable.class.toString() + " : ${variable} ]"
}

Oh, groovy is easy to write ...

String

java


public class Variable {
    public static void main(String[] args) {

        String jString = "java string";

        disp(jString);
    }
}

/*output
 * [ class java.lang.String : java string ]
 */

groovy


def gString = "groovy string"   //Declared with def
def gString2 = "${gString}"     //Declared with def. In the string${variable}Embed

String jString = "java string"  //Declared as String type
String jString2 = "${jString}"  //Declared as a String type. In the string${variable}Embed

def gString3 = """\
First line
Second line
Third line"""                       // """Enclose in and represent a multi-line character string.\Line breaks can be escaped with

def gString4 = 'groovy string' // 'It is OK to enclose it in

disp gString
disp gString2
disp jString
disp jString2

disp gString3
disp gString4

/*output
 * [ class java.lang.String : groovy string ]
 * [ class org.codehaus.groovy.runtime.GStringImpl : groovy string ]
 * [ class java.lang.String : java string ]
 * [ class java.lang.String : java string ]
 * [ class java.lang.String :First line
 *Second line
 *Third line]
 * [ class java.lang.String : groovy string ]
 */

What I want to pay attention to in the String type is the behavior when $ {variable} is embedded in the value string. Groovy expands the value of $ {variable} enclosed in " into a string, but the behavior changes depending on how it is declared.

As an aside, there is a notation for lazy evaluation. If you give $ {-> variable} as a value in the case of declaration by def, even if the reference destination of the variable changes, the change of the reference can be reflected. In this case it has the value of $ {variable} as a closure. Since the value of the variable returned by the closure is expanded at the time of display, the value can be reflected even if the reference destination changes.

Example


def string = ["groovy string"]

String gStringValue = "${string}"     //Value embedding
def gStringReference = "${string}"    //reference
def gStringLazy = "${-> string}"      //Lazy evaluation

string.add "changed"

disp gStringValue
disp gStringReference
disp gStringLazy
println()

string = "replaced"

disp gStringValue
disp gStringReference
disp gStringLazy

/*output
 * [ class java.lang.String : [groovy string] ]
 * [ class org.codehaus.groovy.runtime.GStringImpl : [groovy string, changed] ]
 * [ class org.codehaus.groovy.runtime.GStringImpl : [groovy string, changed] ]
 * 
 * [ class java.lang.String : [groovy string] ]
 * [ class org.codehaus.groovy.runtime.GStringImpl : [groovy string, changed] ]
 * [ class org.codehaus.groovy.runtime.GStringImpl : replaced ]
 */

The above behavior is shown as a character string type implementation when referencing variables and performing lazy evaluation so that it can be read from the output result. This is because ʻorg.codehaus.groovy.runtime.GStringImpl` is used. It is a very convenient function if you can master it.

Numerical value

java


public class Variable {
    public static void main(String[] args) {

        int jInt = 1;                                                            // int
        long jLong = 100000000000000L;                                           //Is it volume?
        BigInteger jBigInteger = new BigInteger("1000000000000000000000000000"); //This is probably the easiest

        disp(jInt);
        disp(jLong);
        disp(jBigInteger);

        double jDouble = 1.212121;                            // double
        float jFloat = 1.212121F;                             //Is it capacitance?
        BigDecimal jBigDecimal = new BigDecimal(1.212121);    //If you pass it with a small number, you will get a tail
        BigDecimal jBigDecimal2 = new BigDecimal("1.212121"); //This is probably the easiest

        disp(jDouble);
        disp(jFloat);
        disp(jBigDecimal);
        disp(jBigDecimal2);
    }
}

/*output
 * [ class java.lang.Integer : 1 ]
 * [ class java.lang.Long : 100000000000000 ]
 * [ class java.math.BigInteger : 1000000000000000000000000000 ]
 * 
 * [ class java.lang.Double : 1.212121 ]
 * [ class java.lang.Float : 1.212121 ]
 * [ class java.math.BigDecimal : 1.2121210000000000039932501749717630445957183837890625 ]
 * [ class java.math.BigDecimal : 1.212121 ]
 */

groovy


def gInt = 1                                    //Fits in int
def gLong = 100000000000000                     //int doesn't fit
def gBigInteger = 1000000000000000000000000000  //Doesn't even fit in Long

disp gInt
disp gLong
disp gBigInteger
println()

def gBigDecimal = 2.121212                     //Try to put a few
double jDouble = 2.121212                      //Declared with double
float jFloat = 2.121212                        //Declared with float

disp gBigDecimal
disp jDouble
disp jFloat

/*output
 * [ class java.lang.Integer : 1 ]
 * [ class java.lang.Long : 100000000000000 ]
 * [ class java.math.BigInteger : 1000000000000000000000000000 ]
 *
 * [ class java.math.BigDecimal : 2.121212 ]
 * [ class java.lang.Double : 2.121212 ]
 * [ class java.lang.Float : 2.121212 ]
 */

Groovy is pretty good when dealing with numbers. As in the above code, in the case of an integer value, the types from ʻinttoBigIntegerare automatically determined and handled according to the assigned value. If it is a minority value, it will be treated asBigDecimal`. It is also attractive that even if you pass a small number value as it is, there is no error tail like java. Of course, if you specify the type, it will be treated as the specified type.

Other primitive types

java


public class Variable {
    public static void main(String[] args) {

        char aznable = 'c';    //Red Comet
        disp(aznable);

        boolean jBool = true; //boolean type
        disp(jBool);
    }
}

/*output
 * [ class java.lang.Character : c ]
 * [ class java.lang.Boolean : true ]
 */

groovy


def gChar = 'c'
def gChar2 = 'c' as char
def gChar3 = 'c' as String
char gChar4 = 'c'

disp gChar
disp gChar2
disp gChar3
disp gChar4

/*output
 * [ class java.lang.String : c ]
 * [ class java.lang.Character : c ]
 * [ class java.lang.String : c ]
 * [ class java.lang.Character : c ]
 */


def gBool = true
def gBool2 = "true" as boolean
boolean gBool3 = true
boolean gBool4 = "true"

disp gBool
disp gBool2
disp gBool3
disp gBool4

/*output
 * [ class java.lang.Boolean : true ]
 * [ class java.lang.Boolean : true ]
 * [ class java.lang.Boolean : true ]
 * [ class java.lang.Boolean : true ]
 */

char There is no char type literal (value) notation in groovy. If you want to treat a character as a char type, you need to assign the String literal to a variable declared as a char type, or specify it as a char type with the ʻaskeyword. Also, although not in the above code, you can cast it with (char) and treat it as achar` type.

boolean For boolean, follow the code above. (It's not omission. I have nothing to write)

List & Array & Range

From here on, it's getting annoying, so if you don't need to compare it, I'll post only the groovy code. "Isn't it a big deal until now? Don't say that. Below is a sample.

groovy


def list = [1, 2, 3]
def linkedList = [1, 2, 3] as LinkedList
LinkedList linkedList2 = [1, 2, 3]

def array = [1, 2, 3] as int[]

def range = 1..3

disp list
disp linkedList
disp linkedList2
disp list[0]
println()
disp array
disp array[0]
println()
disp range
disp range[0]

/*output
 * [ class java.util.ArrayList : [1, 2, 3] ]
 * [ class java.util.LinkedList : [1, 2, 3] ]
 * [ class java.util.LinkedList : [1, 2, 3] ]
 * [ class java.lang.Integer : 1 ]
 *
 * [ class [I : [1, 2, 3] ]
 * [ class java.lang.Integer : 1 ]
 *
 * [ class groovy.lang.IntRange : [1, 2, 3] ]
 * [ class java.lang.Integer : 1 ]
 */

Both List array and Range can get elements with the same syntax. Easy. However, the class name of the array seems to be messy. By the way, the class of the int array was [I, the boolean array was [Z, and the String was [Ljava.lang.String;. It's kind of unpleasant ...

Map

groovy


def map = [ name : "Ponta", age : 20, attend : true]
def hashMap = [ name : "Ponta", age : 20, attend : true] as HashMap
TreeMap treeMap = [ name : "Ponta", age : 20, attend : true]

disp map
disp hashMap
disp treeMap
println()
println map.getClass()
println hashMap.getClass()
println treeMap.getClass()
println()
disp map.name
disp map.age
disp map.attend
println()
disp map["name"]
disp map."name"

/*output
 * [ null : [name:Ponta, age:20, attend:true] ]
 * [ null : [name:Ponta, age:20, attend:true] ]
 * [ null : [age:20, attend:true, name:Ponta] ]
 *
 * class java.util.LinkedHashMap
 * class java.util.LinkedHashMap
 * class java.util.TreeMap
 *
 * [ class java.lang.String :Ponta]
 * [ class java.lang.Integer : 20 ]
 * [ class java.lang.Boolean : true ]
 *
 * [ class java.lang.String :Ponta]
 * [ class java.lang.String :Ponta]
 * [ class java.util.ArrayList : [true, 12, string] ]
 * [ class java.lang.Boolean : true ]
 * [ class java.lang.Integer : 12 ]
 * [ class java.lang.String : string ]
 */

The moment I saw the output, I was most surprised. Because the class is null. I thought this was definitely a bug, but when I looked it up, it was a specification. To explain this, we need to know the specifications of two groovy.

It seems that this misfortune was caused by resolving the above specification conflict by giving priority to the latter. (Null is returned when accessing a non-existent key) I was able to get the class by calling getClass () properly. ~~ All ** LinkedHashMap **, but ... Is it a language specification? I didn't really understand here ... ~~ The above was due to a variable error to be displayed (all map or embarrassing) Thank you, @uehaj.

As an aside, groovy can also access fields etc. in the form of map." Name ". If you combine it with $ {variable}, you can do light black magic.

Summary

** java is a statically typed language ** and ** groovy is a dynamically typed language **. java must specify the type of the variable when declaring the variable, groovy is OK with def. If you declare a variable with def, the type changes dynamically depending on the literal (value) stored in the variable. However, groovy also allows you to statically declare types. In addition, as in the String example, groovy provides fairly flexible dynamic typing, such as how to write literals.

Verification environment

Groovy-2.4.10 jdk1.8.0_60 IntelliJ IDEA Community Edition 2017.1.2

Reference site

http://groovy-lang.org https://www.slideshare.net/nobeans/javagroovy http://npnl.hatenablog.jp/entry/20100605/1275736594 http://qiita.com/abey1192/items/661766fb728fd9b872e2 http://qiita.com/opengl-8080/items/46790e2292cdd0beb1af

P.S It doesn't matter at all, but IntelliJ IDEA was messed up and easy to use.

Recommended Posts

[Monthly 2017/04] Introduction to groovy !! ~ Java grammar / specification comparison ~
[Java] Introduction to Java
Introduction to java
Introduction to java command
An introduction to Groovy for tedious Java engineers
[Java] Introduction to lambda expressions
[Java] Introduction to Stream API
[Introduction to rock-paper-scissors games] Java
[Introduction to Java] About lambda expressions
[Introduction to Java] About Stream API
Introduction to Functional Programming (Java, Javascript)
Initial introduction to Mac (Java engineer)
Introduction to java for the first time # 2
Introduction to Ruby basic grammar with yakiniku
Introduction to algorithms with java --Search (depth-first search)
[Introduction to Java] How to write a Java program
Output of the book "Introduction to Java"
[Java] Introduction
Introduction to monitoring from Java Touching Prometheus
[Introduction to Java] Variable declarations and types
Introduction to Java Web Apps Performance Troubleshooting
Introduction to algorithms with java --Search (breadth-first search)
[Introduction to Java] About type conversion (cast, promotion)
Introduction to algorithms with java --Search (bit full search)
Road to Java Engineer Part1 Introduction & Environment Construction
[Introduction to Java] Basics of java arithmetic (for beginners)
Introduction to Ruby 2
Java basic grammar
Java basic grammar
Introduction to web3j
Introduction to Micronaut 1 ~ Introduction ~
[Java] Map comparison
Java framework comparison
Java basic grammar
Introduction to migration
Java basic grammar
Introduction to Doma
Java specification memo
Introduction to Java for beginners Basic knowledge of Java language ①
[Introduction to Java] Variable scope (scope, local variables, instance variables, static variables)