Groovy – Methods ”; Previous Next 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. The simplest type of a method is one with no parameters as the one shown below − def methodName() { //Method code } Following is an example of simple method class Example { static def DisplayName() { println(“This is how methods work in groovy”); println(“This is an example of a simple method”); } static void main(String[] args) { DisplayName(); } } In the above example, DisplayName is a simple method which consists of two println statements which are used to output some text to the console. In our static main method, we are just calling the DisplayName method. The output of the above method would be − This is how methods work in groovy This is an example of a simple method Method Parameters A method is more generally useful if its behavior is determined by the value of one or more parameters. We can transfer values to the called method using method parameters. Note that the parameter names must differ from each other. The simplest type of a method with parameters as the one shown below − def methodName(parameter1, parameter2, parameter3) { // Method code goes here } Following is an example of simple method with parameters class Example { static void sum(int a,int b) { int c = a+b; println(c); } static void main(String[] args) { sum(10,5); } } In this example, we are creating a sum method with 2 parameters, a and b. Both parameters are of type int. We are then calling the sum method from our main method and passing the values to the variables a and b. The output of the above method would be the value 15. Default Parameters There is also a provision in Groovy to specify default values for parameters within methods. If no values are passed to the method for the parameters, the default ones are used. If both nondefault and default parameters are used, then it has to be noted that the default parameters should be defined at the end of the parameter list. Following is an example of simple method with parameters − def someMethod(parameter1, parameter2 = 0, parameter3 = 0) { // Method code goes here } Let’s look at the same example we looked at before for the addition of two numbers and create a method which has one default and another non-default parameter − class Example { static void sum(int a,int b = 5) { int c = a+b; println(c); } static void main(String[] args) { sum(6); } } In this example, we are creating a sum method with two parameters, a and b. Both parameters are of type int. The difference between this example and the previous example is that in this case we are specifying a default value for b as 5. So when we call the sum method from our main method, we have the option of just passing one value which is 6 and this will be assigned to the parameter a within the sum method. The output of the above method would be the value 11. class Example { static void sum(int a,int b = 5) { int c = a+b; println(c); } static void main(String[] args) { sum(6,6); } } We can also call the sum method by passing 2 values, in our example above we are passing 2 values of 6. The second value of 6 will actually replace the default value which is assigned to the parameter b. The output of the above method would be the value 12. Method Return Values Methods can also return values back to the calling program. This is required in modern-day programming language wherein a method does some sort of computation and then returns the desired value to the calling method. Following is an example of simple method with a return value. class Example { static int sum(int a,int b = 5) { int c = a+b; return c; } static void main(String[] args) { println(sum(6)); } } In our above example, note that this time we are specifying a return type for our method sum which is of the type int. In the method we are using the return statement to send the sum value to the calling main program. Since the value of the method is now available to the main method, we are using the println function to display the value in the console. The output of the above method would be the value 11. Instance methods Methods are normally implemented inside classes within Groovy just like the Java language. A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. The class objects exhibit the properties and behaviors defined by its class. So the behaviors are defined by creating methods inside of the class. We will see classes in more detail in a later chapter but Following is an example of a method implementation in a class. In our previous examples we defined our method as static methods which meant that we could access those methods directly from the class. The next example of methods is instance methods wherein the methods are accessed by creating objects of the class. Again we will see classes in a later chapter, for now we will demonstrate how to use methods. Following is an example of how methods can be implemented. class Example { int x; public int getX() { return x; } public void setX(int pX) { x = pX; } static void main(String[] args) { Example ex = new Example(); ex.setX(100); println(ex.getX()); } } In our above example, note that this time
Category: groovy
Groovy – Basic Syntax
Groovy – Basic Syntax ”; Previous Next 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 − Live Demo class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println(”Hello World”); } } When we run the above program, we will get the following result − Hello World Import Statement in Groovy The import statement can be used to import the functionality of other libraries which can be used in your code. This is done by using the import keyword. The following example shows how to use a simple import of the MarkupBuilder class which is probably one of the most used classes for creating HTML or XML markup. import groovy.xml.MarkupBuilder def xml = new MarkupBuilder() By default, Groovy includes the following libraries in your code, so you don’t need to explicitly import them. import java.lang.* import java.util.* import java.io.* import java.net.* import groovy.lang.* import groovy.util.* import java.math.BigInteger import java.math.BigDecimal Tokens in Groovy A token is either a keyword, an identifier, a constant, a string literal, or a symbol. println(“Hello World”); In the above code line, there are two tokens, the first is the keyword println and the next is the string literal of “Hello World”. Comments in Groovy Comments are used to document your code. Comments in Groovy can be single line or multiline. Single line comments are identified by using the // at any position in the line. An example is shown below − class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println(”Hello World”); } } Multiline comments are identified with /* in the beginning and */ to identify the end of the multiline comment. class Example { static void main(String[] args) { /* This program is the first program This program shows how to display hello world */ println(”Hello World”); } } Semicolons Unlike in the Java programming language, it is not mandatory to have semicolons after the end of every statement, It is optional. Live Demo class Example { static void main(String[] args) { def x = 5 println(”Hello World”); } } If you execute the above program, both statements in the main method don”t generate any error. Identifiers Identifiers are used to define variables, functions or other user defined variables. Identifiers start with a letter, a dollar or an underscore. They cannot start with a number. Here are some examples of valid identifiers − def employeename def student1 def student_name where def is a keyword used in Groovy to define an identifier. Here is a code example of how an identifier can be used in our Hello World program. class Example { static void main(String[] args) { // One can see the use of a semi-colon after each statement def x = 5; println(”Hello World”); } } In the above example, the variable x is used as an identifier. Keywords Keywords as the name suggest are special words which are reserved in the Groovy Programming language. The following table lists the keywords which are defined in Groovy. as assert break case catch class const continue def default do else enum extends false Finally for goto if implements import in instanceof interface new pull package return super switch this throw throws trait true try while Whitespaces Whitespace is the term used in a programming language such as Java and Groovy to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement. For example, in the following code example, there is a white space between the keyword def and the variable x. This is so that the compiler knows that def is the keyword which needs to be used and that x should be the variable name that needs to be defined. def x = 5; Literals A literal is a notation for representing a fixed value in groovy. The groovy language has notations for integers, floating-point numbers, characters and strings. Here are some of the examples of literals in the Groovy programming language − 12 1.45 ‘a’ “aa” Print Page Previous Next Advertisements ”;
Groovy – Home
Groovy Tutorial PDF Version Quick Guide Resources Job Search Discussion 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. Audience This tutorial is going to be extremely useful for all those software professionals who would like to learn the basics of Groovy programming. Prerequisites Before proceeding with this tutorial, you should have some hands-on experience of Java or any other object-oriented programming language. No Groovy experience is assumed. Print Page Previous Next Advertisements ”;
Groovy – Data Types
Groovy – Data Types ”; Previous Next 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. You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Built-in Data Types Groovy offers a wide variety of built-in data types. Following is a list of data types which are defined in Groovy − byte − This is used to represent a byte value. An example is 2. short − This is used to represent a short number. An example is 10. int − This is used to represent whole numbers. An example is 1234. long − This is used to represent a long number. An example is 10000090. float − This is used to represent 32-bit floating point numbers. An example is 12.34. double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565. char − This defines a single character literal. An example is ‘a’. Boolean − This represents a Boolean value which can either be true or false. String − These are text literals which are represented in the form of chain of characters. For example “Hello World”. Bound values The following table shows the maximum allowed values for the numerical and decimal literals. byte -128 to 127 short -32,768 to 32,767 int -2,147,483,648 to 2,147,483,647 long -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 float 1.40129846432481707e-45 to 3.40282346638528860e+38 double 4.94065645841246544e-324d to 1.79769313486231570e+308d Class Numeric Types In addition to the primitive types, the following object types (sometimes referred to as wrapper types) are allowed − java.lang.Byte java.lang.Short java.lang.Integer java.lang.Long java.lang.Float java.lang.Double In addition, the following classes can be used for supporting arbitrary precision arithmetic − Name Description Example java.math.BigInteger Immutable arbitrary-precision signed integral numbers 30g java.math.BigDecimal Immutable arbitrary-precision signed decimal numbers 3.5g The following code example showcases how the different built-in data types can be used − Live Demo class Example { static void main(String[] args) { //Example of a int datatype int x = 5; //Example of a long datatype long y = 100L; //Example of a floating point datatype float a = 10.56f; //Example of a double datatype double b = 10.5e40; //Example of a BigInteger datatype BigInteger bi = 30g; //Example of a BigDecimal datatype BigDecimal bd = 3.5g; println(x); println(y); println(a); println(b); println(bi); println(bd); } } When we run the above program, we will get the following result − 5 100 10.56 1.05E41 30 3.5 Print Page Previous Next Advertisements ”;
Groovy – Operators
Groovy – Operators ”; Previous Next 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 Arithmetic Operators The Groovy language supports the normal Arithmetic operators as any the language. Following are the Arithmetic operators available in Groovy − Show Example Operator Description Example + Addition of two operands 1 + 2 will give 3 − Subtracts second operand from the first 2 − 1 will give 1 * Multiplication of both operands 2 * 2 will give 4 / Division of numerator by denominator 3 / 2 will give 1.5 % Modulus Operator and remainder of after an integer/float division 3 % 2 will give 1 ++ Incremental operators used to increment the value of an operand by 1 int x = 5; x++; x will give 6 — Incremental operators used to decrement the value of an operand by 1 int x = 5; x–; x will give 4 Relational operators Relational operators allow of the comparison of objects. Following are the relational operators available in Groovy − Show Example Operator Description Example == Tests the equality between two objects 2 == 2 will give true != Tests the difference between two objects 3 != 2 will give true < Checks to see if the left objects is less than the right operand. 2 < 3 will give true <= Checks to see if the left objects is less than or equal to the right operand. 2 <= 3 will give true > Checks to see if the left objects is greater than the right operand. 3 > 2 will give true >= Checks to see if the left objects is greater than or equal to the right operand. 3 >= 2 will give true Logical Operators Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy − Show Example Operator Description Example && This is the logical “and” operator true && true will give true || This is the logical “or” operator true || true will give true ! This is the logical “not” operator !false will give true Bitwise Operators Groovy provides four bitwise operators. Following are the bitwise operators available in Groovy − Show Example Sr.No Operator & Description 1 & This is the bitwise “and” operator 2 | This is the bitwise “or” operator 3 ^ This is the bitwise “xor” or Exclusive or operator 4 ~ This is the bitwise negation operator Here is the truth table showcasing these operators. p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Assignment operators The Groovy language also provides assignment operators. Following are the assignment operators available in Groovy − Show Example Operator Description Example += This adds right operand to the left operand and assigns the result to left operand. def A = 5 A+=3 Output will be 8 -= This subtracts right operand from the left operand and assigns the result to left operand def A = 5 A-=3 Output will be 2 *= This multiplies right operand with the left operand and assigns the result to left operand def A = 5 A*=3 Output will be 15 /= This divides left operand with the right operand and assigns the result to left operand def A = 6 A/=3 Output will be 2 %= This takes modulus using two operands and assigns the result to left operand def A = 5 A%=3 Output will be 2 Range Operators Groovy supports the concept of ranges and provides a notation of range operators with the help of the .. notation. A simple example of the range operator is given below. def range = 0..5 This just defines a simple range of integers, stored into a local variable called range with a lower bound of 0 and an upper bound of 5. The following code snippet shows how the various operators can be used. Live Demo class Example { static void main(String[] args) { def range = 5..10; println(range); println(range.get(2)); } } When we run the above program, we will get the following result − From the println statement, you can see that the entire range of numbers which are defined in the range statement are displayed. The get statement is used to get an object from the range defined which takes in an index value as the parameter. [5, 6, 7, 8, 9, 10] 7 Operator Precedence The following table lists all groovy operators in order of precedence. Sr.No Operators & Names 1 ++ — + – pre increment/decrement, unary plus, unary minus 2 * / % multiply, div, modulo 3 + – addition, subtraction 4 == != <=> equals, not equals, compare to 5 & binary/bitwise and 6 ^ binary/bitwise xor 7 | binary/bitwise or 8 && logical and 9 || logical or 10 = **= *= /= %= += -= <<= >>= >>>= &= ^= |= Various assignment operators Print Page Previous Next Advertisements ”;
Groovy – Numbers
Groovy – Numbers ”; Previous Next 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. An integer is a value that does not include a fraction. A floating-point number is a decimal value that includes a decimal fraction. An Example of numbers in Groovy is shown below − Integer x = 5; Float y = 1.25; Where x is of the type Integer and y is the float. The reason why numbers in groovy are defined as objects is generally because there are requirements to perform operations on numbers. The concept of providing a class over primitive types is known as wrapper classes. By default the following wrapper classes are provided in Groovy. The object of the wrapper class contains or wraps its respective primitive data type. The process of converting a primitive data types into object is called boxing, and this is taken care by the compiler. The process of converting the object back to its corresponding primitive type is called unboxing. Example Following is an example of boxing and unboxing − class Example { static void main(String[] args) { Integer x = 5,y = 10,z = 0; // The the values of 5,10 and 0 are boxed into Integer types // The values of x and y are unboxed and the addition is performed z = x+y; println(z); } } The output of the above program would be 15. In the above example, the values of 5, 10, and 0 are first boxed into the Integer variables x, y and z accordingly. And then the when the addition of x and y is performed the values are unboxed from their Integer types. Number Methods Since the Numbers in Groovy are represented as classes, following are the list of methods available. S.No. Methods & Description 1 xxxValue() This method takes on the Number as the parameter and returns a primitive type based on the method which is invoked. 2 compareTo() The compareTo method is to use compare one number against another. This is useful if you want to compare the value of numbers. 3 equals() The method determines whether the Number object that invokes the method is equal to the object that is passed as argument. 4 valueOf() The valueOf method returns the relevant Number Object holding the value of the argument passed. 5 toString() The method is used to get a String object representing the value of the Number Object. 6 parseInt() This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two. 7 abs() The method gives the absolute value of the argument. The argument can be int, float, long, double, short, byte. 8 ceil() The method ceil gives the smallest integer that is greater than or equal to the argument. 9 floor() The method floor gives the largest integer that is less than or equal to the argument. 10 rint() The method rint returns the integer that is closest in value to the argument. 11 round() The method round returns the closest long or int, as given by the methods return type. 12 min() The method gives the smaller of the two arguments. The argument can be int, float, long, double. 13 max() The method gives the maximum of the two arguments. The argument can be int, float, long, double. 14 exp() The method returns the base of the natural logarithms, e, to the power of the argument. 15 log() The method returns the natural logarithm of the argument. 16 pow() The method returns the value of the first argument raised to the power of the second argument. 17 sqrt() The method returns the square root of the argument. 18 sin() The method returns the sine of the specified double value. 19 cos() The method returns the cosine of the specified double value. 20 tan() The method returns the tangent of the specified double value. 21 asin() The method returns the arcsine of the specified double value. 22 acos() The method returns the arccosine of the specified double value. 23 atan() The method returns the arctangent of the specified double value. 24 atan2() The method Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta. 25 toDegrees() The method converts the argument value to degrees. 26 radian() The method converts the argument value to radians. 27 random() The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic. Print Page Previous Next Advertisements ”;
Groovy – Overview
Groovy – Overview ”; Previous Next 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. Features of Groovy Groovy has the following features − Support for both static and dynamic typing. Support for operator overloading. Native syntax for lists and associative arrays. Native support for regular expressions. Native support for various markup languages such as XML and HTML. Groovy is simple for Java developers since the syntax for Java and Groovy are very similar. You can use existing Java libraries. Groovy extends the java.lang.Object. The official website for Groovy is http://www.groovy-lang.org/ Print Page Previous Next Advertisements ”;
Groovy – Environment
Groovy – Environment ”; Previous Next 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. Once you launch the installer, follow the steps given below to complete the installation. Step 1 − Select the language installer. Step 2 − Click the Next button in the next screen. Step 3 − Click the ‘I Agree’ button. Step 4 − Accept the default components and click the Next button. Step 5 − Choose the appropriate destination folder and then click the Next button. Step 6 − Click the Install button to start the installation. Step 7 − Once the installation is complete, click the Next button to start the configuration. Step 8 − Choose the default options and click the Next button. Step 9 − Accept the default file associations and click the Next button. Step 10 − Click the Finish button to complete the installation. Once the above steps are followed, you can then start the groovy shell which is part of the Groovy installation that helps in testing our different aspects of the Groovy language without the need of having a full-fledged integrated development environment for Groovy. This can be done by running the command groovysh from the command prompt. If you want to include the groovy binaries as part of you maven or gradle build, you can add the following lines Gradle ”org.codehaus.groovy:groovy:2.4.5” Maven <groupId>org.codehaus.groovy</groupId> <artifactId>groovy</artifactId> <version>2.4.5</version> Print Page Previous Next Advertisements ”;