Tuesday, 24 November 2015

Java Annotations Tutorial and Example

What is Java Annotations & How to Create It?

Java annotations are used to provide meta data for your Java code. Being meta data, Java annotations do not directly affect the execution of your code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection.

Classes, methods, variables, parameters and packages may be annotated. 

Some Built-in Java Annotations

  • @Override - Checks that the method is an override. Causes a compile error if the method is not found in one of the parent classes or implemented interfaces.
  • @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used.
  • @SuppressWarnings - Instructs the compiler to suppress the compile time warnings specified in the annotation parameters.

Java Annotation Types

  1. Build-time instruction (Development time) - Retention is set to source only, such annotation are use full at source level only and removed by compiler while generating binary class file.
    e.g. @Documented
  2. Compiler  instructions (Deployment time) - Retention is set be to class only. Such annotation are used by compiler or deployment tools for taking some specific action e.g. producing compile time error in case of some rule or guideline violation.
    e.g. @Depricated, @Override
  3. Runtime instructions (Execution time) - Retention is set run-time, such annotation are retained in class file are used for deducing some meta information at run time and may effect run time processing. These annotations are not ignored by VM.
    e.g. @Entity, @Test

Use cases

Annotations can be used for many different purposes, the most common ones are:
  • Information for the compiler - Annotations can be used by the compiler to produce warnings or even errors based on different rules. One example of this kind of usage is the Java 8 @FunctionalInterface annotation. This one makes the compiler to validate the annotated class and check if it is a correct functional interface or not.
  • Documentation - Annotations can be used by software applications to measure the quality of the code like FindBugs or PMD do or generate reports automatically like Jenkins, Jira or Teamcity.
  • Code generation - annotations can be used to generate code or XML files automatically using metadata information present in the code. A good example of this is the JAXB library.
  • Runtime processing - Annotations that are examined in runtime can be used for different objectives like unit testing (Junit), dependency injection (Spring), validation, logging (Log4J) ,data access (Hibernate) etc.

Creating Custom Annotation

Rules of Thumb for Defining Java Annotation Types

Here are some rules-of-thumb when defining an annotation type:
  1. Annotation declaration should start with an 'at' sign like @, following with an interface keyword, following with the annotation name.
  2. Method declarations should not have any parameters.
  3. Method declarations should not have any throws clauses.
  4. Return types of the method should be one of the following:
    • primitives
    • String
    • Class
    • enum
    • array of the above types

The Java reflection API

  • getAnnotations(): Returns all annotations for the given element, also the ones that are not explicitly defined in the element definition.
  • isAnnotationPresent(annotation): Checks if the passed annotation in available or not in the current element.
  • getAnnotation(class): Retrieves an specific annotation passed as parameter. Returns null if this annotation is not present for the given element.
This class is implementing by java.lang.Classjava.lang.reflect.Method and java.lang.reflect.Field among others, so can be used basically with any kind of Java element.

 CLASS:Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.
 RUNTIME:Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
 SOURCE: Annotations are to be discarded by the compiler.

Create Custom Annotation Example

Define new custom annotation

