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

Source: Internet
Author: User
Tags array definition iterable

The same points in groovy and Java are:
6+, 4+, 8+, 12+, 13, 14, 15, +, 20+, 21, 22, 23, 28+, 29+,, and 31+, 32+

+ means groovy not only covers the syntax of Java, but it also has an enhanced section.

The different points of groovy and Java are:
0, 1, 2, 5, 7, 9, 11, 16, 17, 19, 24, 25, 26, 27

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 Kid"  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 Kid";    String name2 = new String ("Mountain Breeze Kid");    Groovy is written as name1 = = Name2    if (name1.equals (name2)) {      System.out.println ("equal");    } else {      SYSTEM.OUT.PRINTLN ("Not Equal");     }    Groovy is written as 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 Boy"  
  The def can be understood as varstring name2 = new String ("Mountain Breeze Boy") defined in JavaScript, and//note the semicolon at the end of groovy is optional,
  You can do it without, if one line of code is a statement//Java is written as name1.equals (name2) if (name1  = = name2) {  System.out.println ("equal");} else {  System.out.println ("Not Equal");} Java is written as name1  = = Name2if (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++) {...} in groovy can also be written for (I-0..len-1) {...} or for (I-in 0).

Java:

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

Groovy:

for (int i =0; l < Len; i++) {  //do something}//or for (i-0..len-1) {  //do something}//or for (i in 0).

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:

/* Multiline Comment *//** * Javadoc comment *///single-line Comment}

Groovy:

#! First-line comment that enables UNIX shell to locate groovy launcher to run groovy code, such as #!/usr/bin/groovy/* * Multiline Comment *//** * Javadoc comment *///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 has the same switch statement 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 (given the semantic aspects, and do-while can be replaced by 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 quotation mark can also ' Hello, Mountain Breeze Kid '//Multiline string "" "Hello, Mountain Breeze Kid" ""//or ' Hello, mountain Breeze Boy '//substitute string def name = "Mountain Breeze Kid" "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 Kid";  public void SayHello () {    System.out.println ("Hello," + name);}  }

Groovy:

Class Hello {  private String name = "Mountain Breeze Kid" public  void SayHello () {    //println same as System.out.println () in Java C9/>println "Hello, $name"  }  /* SayHello can also define  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 slightly different from Java, as follows:

Java:

java:public void Varargsmethod (Type args) {  //do something}

Groovy:

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 the parameter type can be omitted.
If the method declaration has a modifier keyword such as public,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 Boy") {    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 null, then the result is?: the value after that; If not NULL, then the result is adef result = a?: "Default result" println Resulta = "Mountain Breeze Boy" result = a?: "Default result" println result

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 from the list of these, such as the Mixins, builder series: Markupbuilder,swingbuilder, many of which are 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 , which has many examples and tutorials for everyone to see, You can also refer to the following groovy high-efficiency programming series (some of which are under the note). 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

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.