Nowasys.com
Introduction
Groovy is another language for Java Virtual Machine. It’s built on Java, seamlessly integrates with existing Java classes, and compiles to byte code. It’s Object-Oriented (even more where numbers are also objects), and supports the same programming model as Java. However, it’s also a dynamic language with additional powers like scripting and DSL. It reduces scaffolding code that makes it more readable, maintainable and increases productivity.
Groovy is very similar in syntax with java, so developers from java side can learn it easily. It also supports java syntax that means some of java programs can also run over groovy. To learn it we first look at a simple Hello World java program, and then we discuss line by line groovy versions of this java code.
Traditional Java Program
Let’s have a look at simple hello world java program,
public class
HelloWorld {public static void
main(String[] args) {System.
out
.println("Hello World!"
);}
}
HelloWorld is always used as very basic example to learn any programming language. We start with this to easily understandable class
HelloWorld
, which contains entry point method main.
And it prints “Hello World!” on the program console. Now start migrating from this java code to groovy code/script.First step to Groovy
As I mention earlier some of the java programs may also run over groovy without changing a single line of code. Exactly, this program can also run in groovy environment and it behaves same. Although, it can run over groovy but we can’t say it a groovy program. First of all we remove some scaffolding code to improve code readability.
If we look at the very first line of the java code, it’s a class declaration with
public
access modifier.Class and all its methods are by default public in groovy.
So there is no need to explicitly specify
public
with class declaration or even with main
method.
Semicolon is a very basic element in a program structure, in java semicolon is mandatory for statement termination.
Note: But there are some situations where you need to use the semicolons in your groovy application for smooth execution.Semicolons are optional in Groovy.
For now we can remove all the semicolons in our program and it will work fine. Java is a statically typed language, whereas groovy is not that;
Groovy supports dynamic typing.
So we can drop argument’s type information from the
main
declaration.Default return type is void
Based on this default behavior we can ignore
void
from main
method and the signature of main
would be just static
main(args)
.
Lots of new helper methods are added to the groovy JDK. It gives handy methods and shortcuts for some routine tasks such as console printing. You can replace
System.out.println()
with just println()
. At this level we are almost done with scaffolding and lets see how code looks like with these changes.class
GreetWorld {static
main(args) {println("Hello World!")
}
}
It’s really neat and handsome piece of code that is very easy to understand.
Wait for a minute
Groovy is a scripting language as it allows you to write some free form programs that don’t require you to define a class structure. We may use these scripts in Unix shell, in our existing java code or just on command line.
We can optionally omit parentheses for top-level statements (a statement which is just a method call with some parameters). So at the end we leave
main
method back in java and use just the code as script in groovy.
Here it is, the smallest hello world example in groovy presented to you;
println "Hello World!"
Wow! It’s really awesome; the groovyfied code is much more readable, succinct and crispy.
If we compile the above script to bytecode using groovyc, it will generate a single class named after the name of the script file. e.g. if this was saved in HelloWorld.script, a HelloWorld.class file will be the output just like java. When we execute this class, it execute the autogenerated
main(String[] args)
method in the bytecode.Last but not Least
At the end we recap all in few points to summarize as a feature list that we learned in this post.
- Class and all its methods are by default
public
. - Semicolons are optional.
- Dynamic and static typing is supported
- Default return type is
void
- Omit parentheses
- Groovy is a scripting language
Where to go next
You can get more familiar with groovy, some advance concepts in the next part.
September 6, 2012
Java to Groovy by Example – Part 2
Introduction
In the last post we lean very basic concepts from groovy. We also map an example from java to groovy code and then a very simple script. We have also learned that classes are defined in Groovy similarly to Java. Each class in Groovy is a Java class at the bytecode / JVM level. Any methods declared will be available to Java and vice versa. We also learned some of the basic rules/features of groovy;
- Class and all its methods are by default
public
. - Semicolons are optional.
- Dynamic and static typing is supported
- Default return type is
void
- Omit parentheses
- Groovy is a scripting language
Java Sample Code
In this part we look at some advance HelloWorld java program,
public class
GreetWorld {private
String salutation;public void
setSalutation(String salutation) {this
.salutation = salutation;}
public
String getSalutation() {return
salutation;}
public
String greet(String name) {return
salutation
+" "
+ name +"!"
;}
public static void
main(String[] args) {GreetWorld hello =
new
GreetWorld();hello.setSalutation(
"Hello"
);System.
out
.println(hello.greet("Java"
));}
}
It’s a simple class
GreetingWorld
, designed to generate greeting message. There is a private field to preserve salutation with associated setter and getter. You can find a method greet
that used to generate the greeting message, it receives a parameter to associate name with the message. Now let’s see how groovy code looks like for this program.Groovy version
If we look at line 2 to 10, there is a
private
field with associated setter and getter.Groovy support properties - fields and properties have been merged in groovy so that they act and look the same.
Rather than creating a
private
field for salutation
and writing a getter and setter, we can simply declare it as a property without any explicit access modifier. When groovy is compiles to byte code, following rules will apply;- If the data member is declared with an access modifier (
public
,private
orprotected
) then a field is generated. - A data member declared with no access modifier generates a
private
field withpublic
getter and setter (i.e. a property). - If a property is declared
final
theprivate
field is created final and no setter is generated. - You can declare a property and also declare your own getter or setter.
- You can declare a property and a field of the same name, the property will use that field then.
- If you want a
private
orprotected
property you have to provide your own getter and setter which must be declaredprivate
or
protected
.
Note that properties need some kind of identifier: e.g. a variable type (
String
)
Based on these rules, our
salutation
property will be just String salutation
, nothing more. A private
field and associated getter and setter will be provided by Groovy automatically. For calling setSalutaion("Hello"
)
, you need to write hello.salutation = "Hello"
, and for getSalutaion()
, simply hello.salutaion
. This also means that you can call getSalutaion()
and setSalutaion("Hello"
)
from a Java program(invoking our Groovy class) too.
As we move further in our java code, we have a
public
method greet
ahead which receives a String
parameter and returns a String
as well. In java, there has to be a return
statement if your method has the return type.The return statement is optional in Groovy, it return the last statement of the method as return type.
But you can put it if you like to put. In our code, we can remove
return
keyword from the greet
method. As you remember we already remove public
modifier from each of our methods earlier, now code looks simpler and easy to read and understand.
There is another very nice feature that we can apply on this method and that is Groovy’s special string.
The GString, you can embed expressions inside strings.
Inside a normal string, you can put some place holders delimited with curly-brasses like
${someVariable}
or just a dollar sign ahead like $someVariable
, that will be replaced automatically by the value of the variable or expression when the string will be used. So you don’t need to bother about manually concatenating strings.
Java is a strongly typed language; whereas groovy,
Dynamic and static typing is supported – so you can omit the type declarations on methods, fields and variables.
Thus we can get rid of all the types if we wish so, and even don’t mention types with arguments of methods. For dynamic type variables there is a
def
keyword that we can use to define different properties/variables. Here we can change all String
declarations to def
and also can omit argument type in our greet
method.
At this level we are almost done with the
greet
method. As we learned in the last post, groovy is a scripting language as it allows you to write some free form programs that don’t require you to define a class structure. So we don’t need main
method and use just the code as script in groovy outside class.class
GreetWorld {def
salutationdef
greet(name) {"$salutation ${name}!"
}}
def
hello =new
GreetWorld()hello.salutation =
"Hello"
println hello.greet("Groovy")
Voila! It’s really neat and handsome piece of code that is very easy to understand.
Last but not Least
At the end we recap all in few points to summarize as a feature list that we learned in this post.
- Support properties - fields and properties have been merged in groovy so that they act and look the same.
- The
return
statement is optional in Groovy, it returns the last statement of the method as return type. - The GString, you can embed expressions inside strings.
- Dynamic and static typing is supported
Where to go next
You can get more familiar with groovy, some advance concepts in the next part.
July 30, 2012
BitBucket(Git) configuration in xcode
Please follow these steps to configure bitbucket repository in xcode
- Opens xcode and use option ‘connect to a repository’
- Specify following location https://bitbucket.org/location/project.git, i didn’t use username as in repository url in bitbucket
- specify the name as ‘project’ and ‘git’ as type and press clone
- specify folder name and location to clone the repo and press clone again
- there may be an access deny message, don’t be afraid just press try again
- a prompt for user name and password will appear, specify the credentials and press ok
- close xcode and delete if these is any directory as it may created in step 4
- open keychain and find key named bitbucket.org and open it
- go to access control tab and chose very first option ‘allow all application to access this item’ and save changes
- repeat step 1-5, remember this time maybe some error messages will come but be patient and keep trying 2-3 times. Eventually you will succeed.
Note: At this time, due to tight schedule i didn’t investigate the problems. And i knew this method seems not that good, but results are definite.
feel free to comment.
August 12, 2011
Java 7 – Language Enhancements (Part 2)
Previously (in Part 1), we had learned the basic enhancements of Java 7, which includes Binary Literals, Underscores in Numeric Literals, Strings in switch Statements and Type Inference for Generic Instance Creation. Here we will take a look at exception handling updates like try-with-resources statement, catching multiple exceptions in single catch and more. Lets continue our topic:
The try-with-resources Statement
The try-with-resources statement is a
try
statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable
, which includes all objects which implement java.io.Closeable
, can be used as a resource.
The following example reads the first line from a file. It uses an instance of
BufferedReader
to read data from the file. BufferedReader
is a resource that must be closed after the program is finished with it:static
String readFirstLineFromFileWithFinallyBlock(String path)throws
IOException { BufferedReader br =new
BufferedReader(new
FileReader(path));try
{return
br.readLine(); }finally
{if
(br !=null
) br.close(); } }
As we can use a
finally
block to ensure that a resource is closed regardless of whether the try
statement completes normally or abruptly. Java SE 7, provides a new try-with-resources statement to perform the same operation with better managibility:static
String readFirstLineFromFile(String path)throws
IOException {try
(BufferedReader br =new
BufferedReader(new
FileReader(path))) {return
br.readLine(); } }
In this example, the resource declared in the try-with-resources statement is a
BufferedReader
. The declaration statement appears within parentheses immediately after thetry
keyword. The class BufferedReader
, in Java SE 7 and later, implements the interface java.lang.AutoCloseable
. Because the BufferedReader
instance is declared in atry-with-resources statement, it will be closed regardless of whether the try
statement completes normally or abruptly (as a result of the method BufferedReader.readLine
throwing an IOException
).
However, in the first example, if the methods
readLine
and close
both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock
throws the exception thrown from the finally
block; the exception thrown from the try
block is suppressed. In contrast, in the example readFirstLineFromFile
, if exceptions are thrown from both the try
block and the try-with-resources statement, then the method readFirstLineFromFile
throws the exception thrown from the try
block; the exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions.
You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file
zipFileName
and creates a text file that contains the names of these files:public static void
writeToFileZipFileContents(String zipFileName, String outputFileName)throws
java.io.IOException { java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII"); java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName); // Open zip file and create output file with try-with-resources statementtry
( java.util.zip.ZipFile zf =new
java.util.zip.ZipFile(zipFileName); java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset) ) { // Enumerate each entry for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) { // Get the entry name and write it to the output file String newLine = System.getProperty("line.separator"); String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine; writer.write(zipEntryName, 0, zipEntryName.length()); } } }
In this example, the try-with-resources statement contains two declarations that are separated by a semicolon:
ZipFile
and BufferedWriter
. When the block of code that directly follows it terminates, either normally or because of an exception, the close
methods of the BufferedWriter
and ZipFile
objects are automatically called in this order. Note that the close
methods of resources are called in the opposite order of their creation.
The following example uses a try-with-resources statement to automatically close a
java.sql.Statement
object:public static void
viewTable(Connection con)throws
SQLException { String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";try
(Statement stmt = con.createStatement()) { ResultSet rs = stmt.executeQuery(query);while
(rs.next()) { String coffeeName = rs.getString("COF_NAME");int
supplierID = rs.getInt("SUP_ID");float
price = rs.getFloat("PRICE");int
sales = rs.getInt("SALES");int
total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total); } }catch
(SQLException e) { JDBCTutorialUtilities.printSQLException(e); } }
The resource
java.sql.Statement
used in this example is part of the JDBC 4.1 and later API.
Note: A try-with-resources statement can have
catch
and finally
blocks just like an ordinary try
statement. In a try-with-resources statement, any catch
or finally
block is run after the resources declared have been closed.Handling More Than One Type of Exception
In Java SE 7 and later, a single
catch
block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
Consider the following example, which contains duplicate code in each of the
catch
blocks:catch
(IOException ex) { logger.log(ex);throw
ex;catch
(SQLException ex) { logger.log(ex);throw
ex; }
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable
ex
has different types.
The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
catch
(IOException|SQLException ex) { logger.log(ex);throw
ex; }
The
catch
clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|
).
Note: If a
catch
block handles more than one exception type, then the catch
parameter is implicitly final
. In this example, the catch
parameter ex
is final
and therefore you cannot assign any values to it within the catch
block.
Bytecode generated by compiling a
catch
block that handles multiple exception types will be smaller (and thus superior) than compiling many catch
blocks that handle only one exception type each. A catch
block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.Rethrowing Exceptions with More Inclusive Type Checking
The Java SE 7 compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the
throws
clause of a method declaration.
Consider the following example:
static class
FirstExceptionextends
Exception { }static class
SecondExceptionextends
Exception { }public void
rethrowException(String exceptionName)throws
Exception {try
{if
(exceptionName.equals("First")) {throw
new
FirstException(); } else {throw
new
SecondException(); } }catch
(Exception e) {throw
e; } }
This examples’s
try
block could throw either FirstException
or SecondException
. Suppose you want to specify these exception types in the throws
clause of therethrowException
method declaration. In releases prior to Java SE 7, you cannot do so. Because the exception parameter of the catch
clause, e
, is type Exception
, and the catch block rethrows the exception parameter e
, you can only specify the exception type Exception
in the throws
clause of the rethrowException
method declaration.
However, in Java SE 7, you can specify the exception types
FirstException
and SecondException
in the throws
clause in the rethrowException
method declaration. The Java SE 7 compiler can determine that the exception thrown by the statement throw
e
must have come from the try
block, and the only exceptions thrown by the try
block can beFirstException
and SecondException
. Even though the exception parameter of the catch
clause, e
, is type Exception
, the compiler can determine that it is an instance of either FirstException
or SecondException
:public void
rethrowException(String exceptionName)throws
FirstException, SecondException {try
{ // ... }catch
(Exception e) {throw
e; } }
This analysis is disabled if the
catch
parameter is assigned to another value in the catch
block. However, if the catch parameter is assigned to another value, you must specify the exception type Exception
in the throws
clause of the method declaration.
In detail, in Java SE 7 and later, when you declare one or more exception types in a
catch
clause, and rethrow the exception handled by this catch
block, the compiler verifies that the type of the rethrown exception meets the following conditions:- The
try
block is able to throw it. - There are no other preceding
catch
blocks that can handle it. - It is a subtype or supertype of one of the
catch
clause’s exception parameters.
The Java SE 7 compiler allows you to specify the exception types
FirstException
and SecondException
in the throws
clause in the rethrowException
method declaration because you can rethrow an exception that is a supertype of any of the types declared in the throws
.
In releases prior to Java SE 7, you cannot throw an exception that is a supertype of one of the
catch
clause’s exception parameters. A compiler from a release prior to Java SE 7 generates the error, “unreported exception Exception
; must be caught or declared to be thrown” at the statement throw
e
. The compiler checks if the type of the exception thrown is assignable to any of the types declared in the throws
clause of the rethrowException
method declaration. However, the type of the catch parameter e
is Exception
, which is a supertype, not a subtype, of FirstException
andSecondException
.August 9, 2011
Java 7 – Language Enhancements (Part 1)
After nearly five year (on July 2011), Java SE 7 has been released! With Project Coin, the new Fork/Framework, the New File System API (NIO.2), and more. Java SE 7 is an important step in Java’s evolution. There are number of enhancements in the programming language, listed below.
- Binary Literals
- Underscores in Numeric Literals
- Strings in switch Statements
- Type Inference for Generic Instance Creation
- Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
- The try-with-resources Statement
- Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
Binary Literals
In Java SE 7, the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number. Declarative uses of binary literals are demonstrated below:
An 8-bit byte value:
byte ab = (byte)0b00100001;
An 16-bit short value:
short as = (short)0b1010000101000101;
Few 32-bit int values:
int ai = 0b10100001010001011010000101000101;
int ai2 = 0B101; // The B can be upper or lower case.
An 64-bit long value. Note the L suffix:
long al = 0b1010000101000101101000010100010110100001010001011010000101000101L;
Binary literals can make relationships among data more apparent than they would be in hexadecimal or octal. For example, each successive number in the following array is rotated by one bit:
public static final int[] phases = { 0b00110001, 0b01100010, 0b11000100, 0b10001001, 0b00010011, 0b00100110, 0b01001100, 0b10011000}
In hexadecimal, the relationship among the numbers is not readily apparent:
public static final int[] phases = { 0×31, 0×62, 0xC4, 0×89, 0×13, 0×26, 0x4C, 0×98}
You can use binary literals to make a bitmap more readable:
public static final short[] HAPPY_FACE = { (short)0b0000011111100000;
(short)0b0000100000010000;
(short)0b0001000000001000;
(short)0b0010000000000100;
(short)0b0100000000000010;
(short)0b1000011001100001;
(short)0b1000011001100001;
(short)0b1000000000000001;
(short)0b1000000000000001;
(short)0b1001000000001001;
(short)0b1000100000010001;
(short)0b0100011111100010;
(short)0b0010000000000100;
(short)0b0001000000001000;
(short)0b0000100000010000;
(short)0b0000011111100000;}
Uses of binary literals in bit wise operations also help to understand the logic and program structure.
Underscores in Numeric Literals
Any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code. For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator. The following example shows other ways you can use the underscore in numeric literals:
long creditCardNumber = 1234_5678_9012_3456L;long socialSecurityNumber = 999_99_9999L;float pi = 3.14_15F;long hexBytes = 0xFF_EC_DE_5E;long hexWords = 0xCAFE_BABE;long maxLong = 0x7fff_ffff_ffff_ffffL;byte nybbles = (byte)0b0010_0101;long bytes = 0b11010010_01101001_10010100_10010010;
You can place underscores only between digits; you cannot place underscores in the following places:
- At the beginning or end of a number
- Adjacent to a decimal point in a floating point literal
- Prior to an F or L suffix
- In positions where a string of digits is expected
The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:
float pi1 = 3_.1415F; // Invalid; cannot put underscores adjacent to a decimal pointfloat pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal pointlong socialSecurityNumber1 = 999_99_9999_L; // Invalid; cannot put underscores prior to an L suffixint x1 = _52; // This is an identifier, not a numeric literalint x2 = 5_2; // OK (decimal literal)int x3 = 52_; // Invalid; cannot put underscores at the end of a literalint x4 = 5_______2; // OK (decimal literal)int x5 = 0_x52; // Invalid; cannot put underscores in the 0x radix prefixint x6 = 0x_52; // Invalid; cannot put underscores at the beginning of a numberint x7 = 0x5_2; // OK (hexadecimal literal)int x8 = 0x52_; // Invalid; cannot put underscores at the end of a numberint x9 = 0_52; // OK (octal literal)int x10 = 05_2; // OK (octal literal)int x11 = 052_; // Invalid; cannot put underscores at the end of a number
Strings in switch Statements
You can use the String class in the expression of a switch
statement.
statement.
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {String typeOfDay;
switch (dayOfWeekArg) {
case “Monday”:typeOfDay = “Start of work week”;break;
case “Tuesday”:case “Wednesday”:case “Thursday“:typeOfDay = “Midweek”;break;
case “Friday”:typeOfDay = “End of work week”;break;
case “Saturday”:case “Sunday”:typeOfDay = “Weekend”;break;
default:throw new IllegalArgumentException(“Invalid day of the week: “ + dayOfWeekArg);}
return typeOfDay;}
The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-else-then statements.
Type Inference for Generic Instance Creation
You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. For example, consider the following variable declaration:
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):
Map<String, List<String>> myMap = new HashMap<>();
Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map<String, List<String>> type:
Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning
Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:
List<String> list = new ArrayList<>();list.add(“A”);// The following statement should fail since addAll expects Collection<? extends String>list.addAll(new ArrayList<>());
Note that the diamond often works in method calls; however, it is suggested that you use the diamond primarily for variable declarations.
In comparison, the following example compiles:
// The following statements compile:List<? extends String> list2 = new ArrayList<>();list.addAll(list2);
There are some other examples and uses of Type Interface of Generic Instance Creation that we will cover in our next part (Part 2) with remaining three language enhancements.
No comments:
Post a Comment