@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface CustomAnnotationMethod {
public String author() default "danibuiza";
public String date();
public String description();

Use on Class or Method

@CustomAnnotationClass( date = "2014-05-05" )
public class AnnotatedClass {

@CustomAnnotationMethod( date = "2014-06-05", description = "annotated method" )
public String annotatedMethod() {
return "nothing niente";

Write a program to Process Annotations

public static void main(String[] args) throws Exception {
Class < AnnotatedClass > object = AnnotatedClass.class;
// Retrieve all annotations from the class
Annotation[] annotations = object.getAnnotations();
for (Annotation annotation: annotations) {

// Checks if an annotation is present
if (object.isAnnotationPresent(CustomAnnotationClass.class)) {
// Gets the desired annotation
Annotation annotation = object.getAnnotation(CustomAnnotationClass.class);
// the same for all methods of the class
for (Method method: object.getDeclaredMethods()) {
if (method.isAnnotationPresent(CustomAnnotationMethod.class)) {
Annotation annotation = method.getAnnotation(CustomAnnotationMethod.class);

Thursday, 19 November 2015

Improve Software Quality

Improve Software Quality= Development Improvement + Management Improvement

Development Improvement

1. Get the Requirements Right
               Impact on Quality: Meet business requirements; achieve a satisfying user experience.
               Benefit: Less rework means less retesting and fewer cycles, which greatly reduces the overall effort.
2. Design Applications to Lessen Bug Risk
               Impact on Quality: Reduce defects.
               Benefit: Simpler, cleaner designs result in code that is simpler, cleaner, and easier to test and rework.
3. Implement Best Practices, Follow Design Patterns & Principles, Increase Reusability
               Impact on Quality: Improves Quality and Performance
               Benefit: Decreases unexpected bugs. Best Practices and Design Principle improves skills, reduces waste and improves quality. Fast development & thus Developers/Managers could give more time about Quality and user experience.
4. Test Smarter to Test Less & Optimize the Use of Testing Tools
               Impact on Quality: Reduce defects.
               Benefit: A focus at risk areas on testing the most crucial. Automation frees resources from mundane testing to focus on the highest-priority tests and increases test cycles' repeatability.

Management Improvement

1. Fine-Tune Team/Individual Goals to Include Quality
               Impact on Quality: Meet business requirements; achieve a satisfying user experience; reduce defects.
               Benefit:Team members perform according to their incentives, making quality improvement part of their goals reinforces desirable behavior.
2. Define Quality and Broadcast Simple Quality Metrics
               Impact on Quality: Achieve a satisfying user experience. Increases Quality
               Benefit: Highly visible metrics keep quality top of mind for the entire team and expose when efforts fall short.
3. Reuse Knowledge and Experience
               Impact on Quality: Reduce defects.
               Benefit: Reusing ideas, documents, and expertise avoids making the same mistakes again. Makes the organization's best problem-solving experiences reusable.

4. Continues Feedbacks
               Impact on Quality: Improves Quality and User experience.
               Benefit: Whatever has been learned about the product, the processes that produced it, or any other feedback will improve improves Quality and User experience.

Wednesday, 18 November 2015

New features in Java 8

Java 8 included following new Features.

    1. Lambda expressions
    2. Method references
    3. Default Methods (Defender methods)
    4. A new Stream API (Parallel operations)
    5. Optional Class
    6. A new Date/Time API
    7. Nashorn, the new JavaScript engine (Java + JavaScript)
    8. Removal of the Permanent Generation
    9. Other New Features

1. Lambda Expressions

The biggest new feature of Java 8 is language level support for lambda expressions (Project Lambda). Java lambda expressions are Java's first step into functional programming. A Java lambda expression is thus a function which can be created without belonging to any class. A lambda expression can be passed around as if it was an object and executed on demand.

Following are the important characteristics of a lambda expression

    • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
    • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
    • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
    • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.


parameter -> expression body


1. With type declaration

MathOperation addition = (int a, int b) -> a + b;  

2. With out type declaration

MathOperation subtraction = (a, b) -> a - b;  

3. With return statement along with curly braces

MathOperation multiplication = (int a, int b) -> { return a * b; };  
4. Without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b;

More Info

2. Method references(Parallel operations)

You use lambda expressions to create anonymous methods. Method references help to point to methods by their names. A method reference is described using :: (double colon) symbol.
You can use replace Lambda Expressions with Method References where Lamdba is invoking already defined methods.
You can’t pass arguments to methods Reference

There are four kinds of method references:

  1. Reference to a static method  ContainingClass::staticMethodName
  2. Reference to an instance method of a particular object
  3. Reference to an instance method of an arbitrary object of a particular type
  4. Reference to a constructor ClassName::new


List names = new ArrayList();



More Info

3. Default Methods (Defender methods)

Default methods can be provided to an interface without affecting implementing classes as it includes an implementation just by adding the keyword default before the method’s access modifier.
Modify one interface in JDK framework breaks all classes that extends the interface. Default methods enable us to add new or default functionalities/behavior to existing interfaces without breaking the classes that implements that interface.
After introducing Default Method, it seems that interfaces and abstract classes are same. However, they are still different concept in Java 8.


public interface vehicle {

  default void print(){

 System.out.println("I am a vehicle!");


4. A new Stream API.
Don't confuse with InputStream and OutputStream from Java I/O. This is Completely different thing. Streams adhere to a common Pipes and Filters software pattern.

A Stream is a free flowing sequence of elements. They do not hold any storage as that responsibility lies with collections such as arrays, lists and sets. Every stream starts with a source of data, sets up a pipeline, processes the elements through a pipeline and finishes with a terminal operation. They allow us to parallelize the load that comes with heavy operations without having to write any parallel code. A new package java.util.stream was introduced in Java 8 to deal with this feature.


List<String>  myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");

.filter(s -> s.startsWith("c"))

Deeper Look at Streams

The Stream interface is defined in java.util.stream package. Starting from Java 8, the java collections will start having methods that return Stream. This is possible because of another cool feature of Java 8, which is default methods. Streams can be defiled as a sequence of elements from a source that supports aggregate operations.
The source here refers to a Collection, IO Operation or Arrays who provides data to a Stream. Stream keeps the order of the data as it is in the source. Just like functional programming languages, Streams support Aggregate Operations. The common aggregate operations are filter, map, reduce, find, match, sort. These operations can be executed in series or in parallel.

The Streams also support Pipelining and Internal Iterations. The Java 8 Streams are designed in such a way that most of its stream operations returns Streams only. This help us creating chain of various stream operations. This is called as pipelining. The pipelined operations looks similar to a sql query.

5. Optional Class

Optional is a new container type that wraps a single value, if the value is available. So it's meant to convey the meaning that the value might be absent. 

Optional is an attempt to reduce the number of null pointer exceptions in Java systems, by adding the possibility to build more expressive APIs that account for the possibility that sometimes return values are missing. By using Optional, and never working with null, you could avoid null checks altogether.


public Optional<String> getOptionalNullString(){



java.util.Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

More Info

6. A new Date/Time API

Working with New Date and Time objects

By default LocalDate/Time classes will use the system clock in the default time zone. We can change this by providing a time zone or an alternative Clock implementation.

They are also coming with better time zone support with ZoneOffSet, ZoneId, ZonedDateTime or OffsetDateTime. 
Parsing and Formatting of Dates are also revamped with new DateTimeFormatter class.
Clock, which can be used to get current instant, date and time using time zone.

Deeper Look at Date/Time API

New date and time API is located inside java.time package and some of the key classes are following.
Instant - Represents a timestamp
LocalDate - Represents a year-month-day date without time.
LocalTime - Represents a time without dates.
LocalDateTime - Combines date and time in one class.
We can use the plus and minus methods to add or subtract specific amounts of time. Note that these methods always return a new instance (Java 8 date/time classes are immutable).


LocalDate tomorrow = LocalDate.now().plusDays(1);
Some information can be obtained without providing a specific date. For example, we can use the Year class if we need information about a specific year:


Year currentYear = Year.now();
  boolean isLeap = currentYear.isLeap();
  Classes like LocalDate and ZonedDateTime provide a human view on time. However, often we need to work with time viewed from a machine perspective. For this we can use the Instant class which represents timestamps. 


  Instant now = Instant.now(); // current time
  Instant fromUnixTimestamp = Instant.ofEpochSecond(1262347200); // from unix timestamp, 2010-01-01 12:00:00
  Instant fromEpochMilli = Instant.ofEpochMilli(1262347200000l); // same time in millis 
Periods and Durations
  Period and Duration are two other important classes. Like the names suggest they represent a quantity or amount of time. A Period uses date based values (years, months, days) while a Duration uses seconds or nanoseconds to define an amount of time.


  LocalDate firstDate = LocalDate.of(2010, 5, 17); // 2010-05-17
  LocalDate secondDate = LocalDate.of(2015, 3, 7); // 2015-03-07
  Period period = Period.between(firstDate, secondDate);

  Instant firstInstant= Instant.ofEpochSecond( 1294881180 ); // 2011-01-13 01:13
  Instant secondInstant = Instant.ofEpochSecond(1294708260);
  Duration between = Duration.between(firstInstant, secondInstant);
More Info 
More Examples

7. Nashorn, the new JavaScript engine (Java + JavaScript)

Nashorn is a JavaScript engine for the JVM that is released with Java 8. It has replaced the existing Rhino engine.

As JavaScript is getting popular on server-side programming (like Node.js).

The Nashorn javascript engine can either be used pragmatically from java programs or by utilizing the command line tool jjs, which is located in $JAVA_HOME/bin. If you plan to work with jjs you might want to put a symbolic link for simple access:

Example 1:

$  jjs -scripting heredocs.js

Example 2:

ScriptEngineManager engineManager =  new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("nashorn");
engine.eval(new FileReader("src/sample2/mustache.js"));
engine.eval("print('Hello World!');");

8. Removal of the Permanent Generation

Permanent Generation memory space is completely removed.
The good news is that it means no more java.lang.OutOfMemoryError: PermGen space problems and no need for you to tune and monitor this memory space any more.


The PermSize and MaxPermSize JVM arguments are ignored and a warning is issued if present at start-up.
Metaspace: A new memory space is born.
More Info

9. Other New Features

Concurrent accumulators

One of the most common scenarios in concurrent programming is updating of numeric counters accessed by multiple threads.

Parallel operations

You can think of this as an extension of iterators where the actual operation of extracting the next item from a collection on which to operate is carried out by an iterator. An exciting possibility opened by this design pattern is to enable operations carried out on long arrays such as sorting, filtering and mapping to be carried out in parallel by the framework. 


String abc= String.join(" ", "Java", "8");

Type Annotations

List<@Nullable String>
@NotNull String[] arr;
new @NonEmpty @Readonly List(myNonEmptyStringSet)
new @Interned MyObject()

Functional Interfaces


Stamped Locks

The problem is that the ReadWriteLock can be super slow (up to 10x), which kind of defeats its purpose. Java 8 introduces a new ReadWrite lock – called StampedLock.

Controlling OS Processes

Launching an OS process from within your code is right there with JNI calls – it’s something you do half-knowing there’s a good chance you’re going to get some unexpected results and some really bad exceptions down the line.

Exact Numeric Operations

Math class geared towards protecting sensitive code from implicit overflows, by throwing an unchecked ArithmeticException when the value of an operation overflows its precision.
int safeC = Math.multiplyExact(bigA, bigB); // will throw ArithmeticException if result exceeds +-2^31

Secure Random Generation

Java 8 has added a new method called SecureRandom.getInstanceStrong() whose aim is to have the JVM choose a secure provider for you.


Other Milestones Completed
New Features in Java SE 8 PPT
8 Great Java 8 Features
Video: New Features in Java SE 8
JDK 8 Features