An introduction to Groovy for tedious Java engineers

table of contents

--What is Groovy? --Characteristics of Groovy --Advantages of Groovy --Disadvantages of Groovy


What is Groovy

** Dynamically typed scripting language that runs on the JVM **


Features of Groovy

Why target "troublesome" "Java engineers" ...

That's because Groovy has the following advantages.

** 1. Less code than Java ** 2. Java API is also available 3. Rich ecosystem (Grails, web application framework, Spock, testing framework, etc.)


Groovy Benefits-Less code volume compared to Java

--Variable declaration / method declaration

Variable declaration is possible with def (type can be specified) When declared with def, the variable type is ʻObject type publicpublic` is not required when declaring a method (because the method scope is public by default)

Java


String helloWorld = "Hello World.";

public static void main(String[] args) {
    // do something
}

Groovy


def helloWorld = "Hello World."

//public can be omitted
static void main(String[] args) {
    // do something
}

//The return type can be def
static def main(String[] args) {
    //do something
}

//Return type can be omitted
static main(String[] args) {
    //do something
}

//Argument type can also be omitted
static main(args) {
    //do something
}

--String

You can embed a variable in a string in the form of a $ variable

Java


String name = "Michael";
System.out.println("Hello " + name + "!");

//Output result
// Hello Michael!

Groovy


def name = "Michael"
println "Hello $name!"

//Output result
// Hello Michael!

--Initialization of List and Map

List initialization is [] Map initialization is [:]

Java


List<String> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();

Groovy


def list = []
def map = [:] //Type will be LinkedhashMap

--Collection operation

Closure is convenient ʻItis an implicit variable that represents the arguments passed to the closure (in the example below, each element of thenumbers` list)

Java


List<Integer> numbers = List.of(1, 2, 3, 4, 5);
List<Integer> odds = numbers.stream().filter(number -> number % 2 != 0).collect(Collectors.toList());
System.out.println(odds);

//Output result
// [1, 3, 5]

Groovy


def numbers = [1, 2, 3, 4, 5] 
def odds = numbers.findAll { it % 2 != 0 } 
//This way of writing is also OK
// def odds = numbers.findAll { number -> number % 2 != 0 }
println odds

//Output result
// [1, 3, 5]

--DB operation (MySQL)

You can get the library from an external repository (such as Maven repository) using a configuration management tool called Grape with @ Grab The groovy.sql.Sql class is useful

person table

person_id first_name last_name
1 Michael Jordan
2 Michael Jackson

Java


// mysql-connector-Download java and add it to your classpath

Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sampledb", "root", "root");
// first_The last record whose name is Michael_Get name
PreparedStatement pstmt = conn.prepareStatement("SELECT last_name FROM person WHERE first_name = ?");
pstmt.setString(1, "Michael");
ResultSet rs = pstmt.executeQuery();
//Last of the acquired record_Output name to console
while(rs.next()) {
    System.out.println(rs.getString("last_name"));
}

//Output result
// "Jordan"
// "Jackson"

Groovy


//Mysql from external repository using Grape-connector-get java
@GrabConfig(systemClassLoader=true)
@Grab("mysql:mysql-connector-java:5.1.49")

def sql = Sql.newInstance("jdbc:mysql://localhost:3306/sampledb", "root", "root", "com.mysql.jdbc.Driver")
// first_The last record whose name is Michael_Get name
def rows = sql.rows("SELECT last_name FROM person WHERE first_name = ?", ["Michael"])
//Last of the acquired record_Output name to console
rows.each {
    println it.last_name
}

//Output result
// "Jordan"
// "Jackson"

Disadvantages of Groovy

--Type checking is not possible at compile time

Since it is a dynamically typed language, the type is not declared, and the variables and closure arguments declared with def are type-checked at runtime, so errors caused by the type are not pointed out until runtime.

--Some versions do not support some Java syntax

Some syntaxes such as try-with-resource statements and lambda expressions are not supported in system 2. These are also supported in version 3 series, but since it was released in February of this year, there is a possibility that the latest version also uses 2.5 series for frameworks and libraries that use Groovy.


in conclusion

Groovy requires less code than Java and can be expected to improve development efficiency. Also, learning costs are low for Java engineers and it won't take long to learn. (I also learned it in about 3 months.) If you find your Java code verbose or want to develop it more efficiently, why not give Groovy a try?


Recommended Posts

An introduction to Groovy for tedious Java engineers
[Java] Introduction to Java
Introduction to java
Introduction to java for the first time # 2
[Monthly 2017/04] Introduction to groovy !! ~ Java grammar / specification comparison ~
Introduction to java command
[Introduction to Java] Basics of java arithmetic (for beginners)
Introduction to Java for beginners Basic knowledge of Java language ①
What Java engineers need to prepare for the Java 11 release
[Java] Introduction to lambda expressions
[Java] Introduction to Stream API
[Introduction to rock-paper-scissors games] Java
An introduction to functional programming for object-oriented programmers in Elm
C # cheat sheet for Java engineers
[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 Programming for College Students: Introduction
Getting Started with Ruby for Java Engineers
Introduction to Programming for College Students: Variables
About the procedure for java to work
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"
Learning for the first time java [Introduction]
[Java] Introduction
[Introduction to Java] Variable declarations and types
Introduction to kotlin for iOS developers ④-Type
Memo for migration from java to kotlin
[Introduction to Java] About iterative processing (while, do-while, for, extension for, break, continue)
Introduction to Java Web Apps Performance Troubleshooting
Introduction to algorithms with java --Search (breadth-first search)
[Introduction to Java Data Structures] Create your own fast ArrayDeque for primitive types
[For beginners] Introduction to Java Basic knowledge of Java language ③ Array, selection structure, iteration structure
For my son who started studying Java with "Introduction to Java" in one hand
A way for Java / Scala developers to advance their careers as data engineers.
[Java] How to test for null with JUnit
[Introduction to Java] About type conversion (cast, promotion)
Introduction to algorithms with java --Search (bit full search)
Quick learning Java "Introduction?" Part 1 Building an environment
I want to send an email in Java.
How to use an array for HashMap keys
Road to Java Engineer Part1 Introduction & Environment Construction
[Java] Let's create a mod for Minecraft 1.14.4 [Introduction]
Introduction to kotlin for iOS developers ⑤-Practical XML
[Java] Let's create a mod for Minecraft 1.16.1 [Introduction]
[Java] (for MacOS) How to set the classpath
An introduction to Spring Boot + in-memory data grid
Introduction to kotlin for iOS developers ③-About gradle
For Java engineers starting Kotlin from now on
How to solve an Expression Problem in Java
Introduction to kotlin for iOS developers ①-Environment construction
Introduction to kotlin for iOS developers ②-Project creation
Let's use Java New FileIO! (Introduction, for beginners)
Things to watch out for in Java equals
[Java] How to make multiple for loops single
An introduction to Java that conveys the C language to those who have been doing it for a long time
Introduction to Ruby 2
For JAVA learning (2018-03-16-01)
Introduction to SWING