Thursday, February 2, 2017

Groovy - Overview

Groovy is an object oriented language which is based on Java platform. Groovy 1.0 was released in January 2, 2007 with Groovy 2.4 as the current major release. Groovy is distributed via the Apache License v 2.0.

Groovy - Environment

There are a variety of ways to get the Groovy environment setup.
Binary download and installation − Go to the link www.groovy-lang.org/download.html to get the Windows Installer section. Click on this option to start the download of the Groovy installer.

Groovy - Basic Syntax

In order to understand the basic syntax of Groovy, let’s first look at a simple Hello World program.

Creating Your First Hello World Program

Creating your first hello world program is as simple as just entering the following code line −
class Example {
   static void main(String[] args) {
      // Using a simple println statement to print output to the console
      println('Hello World');

Groovy - Data Types

In any programming language, you need to use various variables to store various types of information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory to store the value associated with the variable.

Groovy - Variables

Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.

Groovy - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
Groovy has the following types of operators −
  • Arithmetic operators
  • Relational operators
  • Logical operators
  • Bitwise operators
  • Assignment operators

Groovy - Loops

So far, we have seen statements which have been executed one after the other in a sequential manner. Additionally, statements are provided in Groovy to alter the flow of control in a program’s logic. They are then classified into flow of control statements which we will see in detail.

Groovy - Decision Making

Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Groovy - Methods

A method is in Groovy is defined with a return type or with the def keyword. Methods can receive any number of arguments. It’s not necessary that the types are explicitly defined when defining the arguments. Modifiers such as public, private and protected can be added. By default, if no visibility modifier is provided, the method is public.

Groovy - File I/O

Groovy provides a number of helper methods when working with I/O. Groovy provides easier classes to provide the following functionalities for files.
  • Reading files
  • Writing to files
  • Traversing file trees
  • Reading and writing data objects to files

Groovy - Optionals

Groovy is an “optionally” typed language, and that distinction is an important one when understanding the fundamentals of the language. When compared to Java, which is a “strongly” typed language, whereby the compiler knows all of the types for every variable and can understand and honor contracts at compile time. This means that method calls are able to be determined at compile time.

Groovy - Numbers

In Groovy, Numbers are actually represented as object’s, all of them being an instance of the class Integer. To make an object do something, we need to invoke one of the methods declared in its class.
Groovy supports integer and floating point numbers.

Groovy - Strings

A String literal is constructed in Groovy by enclosing the string text in quotations.
Groovy offers a variety of ways to denote a String literal. Strings in Groovy can be enclosed in single quotes (’), double quotes (“), or triple quotes (“””). Further, a Groovy String enclosed by triple quotes may span multiple lines.

Groovy - Ranges

A range is shorthand for specifying a sequence of values. A Range is denoted by the first and last values in the sequence, and Range can be inclusive or exclusive. An inclusive Range includes all the values from the first to the last, while an exclusive Range includes all values except the last. Here are some examples of Range literals −

Groovy - Lists

The List is a structure used to store a collection of data items. In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index. A List literal is presented as a series of objects separated by commas and enclosed in square brackets.

Groovy - Maps

A Map (also known as an associative array, dictionary, table, and hash) is an unordered collection of object references. The elements in a Map collection are accessed by a key value. The keys used in a Map can be of any class. When we insert into a Map collection, two values are required: the key and the value.
Following are some examples of maps −

Groovy - Dates & Times

The class Date represents a specific instant in time, with millisecond precision. The Date class has two constructors as shown below.

Groovy - Regular Expressions

A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison.

Groovy - Exception Handling

Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained.
Exception normally disrupts the normal flow of the application, which is the reason why we need to use Exception handling in our application.
Exceptions are broadly classified into the following categories −

Groovy - Object Oriented

In Groovy, as in any other Object-Oriented language, there is the concept of classes and objects to represent the objected oriented nature of the programming language. A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain.

Groovy - Generics

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

Groovy - Traits

Traits are a structural construct of the language which allow −
  • Composition of behaviors.
  • Runtime implementation of interfaces.
  • Compatibility with static type checking/compilation

Groovy - Closures

A closure is a short anonymous block of code. It just normally spans a few lines of code. A method can even take the block of code as a parameter. They are anonymous in nature.
Following is an example of a simple closure and what it looks like.

Groovy - Annotations

Annotations are a form of metadata wherein they provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.
Annotations are mainly used for the following reasons −

Groovy - XML

XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language. This is one of the most common languages used for exchanging data between applications.

Groovy - JMX

JMX is the defacto standard which is used for monitoring all applications which have anything to do with the Java virual environment. Given that Groovy sits directly on top of Java, Groovy can leverage the tremendous amount of work already done for JMX with Java.

Groovy - JSON

This chapter covers how to we can use the Groovy language for parsing and producing JSON objects.

JSON Functions

Function Libraries
JsonSlurper JsonSlurper is a class that parses JSON text or reader content into Groovy data
Structures such as maps, lists and primitive types like Integer, Double, Boolean and String.
JsonOutput This method is responsible for serialising Groovy objects into JSON strings.

Groovy - DSLS

Groovy allows one to omit parentheses around the arguments of a method call for top-level statements. This is known as the "command chain" feature. This extension works by allowing one to chain such parentheses-free method calls, requiring neither parentheses around arguments, nor dots between the chained calls.

Groovy - Database

Groovy’s groovy-sql module provides a higher-level abstraction over the current Java’s JDBC technology. The Groovy sql API supports a wide variety of databases, some of which are shown below.
  • HSQLDB
  • Oracle
  • SQL Server
  • MySQL
  • MongoDB

Groovy - Builders

During the process of software development, sometimes developers spend a lot of time in creating Data structures, domain classes, XML, GUI Layouts, Output streams etc.And sometimes the code used to create these specific requirements results in the repitition of the same snippet of code in many places.

Groovy - Command Line

The Groovy shell known as groovysh can be easily used to evaluate groovy expressions, define classes and run simple programs. The command line shell gets installed when Groovy is installed.
Following are the command line options available in Groovy −

Groovy - Unit Testing

The fundamental unit of an object-oriented system is the class. Therefore unit testing consists of testig within a class. The approach taken is to create an object of the class under testing and use it to check that selected methods execute as expected. Not every method can be tested, since it is not always pratical to test each and every thing. But unit testing should be conducted for key and critical methods.

Groovy - Template Engines

Groovy’s template engine operates like a mail merge (the automatic addition of names and addresses from a database to letters and envelopes in order to facilitate sending mail, especially advertising, to many addresses) but it is much more general.

Groovy - Meta Object Programming

Meta object programming or MOP can be used to invoke methods dynamically and also create classes and methods on the fly.
So what does this mean? Let’s consider a class called Student, which is kind of an empty class with no member variables or methods.

Groovy - Quick Guide

Groovy - Overview

Groovy is an object oriented language which is based on Java platform. Groovy 1.0 was released in January 2, 2007 with Groovy 2.4 as the current major release. Groovy is distributed via the Apache License v 2.0.

Groovy - Useful Resources

The following resources contain additional information on Groovy. Please use them to get more in-depth knowledge on this.

Discuss Groovy

Groovy is an object oriented language which is based on Java platform. Groovy 1.0 was released in January 2, 2007 with Groovy 2.4 as the current major release. Groovy is distributed via the Apache License v 2.0. In this tutorial, we would explain all the fundamentals of Groovy and how to put it into practice.

Go - Overview

Go is a general-purpose language designed with systems programming in mind.It was initially developed at Google in year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection and supports concurrent programming.

Go - Environment Setup

Try it Option Online

You really do not need to set up your own environment to start learning Go programming language. Reason is very simple, we already have set up Go Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work.

Go - Program Structure

Before we study basic building blocks of the Go programming language, let us look a bare minimum Go program structure so that we can take it as a reference in upcoming chapters.

Go - Basic Syntax

You have seen a basic structure of Go program, so it will be easy to understand other basic building blocks of the Go programming language.

Go - Data Types

In the Go programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

Go - Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

Go - Constants

The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.

Go - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Go language is rich in built-in operators and provides the following types of operators:
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators

Go - Decision Making

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Go - Loops

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Go - Functions

A function is a group of statements that together perform a task. Every Go program has at least one function, which is main(), and all the most trivial programs can define additional functions.

Go - Scope Rules

A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable can not be accessed. There are three places where variables can be declared in C programming language:

Go - Arrays

Go programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Go - Pointers

Pointers in Go are easy and fun to learn. Some Go programming tasks are performed more easily with pointers, and other tasks, such as call by reference, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Go programmer. Let's start learning them in simple and easy steps.

Go - Structures

Go arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user defined data type available in Go programming, which allows you to combine data items of different kinds.

Go - Slices

Go Slice is an abstraction over Go Array. As Go Array allows you to define type of variables that can hold several data items of the same kind but it do not provide any inbuilt method to increase size of it dynamically or get a sub-array of its own. Slices covers this limitation. It provides many utility functions required on Array and is widely used in Go programming.

Go - Range

The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table.

Go - Maps

Go provides another important data type map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can strore the value in a Map object. After value is stored, you can retrieve it by using its key.

Go - Recursion

Recursion is the process of repeating items in a self-similar way. Same applies in programming languages as well where if a programming allows you to call a function inside the same function that is called recursive call of the function as follows.

Go - Type Casting

Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another using the cast operator as following:

Go - Interfaces

Go programming provides another data type called interfaces which represents a set of method signatures. struct data type implements these interfaces to have metho definitions for the method signature of the interfaces.

Go - Error Handling

Go programming provides a pretty simple error handling framework with inbuit error interface type of following declaration:
type error interface {
   Error() string
}

Go Questions and Answers

Go Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations.

Go - Quick Guide

Go - Overview

Go is a general-purpose language designed with systems programming in mind.It was initially developed at Google in year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection and supports concurrent programming. Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries.

Go - Useful Resources

If you want to list down your website, book or any other resource on this page then please contact at webmaster@tutorialspoint.com

Discuss Go

Go language, is a programming language initially developed at Google in year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go programming language is a statically-typed language with syntax similar to that of C. It provides garbage collection, type safety, dynamic-typing capability, many advanced built-in types such as variable length arrays and key-value maps. It also provides a rich standard library. The Go programming language was announced in November 2009 and is used in some of the Google's production systems.