Groovy easy to get started with-compare with Java to quickly master groovy

Source: Internet
Author: User
Tags array definition closure iterable

Turn from: Groovy easy to get started-get a quick grasp of groovy with Java comparison (updated on 2008.10.18)

in the previous articles, I've already told you what groovy is, how important it is to learn groovy, and what I don't know about groovy as a friend of my blog.Groovy Categories. I'll take a comparison of groovy and Java to unlock the mystery of groovy. Ready? start!

Note: This tutorial is written for the latest version of Groovy

The same points in groovy and Java are:
0+,the4+, 6+, 8+, +, 12+, +,19+,20+, 28+, 29+ ,31+, 32+
+ means groovy not only covers the syntax of Java, but also the enhanced part

Groovy and Java are notwithpoints are:
1, 2, 5, 7, 9, one, , 27,33

the sequence numbers listed below are in order:

0. In groovy you can define untyped variables with DEF (defining variables in terms of Def and Var in JavaScript), and return values as untyped methods without Def in Java
Groovy:

Class Man {
def name = "Mountain Breeze Boy"
def introduce () {
Return "I ' m $name"//return can be omitted
}
}

1. The Equals method in Java corresponds to = = in groovy, and = = in Java (judging whether to refer to the same object) corresponds to the is method in groovy
eg.
Test1.java:

public class Test {
public static void Main (string[] args) {
String name1 = "Mountain Breeze Boy";
String name2 = new String ("Mountain Breeze Kid");
Groovy is written in name1 = = Name2
if (Name1.equals (name2)) {
System.out.println ("equal");
} else {
SYSTEM.OUT.PRINTLN ("Not Equal");
}
Groovy is written in name1.is (name2)
if (name1 = = name2) {
System.out.println ("identical");
} else {
System.out.println ("not identical");
}
}


corresponding to the Test1.java
Test1.groovy:

String name1 = "Mountain Breeze Boy"//You can also write this: def name1 = "Mountain Breeze Kid" where def can be understood as the Var of variables defined in JavaScript
String name2 = new String ("Mountain Breeze Boy")//Note the semicolon at the end of groovy is optional and can be done without, provided that one line of code is a statement
Written in Java as Name1.equals (name2)
if (name1 = = name2) {
System.out.println ("equal");
} else {
SYSTEM.OUT.PRINTLN ("Not Equal");
}
Written in Java as name1 = = Name2
if (name1.is (name2)) {
System.out.println ("identical");
} else {
System.out.println ("not identical");
}


2. The array definition in Java int[] A = {1, 2, 3}; Written in groovy int[] A = [1, 2, 3]
3. In Java, for loop for (int i = 0; i < len; i++) {...} can also be written for (I-0..len-1) {...} or for (I-in-0..<len) {...} in Groovy)
Java:

for (int i =0; i < Len; i++) {
Do something
}

Groovy:

for (int i =0; i < Len; i++) {
Do something
}

//or
For (i in 0..len-1) {
Do something
}

Or
For (i in 0..<len) {
Do something
}


4. The method returned in Java is written as return; or return obj; Return is optional in Groovy's method
Java:

Public String SayHello () {
Return "Hello, Mountain Breeze Boy";
}

Groovy:

Public String SayHello () {
Return "Hello, Mountain Breeze Boy"
}
Or
Public String SayHello () {
"Hello, Mountain Breeze Boy."
}
Or
String SayHello () {
"Hello, Mountain Breeze Boy."
}
Or
Public SayHello () {
"Hello, Mountain Breeze Boy."
}
Or
Def SayHello () {
"Hello, Mountain Breeze Boy."
}


5. Inner class in Java is the inner class, implemented with closure in groovy (closure is a feature that JAVA7 is considering, more semantically than inner class)
6. The annotations in groovy are more than the first line of comment #! in Java, others are the same as Java, such as single-line comments://Multiline Comment:///or Javadoc support/** */
Java:

/*
* Multi-line Comment
*/

/**
* Javadoc Notes
*/

Single-line Comment


Groovy:

#! First lineannotations that enable Unix shells to locate groovy launcher to run groovy code, such as
#!/usr/bin/groovy

/*
* Multi-line Comment
*/

/**
* Javadoc Notes
*/

Single-line Comment



7. Java5 in For-each:for (Type t:iteratable) {...} In groovy, the for (T in iteratable) {...}
Java:

for (Type t:iterable) {
Do something
}


Groovy:

for (T in iterable) {
Do something
}


8. Groovy in the switch statement is the same as in Java, but supports more types, such as String
9. Groovy's while statement is the same as Java, but Do-while is discarded (considering semantic aspects, and do-while can be replaced with other forms of loop statements with low frequency)
The string constants in Java are expressed as "Hello, Mountain Breeze Boy", which can be represented in groovy as follows

Double quotes
"Hello, Mountain Breeze Boy."

Single quotes can also be
' Hello, Mountain Breeze Boy '

Multi-line string
"" "Hello,
Mountain Breeze Boy "" "

Or
"' Hello,
Mountain Breeze Boy.
‘‘‘

Substitution string
def name = "Mountain Breeze Boy"
"Hello, ${name}"
Or
"Hello, $name"

11. Define a class in groovy, with the same definition of a class as in Java, the only difference being that the classes in groovy, the properties and methods are public by default, the package is default in Java, and in groovy you can define methods with Def, see comments.
Java:

public class Hello {
Private String name = "Mountain Breeze Boy";
public void SayHello () {
System.out.println ("Hello," + name);
}
}

Groovy:

