Getting started with Groovy

Source: Internet
Author: User

I. What is Groovy?

Simply put, Groovy is the next-generation java language. Like java, it also runs in JVM.

As another language running in JVM, groovy syntax is similar to Java syntax. At the same time, Groovy has abandoned the cumbersome java syntax. With the same statement, groovy can minimize the number of times you press keys-this is indeed the gospel of "lazy programmers.

Groovy details: click here
Groovy: click here

2. Development Environment

1. jdk 1.5 or above

2. eclipse + groovy plugin (supports Groovy 1.5.7)

Open eclipse and use the "Search for new features to Install" menu to download and install the groovy plug-in. A New remote site. The url can be http://dist.codehaus.org/policy/distributions/update/, with the plug-in name: groovy plug-in. You can select groovy and grails at the same time as needed (which will be learned later ):

3. Create a groovy Project

1. Create a groovy Project

New --> Project à Java Project creates a java Project. To facilitate management, we recommend that you create two source folders, java and groovy, to store the java source files and groovy source files respectively:

 

2. Add Groovy features

Right-click the project and choose Groovy à Add Groovy Nature to Add Groovy Libraries to the project.

 

3. Add Groovy class

Right-click the groovy source file in the project, and choose New à Other à Groovy Class.

 

The automatically generated source code is as follows:

Public class HelloWorld {

/**

* @ Param args

*/

Public static void main (def args ){

// TODO Auto-generated method stub

}

}

We add a print statement in the main method:

Println "Hello World"

4. Compile and run the groovy class

Right-click the source File, right-click Compile Groovy File, and right-click Run As à Groovy to view the running result in the console.

In fact, the groovy syntax is concise, even if the entire file contains only the println "Hello World" code (delete the statements except this one ), the program can also run.

Of course, to demonstrate that groovy is actually java, you can write the HelloWorld class in full accordance with the java syntax.

 

Iv. Groovy syntax

1. No java type

As a dynamic language, all variables in groovy are objects (similar.. net framework. All objects are inherited from java. lang. object). When declaring a variable, groovy does not require forced type declaration. It only requires that the keyword def be used before the variable name (starting from groovy jsr 1, in earlier versions, even def is not required ).

Modify the code in the main method:

Def var = "hello world"

Println var

Println var. class

You can see that the actual var type output by the program is: java. lang. String

As an exception, def is not required for declaring method parameters and cyclic variables.

2. Unnecessary public

You can remove the public in front of the main method. In fact, the default modifier in groovy is public, so you do not need to write the public modifier, which is different from that in java.

3. unwanted statement Terminator

There is no statement terminator in Groovy. Of course, to maintain consistency with java, you can also use the; sign as the statement Terminator. After each of the preceding statements is added, the program runs normally (to accept the stubborn habits of java programmers ).

4. String Connector

Like java, if you need to write a string in multiple rows, you can use the + sign to connect the string. The code can be written as follows:

Def var = "hello" +

"World" +

", Groovy! "

Of course, groovy is written as follows:

Def var = "" hello

World

Groovy! """

You do not need to connect the three "numbers with the plus sign (however, all format characters in the string will be retained, including carriage return and tab ).

5. Everything is an object

It sounds like "equality of Life". In fact, groovy does not care about the object type. The type of a variable can be changed at any time during running, and everything depends on the needs. If you assign a boolean value to it, the type is automatically converted to a boolean value after it accepts the boolean value regardless of its original type. See the following code:

Def var = "hello" +

"World" +

", Groovy! "

Println var;

Println var. class;

Var = 1001.

Println var. class

Output result:

Hello world, groovy!

Class java. lang. String

Class java. lang. Integer

 

The var variable is running and the type is changing. At first, assign a value to it, which is of the String type, and assign an Integer to it, which is converted to an Integer.

6. Loop

Delete the entire source file and use the following code instead:

Def var = "hello" +

"World" +

", Groovy! "

Def repeat (val ){

For (I = 0; I <5; I ++ ){

Println val

}

}

Repeat (var)

Output:

Hello world, groovy!

Hello world, groovy!

Hello world, groovy!

Hello world, groovy!

Hello world, groovy!

Note that there is no def before the loop variable I. Of course, there is no common int in java, but if you have to add int, there will be no error, because from yy1.1beta2 (not including 1.1beta2), groovy began to support the java classic for loop writing.

In addition, the preceding for statement can also be written as follows:

For (I in 0 .. 5)

The results are the same.

7. String and Gstring

In addition to the standard java. lang. String (enclosed by the 'sign), groovy also supports the Gstring type (enclosed by the "sign ). Change the statements in the for loop above:

Println "This is $ {I }:$ {val }"

Run it to understand what Gstring is.

8. Scope

This is the same as the subinterface in pascal. In the previous for loop introduction, we have used the for (I in 0 .. 5) usage, where 0 .. 5 is a range.

The range is a series of values. For example, "0 .. 4" indicates that it contains integers 0, 1, 2, 3, and 4. Groovy also supports the exclusion range. "0 .. <4" indicates 0, 1, 2, and 3. You can also create a character range: "a. e" is equivalent to a, B, c, d, and e. "A .. <e" includes all values smaller than e.

The range is mainly used in the for loop.

9. default parameter value

You can specify the default parameter value for the method. Modify the repeat method definition:

Def repeat (val, repeat = 3 ){

For (I in 0 .. <repeat ){

Println "This is $ {I }:$ {val }"

}

}

We can see that the repeat method adds a parameter repeat (and a default value of 3 is given) to specify the number of cycles.

When we do not specify 2nd parameters to call the repeat method, the default value of the repeat parameter is 3.

10. Set

Groovy supports the two most common java collections: java. util. Collection and java. util. Map. The range mentioned above is actually a set (java. util. List ).

(1) Collection

In Groovy, a Collection is defined as follows:

Def collect = ["a", "B", "c"]

In addition to adding elements to the set during declaration, you can also add elements to the set in the following ways:

Collect. add (1 );

Collect <"come on ";

Collect [collect. size ()] = 100.0

Collection uses an array-like method to retrieve objects:

Println collect [collect. size ()-1]

Println collect [5]

Groovy supports negative indexes:

Println collect [-1] // index the last 1st Elements

Println collect [-2] // index the last 2nd Elements

Collection supports set operations:

Collect = collect + 5 // Add element 5 to the set

Println collect [collect. size ()-1]

Collect = collect-'A' // subtract element a from the set (1st)

Println collect [0] // now 1st elements are changed to B

Similarly, you can add or delete another set to or from the collection:

Collect = collect-collect [0 .. 4] // remove the first five elements from the set

Println collect [0] // there is only one element in the current collection, that is, the last element of the original

Println collect [-1] // you can also use a negative index to prove that the last element is the first element.

(2) Map

Map is a set of "key-value" pairs. In groovy, the key is not necessarily a String, but any object (in fact, Map in Groovy is java. util. Linke dHashMap ).

A Map can be defined as follows:

Def map = ['name': 'john', 'age': 14, 'sex': 'boys']

Add item:

Map = map + ['weight': 25] // Add john's weight

Map. put ('length', 1.27) // Add john's height

Map. father = 'keller '// Add john's father

You can retrieve values in two ways:

Println map ['father '] // uses the key as the subscript Index

Println map. length // use the key as the member name index

  • 1
  • 2
  • 3
  • Next Page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.