RSS from Javabeginnerstutorial.com
Groovy has a language specification. It breaks down code into statements and expressions.
Declaring Classes:
Classes are consider as the backbone of Object oriented programming, because they define the blueprint from which objects are drawn. Methods are public by default. Example contains a simple Groovy class named Book, which has an instance variable title, a constructor that sets the title, and a getter method for the title. Note that everything looks much like Java, except there’s no accessibility modifier: Methods are public by default.
Please save this code in a file named Book.groovy, because we will refer to it in the next section.
The code is not surprising. Class declarations look much the same in most object-oriented languages.
Using Scripts:
Scripts are text files, typically with an extension of .groovy, that can be executed from the command shell via.
Note that this is very different from Java. In Groovy, we are executing the source code! An ordinary Java class is generated for us and executed behind the scenes. But from a user’s perspective, it looks like we are executing plain Groovy source code.
Scripts contain Groovy statements without an enclosing class declaration. Scripts can even contain method definitions outside of class definitions to better structure the code. You will learn more about scripts in future. Until then, take them for granted.
Following example shows how easy it is to use the Book class in a script. We create a new instance and call the getter method on the object by using Java’s dot-syntax. Then we define a method to read the title backward.
Note how we are able to invoke the method getTitleBackwards before it is declared. Behind this observation is a fundamental difference between Groovy and other scripting languages such as Ruby. A Groovy script is fully constructed; that is, parsed, compiled, and generated—before execution.
Another important observation is that we can use Book objects without explicitly compiling the Book class! The only prerequisite for using the Book class is that Book.groovy must reside on the classpath. The Groovy runtime system will find the file, compile it transparently into a class, and yield a new Book object. Groovy combines the ease of scripting with the merits of object orientation.
This inevitably leads to how to organize larger script-based applications. In Groovy, the preferred way is not meshing together numerous script files, but instead grouping reusable components in classes such as Book. Remember that such a class remains full scriptable; you can modify Groovy code, and the changes are instantly available without further action.
Programming the Book class and the script that uses it was simple. It’s hard to believe that it can be any simpler, but it can, as you will see next.
Groovy Beans
JavaBeans are ordinary Java classes that expose properties. Property is not easy to explain because it is not a single entity. It is a concept made up from convention. If a class exposes methods with the naming scheme getName() and setName(name), then the concept describes name as a property of that class. The get and set methods are called accessor methods.
A GroovyBean is a JavaBean defined in Groovy. In Groovy, working with beans is much easier than in Java. Groovy beans are beneficial in following ways:
Generating the accessor methods
Allowing simplified access to all JavaBeans.
Simplified registration of event handlers.
We also demonstrate how to access the bean the standard way with accessor methods, as well as the simplified way, where property access reads like direct field access.
Defining the Bookclass as a GroovyBean:
Handling Text:
Just like in Java, character data is mostly handled using the java.lang.String class. However, Groovy provides some tweaks to make that easier, with more options for string literals and some helpful operators.
GStrings:
In Groovy, string literals can appear in single or double quotes. The double quoted version allows the use of placeholders, which are automatically resolved as required. This is a GString, and that’s also the name of the class involved. The following code demonstrates a simple variable expansion, although that’s not all GStrings can do:
Regular Expressions:
If you are familiar with the concept of regular expressions, you will be glad to hear that Groovy supports them at the language level. If this concept is new to you, you can safely skip this section for the moment.
Groovy provides a means for easy declaration of regular expression patterns as well as operators for applying them.
Note that replaceAll is defined on java.lang.String and takes two string arguments. It becomes apparent that ‘12345’ is a java.lang.String, as is the expression /\d/.
Figure give bellow declares a pattern with the slashy // syntax and uses the =~ find operator to match the pattern against a given string. The first line ensures that the string contains a series of digits; the second line replaces every digit with an x.
Numbers are Objects:
Any program can do without numbers. Groovy numbers are first class objects. They are not primitive types. In Java, you cannot invoke methods on primitive types. If x is of primitive type int, you cannot write x.toString() and if y is an object, you cannot use 2*y. In Groovy, both are possible. You can use numbers with numeric operators, and you can also call methods on number instances.
The variables x and yare objects of type java.lang.Integer. Thus, we can use the plus method. But we can just as easily use the + operator.
Using Lists, Maps and Ranges:
Many languages directly understand only a single collection type an array but groovy makes collection handling simple, with added support for operators, literals, and extra methods.
Lists:
Java supports indexing arrays with a square bracket syntax, which we will call the sub-script operator. Groovy allows the same syntax to be used with lists instances of java.util.List which allows adding and removing elements, changing the size of the list at runtime, and storing items that are not necessarily of a uniform type. In addition, Groovy allows lists to be indexed outside their current bounds, which again can change the size of the list. Furthermore, lists can be specified as literals directly in your code.
The following example declares a list of Roman numerals and initializes it with the first seven numbers. The list is constructed such that each index matches its representation as a Roman numeral. Working with the list looks much like working with arrays, but in Groovy, the manipulation is more expressive, and the restrictions that apply to arrays are gone:
Note that there was no list item with index 8when we assigned a value to it. We indexed the list outside the current bounds.
Simple Maps:
A map is a storage type that associates a key with a value. Maps store and retrieve the values by key, whereas lists retrieve the values by numeric index.
Groovy supports maps at the language level, allowing them to be specified with literals and providing suitable operators to work with them. It does so with a clear and easy syntax. The syntax for maps looks like an array of key-value pairs, where a colon separates keys and values.
You see the map declaration and initialization, the retrieval of values, and the addition of a new entry. All of this is done with a single method call explicitly appearing in the source code and even that is only checking the new size of the map:
Note how the syntax is consistent with that used to declare, access, and modify lists. The differences between using maps and lists are minimal, so it’s easy to remember both. This is a good example of the Groovy language designers taking commonly required operations and making programmers’ lives easier by providing a simple and consistent syntax.
Ranges:
Range is effectively a start point and an end point, with a notion of how to move from the start to the end point. Groovy provides literals to support this useful concept, along with other language features such as the for statement, which understands ranges.
The following code demonstrates the range literal format, along with how to find the size of a range, determine whether it contains a particular value, find its start and end points, and reverse it:
These examples are limited because we are only trying to show what ranges do on their own. Ranges are usually used in conjunction with other Groovy features.
Groovy Control Structures:
Control structures allow a programming language to control the flow of execution through code. There are simple versions of everyday control structures like if-else, while, switch, and try-catch-finally in Groovy, just like in Java.
In conditionals, null is treated like false; not-null is treated like true. The for loop has a for(i in x){body}notation, where x can be anything that Groovy knows how to iterate through, such as an iterator, an enumeration, a collection, a range, a map, or literally any object.
Control Structures:
The post GROOVY AT A GLANCE appeared first on Java Beginners Tutorial.