Class Hello {
Private String name = "Mountain Breeze Kid"
public void SayHello () {
Println is the same as SYSTEM.OUT.PRINTLN () in Java
Println "Hello, $name"
}
/* SayHello can also be defined like this
Def SayHello () {
Println "Hello, $name"
}
*/
}


12. Object creation in Java written as thought T = New Thought (); This can be done in groovy, but there are many more ways to write it: def t = New Thought ();
13. Static method invocation is the same in Java and Groovy, i.e. classname.staticmethodname ();
14. To implement the interface and inherit the parent class, groovy is exactly the same as Java, which implements the interface class ClassName implements InterfaceName {...}
Inherit parent class: Class ClassName extends Superclass {...}
15. Defining the interface groovy is exactly the same as Java, i.e. interface InterfaceName {...} In groovy, the default is public
16. Regular expression constants are not in Java and are represented as/pattern/in groovy
17.HASH constant (type Java.util.HashMap) Not in Java, represented in groovy as def frequence = ["The": 5, "Hello": 2, "World": 2]
18. Class variable is the static variable, groovy is the same as Java, static String name = "Mountain Breeze Kid", in Groovy can also be written as static name = "Mountain Breeze Kid"
19. In the varargs approach, groovy is a more expressive method than Java, as follows:
Java:

Java:
public void Varargsmethod (Type args) {
Do something
}


Groovy:

//Same as in Java
def varargsmethod (Type ... args) {
//do something
}

//Groovy can also use [] instead of ... to reflect the nature of varargs .
def varargsmethod (type[] args) {
Do something
}


20. Refer to the current object, groovy is the same as Java, in Java, this is represented in groovy, and in groovy, this can appear in the static range, pointing to the class object of the class, in this case, this is equivalent to Thisinstaticscope.class (Java notation ) or thisinstaticscope (groovy notation)

Class Thisinstaticscope {
static {
Println this
}
Please do not be surprised that parameter types can be omitted. If the method declaration has modifier keywords such asPublic,synchronized,static, the return value type can be omitted.
Static main (args) {
Println this
}
}


21. Call the parent class method in the subclass, groovy and Java are the same, Super.methodname () in Java, Super.methodname () in Groovy
22. Namespace definition, groovy and Java, the package Edu.ecust.bluesun in Java; Package Edu.ecust.bluesun (semicolon can be omitted) in groovy
23. In the import class, groovy is the same as Java, import edu.ecust.bluesun.GroovyTest in Java; Import Edu.ecust.bluesun.GroovyTest in Groovy
24.List Constants (type Java.util.ArrayList) are not in Java, represented in groovy as def list = [3, one, "Hello", "Mountain Breeze Boy", "!"]
25. In exception handling, groovy is the same as Java, except that the programmer is not forced to catch check exceptions (checked exception) (this is like C #, if I remember correctly:)
Also, you can not write throws statements when you declare a method.
26. The default parameters of the method, not in Java, are indicated in groovy as follows:

Class Hello {
If no parameters are passed in, the default prints out Hello, Mountain Breeze Boy
def greet (name= "Mountain Breeze Kid") {
println ("Hello, $name")//can also omit parentheses ()
}
}

27. In groovy, if a statement is a single line, the semicolon (;) can be omitted from the end of the sentence, and each statement in Java must be followed by a semicolon (;)
28. In groovy, if it is not a Boolean or Boolean type, non-null or non-null (empty string, [],[:]) is true,null false, and the object in Java cannot represent true or false ; If it is a Boolean or Boolean type, it is the same as in Java.
29. In groovy, everything is an object! This is not the case in Java, where the base type (primitive type) is not an object.
30. In Java, class objects are represented as Classname.class, while in groovy you can represent class objects directly with classname
31.Groovy will automatically import java.lang.*, java.util.*, java.net.*, java.io.*, Java.math.BigInteger, Java.math.BigDecimal, Groovy.lang.*, groovy.util.*, and Java is only automatically imported java.lang.*
32.Groovy not only have? : ternary operator, plus?: two-dollar operator, but Java only? : ternary operator.
Groovy:

def a = null;
If A is "empty" (null, empty string "", [],[:]), then the result is?: the value after that; If it's not "empty," then the result is a.
def result = a?: "Default Result"
println result

A = "Mountain Breeze Boy"
result = a?: "Default Result"
println result

33.Groovy can perform multiple assignments, but Java cannot
Groovy:

def A, b

(A, b) = [1, 2]//Assign values to a and B

println ([A, b])

(A, b) = [B, a]//Exchange values of a and B

println ([A, b])

def (c, d) = [1, 2]//Declaration is initialized at the same time

println ([C, D])




From the above, groovy is almost entirely compatible with Java syntax, no wonder ' Jiangnan white ' called Groovy the ' illegitimate bastard ' of Java, but because groovy not only draws on Java 95% features, but also draws on a number of excellent dynamic language, such as Python, Ruby, etc. Make groovy a very efficient and agile programming language, not just a copy of Java. So in fact java++ can be used as a groovy alias, i.e. Java with dynamic characteristics.

Finally, I would like to add: Groovy's features are far less than those listed, such as the Mixins,builder series: Markupbuilder,swingbuilder, many of which are in groovy and not in Java, so they are not listed, To continue in-depth learning groovy, visit the Groovy official website: http://groovy.codehaus.org, there are many examples and tutorials for everyone to refer to, or refer to the groovy high-efficiency programming series below (some of which are under the notes). There are also "Groovy in Action" e-book downloads online, so you might want to search.


Reference documents
Differences from Java:Http://groovy.codehaus.org/Differences+from+Java

Attached: Groovy Easy to get started--build a groovy development environment

Groovy easy to get started with-compare with Java to quickly master groovy

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.