Friday, 27 May 2016

Java Method Reference ::

Method reference in Java 8 is the ability to use a method as an argument for a matching functional interface. :: (double colon) is the operator used for method reference in Java. An interface with only one method is called a functional interface. For example, Comparable, Runnable, AutoCloseable are some functional interfaces in Java.
Its there all through the Internet saying Java does not have the scope resolution operator (::), in comparison with C++. Its on the way and it will be here with Java 8. Between Java and C++, only the operator :: (double colon) is same, the way it is implemented is different. So we cannot call it as scope resolution operator in Java. It is used for method referencing and not for scope resolution.
Method-Reference

Method References and Lambda Expressions

Method reference using :: is a convenience operator. Method reference is one of the features belonging to Java lambda expressions. Method reference can be expressed using the usual lambda expression syntax format using –> In order to make it more simple :: operator can be used.
In the last tutorial, I gave a list of examples for Java lambda expressions. Which will give detail on different ways of using lambda expressions and I recommend you to go through it using JDK 8. In that article refer example 5 (Lambda Expression Sorting), there we can see method reference used.
Syntax: <classname or instancename>::<methodname>
The method in the functional interface and the passing method reference should match for the argument and returntype. Method reference can be done for both static and class methods. Let us consider the following example to understand this. In AutoCloseable interface we have the method of signature as,
void close throws Exception()
In our example below we have the method with signature,
void close()
So these two methods are matching in terms of argument and returntype (type match). Therefore we can use the method we have written for the functional interface AutoCloseable as a method reference.

Method Reference Example

package com.javapapers.java8;

public class MethodReferenceExample {
 void close() {
  System.out.println("Close.");
 }

 public static void main(String[] args) throws Exception {
  MethodReferenceExample referenceObj = new MethodReferenceExample();
  try (AutoCloseable ac = referenceObj::close) {
  }
 }
}

Constructor References

Constructor reference is similar to method references, wherein used at the place of constructors. It gives best opportunity to use at factory scenarios. in the following example, we are using the zoo constructor with argument as constructor reference. I have provided the equivalent line in lambda expression in the code, just to understand it.

Constructor Reference Example

package com.javapapers.java8;

import java.util.List;
import java.util.ArrayList;

class Zoo {
    private List animalList;
    public Zoo(List animalList) {
        this.animalList = animalList;
  System.out.println("Zoo created.");
    }
}

interface ZooFactory {
    Zoo getZoo(List animals);
}
 
public class ConstructorReferenceExample {

    public static void main(String[] args) {
  //following commented line is lambda expression equivalent
  //ZooFactory zooFactory = (List animalList)-> {return new Zoo(animalList);}; 
  ZooFactory zooFactory = Zoo::new;
  System.out.println("Ok");  
  Zoo zoo = zooFactory.getZoo(new ArrayList());
    }
} 
 
 
SOURCE 

Java JSON Conversion Tutorial

This is a beginner level tutorial on using the Jackson JSON API to convert between Java objects and JSON data. We have been seeing a RESTful services tutorial series in the recent past. I will be using JSON conversion in RESTful services in the coming weeks. This JSON tutorial is to help started with it.
Java 9 features was announced earlier and it includes a JSON parser that is to be bundled with the java core lib. Once that is available, we may not need a third-party library. Till then, we have to go with an external library.
There are two options we can go with. First one is the popular Jackson JSON processor a third party API. Second one is the JSR 353, Java API for JSON Processing and its reference implementation JSON-P. In this tutorial, we will use the popular option, the Jackson JSON processor.

Jackson JSON Processing

Old jackson API was in codehaus.org and presently it is hosted at github and named as FasterXML/jackson. API’s package structure also changed to com.fasterxml.jackson.*. Jackson Processor API library files can be downloaded from http://mvnrepository.com/artifact/com.fasterxml.jackson.core

Java to JSON Conversion

package com.javapapers.java;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JavaToJSON {
 public static void main(String[] args) {
  Animal crocodile = new Animal(1, "Crocodile", "Wild");
  ObjectMapper objectMapper = new ObjectMapper();
  try {
   objectMapper.writeValue(new File("animal.json"), crocodile);
  } catch (IOException e) {
   e.printStackTrace();
  }

  try {
   objectMapper.writerWithDefaultPrettyPrinter().writeValue(
     new File("prettyanimal.json"), crocodile);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

JSON to Java Conversion

package com.javapapers.java;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONToJava {
 public static void main(String[] args) {
  Animal animal = null;
  ObjectMapper objectMapper = new ObjectMapper();
  try {
   animal = objectMapper.readValue(new File("animal.json"),
     Animal.class);
  } catch (IOException e) {
   e.printStackTrace();
  }
  System.out.println(animal);
 }
}

Download Java to JSON to Java Example Project

JSON Conversion Output

animal.json
{"id":1,"firstName":"Crocodile","lastName":"Wild"}
prettyanimal.json
{
  "id" : 1,
  "firstName" : "Crocodile",
  "lastName" : "Wild"
}
 
 
SOURCE 

Java Double Brace Initialization

Double brace initialization is a combination of two separate process in java. There are two { braces involved in it. If you see two consecutive curly braces { in java code, it is an usage of double brace initialization.
Java Double Brace Initialization
First brace is creation of an anonymous inner class. Without considering the second brace if you see the first brace alone then its nothing new for us. We have created many anonymous inner classes in such a way.
Second brace is an initialization block. That too you have seen in it a class for initialization. You may have used a static initialization block. When you use the initialization block for an anonymous inner class it becomes java double brace initialization. The inner class created will have a reference to the enclosing outer class. That reference can be used using the ‘this’ pointer.

Example for double brace initialization

class JavaPapers {
....
....
add(new JPanel() {{
setLayout(...);
setBorder(...);
...
}}
);
}

Uses of double brace initialization

Using double brace initialization, we can initialize collections. Though people say, it is easier to initialize a constant collection using double brace initialization. I don’t see any advantage in using double brace initialization to initialize collections. In jdk 1.7 there is going to be an exclusive construct for that. Then java double brace initialization will become completely obsolete.
...
myMethod(
  new ArrayList() {{
     add("java");
     add("jsp");
     add("servlets");
  }}
);
...

Note on double brace initialization

Serialization of non-static inner class has an issue. The outer class will also get serialized. Because the inner class has got a reference to the outer class and it is implicit. Since it is implicit, it cannot be marked as transient. This issue is also applicable for double brace initialization.

SOURCE

Java Integer Cache

This Java article is to introduce and discuss about Integer Cache. This is a feature introduced in Java 5 to save memory and improve the performance. Let us first have a look at a sample code which uses Integers and showcases the Integer Cache behavior. From there lets study how and why it is implemented. Can you guess the output of the following Java program. Obviously there is some twist in it and that’s why we have this Java article.
package com.javapapers.java;

public class JavaIntegerCache {
 public static void main(String... strings) {

  Integer integer1 = 3;
  Integer integer2 = 3;

  if (integer1 == integer2)
   System.out.println("integer1 == integer2");
  else
   System.out.println("integer1 != integer2");

  Integer integer3 = 300;
  Integer integer4 = 300;
  
  if (integer3 == integer4)
   System.out.println("integer3 == integer4");
  else
   System.out.println("integer3 != integer4");
    
 }
}
What we generally expect is to have both statements to return false. Though the values are same, the compared objects should be different as they will have different references. If you are a beginner, then in Java == checks for object references and equals() checks for values. So here in this case, different objects should be having different reference and so when compared, they should return a false boolean value. What is strange here is, the behavior is not same. Two similar if-conditions returns different boolean values.
Now lets look at the above Java program’s output,
integer1 == integer2
integer3 != integer4
Cache

Java Integer Cache Implementation

In Java 5, a new feature was introduced to save the memory and improve performance for Integer type objects handlings. Integer objects are cached internally and reused via the same referenced objects.
  • This is applicable for Integer values in range between –127 to +127 (Max Integer value).
  • This Integer caching works only on autoboxing. Integer objects will not be cached when they are built using the constructor.
Automatic conversion done by Java compiler from a primitive to its corresponding Java wrapper class type is called autoboxing. This is equal to using the valueOf as follows,
Integer a = 10; //this is autoboxing
Integer b = Integer.valueOf(10); //under the hood
So now we know where this caching should be implemented in the Java JDK source. Lets look at the valueOf method source from Java JDK. Following is from Java JDK 1.8.0 build 25.
   /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
There is a lookup to IntegerCache.cache before constructing a new Integer instance. Then there is a Java class taking care of the Integer caching.

IntegerCache Class

IntegerCache is a private static inner class of Integer class. Lets have a look at that class. It is nicely documented in the JDK and gives most of the information.
 
  /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }
The Javadoc comment clearly states that this class is for cache and to support the autoboxing of values between 128 and 127. The high value of 127 can be modified by using a VM argument -XX:AutoBoxCacheMax=size. So the caching happens in the for-loop. It just runs from the low to high and creates as many Integer instances and stores in an Integer array named cache. As simple as that. This caching is doing at the first usage of the Integer class. Henceforth, these cached instances are used instead of creating a new instance (during autoboxing).
Actually when this feature was first introduced in Java 5, the range was fixed to –127 to +127. Later in Java 6, the high end of the range was mapped to java.lang.Integer.IntegerCache.high and a VM argument allowed us to set the high number. Which has given flexibility to tune the performance according to our application use case. What is should have been the reason behind choosing this range of numbers from –127 to 127. This is conceived to be the widely most range of integer numbers. The first usage of Integer in a program has to take that extra amount of time to cache the instances. 

Cache Enforcement in Java Language Specification

In the Boxing Conversion section of Java Language Specification (JLS) it is stated as follows,
If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between ‘\u0000’ and ‘\u007f’ inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.
A above statement ensures that the reference of objects with values between -128 and 127 should be the same. Reasoning for this decision is also provided as below,
Ideally, boxing a primitive value would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rule above is a pragmatic compromise, requiring that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, the rule disallows any assumptions about the identity of the boxed values on the programmer’s part. This allows (but does not require) sharing of some or all of these references. Notice that integer literals of type long are allowed, but not required, to be shared.
This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

Other Cached Objects

This caching behavior is not only applicable for Integer objects. We have similar caching implementation for all the integer type classes.
  • We have ByteCache doing the caching for Byte objects.
  • We have ShortCache doing the caching for Short objects.
  • We have LongCache doing the caching for Long objects.
  • We have CharacterCache doing the caching for Character objects.
Byte, Short, Long has fixed range for caching, i.e. values between –127 to 127 (inclusive). For Character, the range is from 0 to 127 (inclusive). Range cannot be modified via argument but for Integer, it can be done.

SOURCE

Java Variable Arguments

Varargs is a helper syntax and it enables use of variable number of arguments in a method call. In method definition variable aruguments are indicated by elipsis (…) and is called as ‘variable arity method’ and ‘variable arity parameter’ in java language specification. While invoking the varargs method we can use any number of arguments of type specified and separated by comma.

Varargs Formal Syntax

FormalParameterList:
 LastFormalParameter
 FormalParameters , LastFormalParameter

FormalParameters:
 FormalParameter
 FormalParameters , FormalParameter

FormalParameter:
 VariableModifiers Type VariableDeclaratorId

VariableModifiers:
 VariableModifier
 VariableModifiers VariableModifier

VariableModifier: one of
 final Annotation

LastFormalParameter:
 VariableModifiers Type...opt VariableDeclaratorId
 FormalParameter
In the above note LastFormalParameter gives the elipsis for varargs.
  • We can have only one varargs in a method.
  • Varargs must be the last formal parameter.
  • Is it infinitely variable? No, the variable number of arguments is limited by maximum dimension of a Java array allowed in the respective JVM.

Following is quoted from java language specification and gives information about what is varargs,
If the method being invoked is a variable arity method (§8.4.1) m, it necessarily has n > 0 formal parameters. The final formal parameter of m necessarily has type T[] for some T, and m is necessarily being invoked with k >= 0 actual argument expressions.
If m is being invoked with kn actual argument expressions, or, if m is being invoked with k != n actual argument expressions and the type of the kth argument expression is not assignment compatible with T[], then the argument list (e1, … , en-1, en, …ek) is evaluated as if it were written as (e1, …, en-1, new T[]{en, …, ek}).

Varargs Sample

package com.javapapers.corejava;

public class VarArgSample {

 static int sum(int i, int... marks) {
  int total = 0;
  for (int mark : marks) {
   total = total + mark;
  }
  return total;
 }

 public static void main(String[] args) {

  //invoking with variable arguments
  System.out.println(sum(1, 2, 3));

  //same invocation using an array
  int arr[] = {2,3};
  System.out.println(sum(1, arr));
 }
}

How Varargs Works?

When invoking with variable arguments, compiler matches the argument list from left-to-right with the formal parameters. Once initial set of parameters are matched, then whatever arguments are remaining are constructed as an array and passed to the method. In the given example, value ‘1’ is passed as argument for variable ‘i’ then there are no other arguments remaining except varargs. So the remaining values ‘2, 3’ are constructed as array and passed as parameter. This is how the dynamism is achieved.
Things are just syntactic since once we compile the source changes into array in bytecode. Following is a snapshot from bytecode compiled from the above source.
In bytecode,
 15  invokestatic com.javapapers.corejava.VarArgSample.sum(int, int[]) : int [32] 

What was there before variable arguments?

Variable arguments was introduced long long ago in JDK 1.5 But how did we did the same thing before that? We used java array or collections and to some extent we used method overloading.
When we use method overloading we will not be able to achieve complete variability. Like the below we need to write multiple methods and I don’t think will scale enough.
 static int sum(int i, int j){
  return i + j;
 }

 static int sum(int i, int j, int k){
  return i + j + k;
 }
We can implement the same use case as follows using java array and that is how we achieved variable arguments before varargs.
package com.javapapers.corejava;

public class VarArgSample {

 static int sum(int i, int marks[]) {
  int total = 0;
  for (int mark : marks) {
   total = total + mark;
  }
  return total;
 }

 public static void main(String[] args) {

  //invocation using an array
  int arr[] = {2,3};
  System.out.println(sum(1, arr));
 }

}
Though I didn’t measure performance, I guess that there is no significant overhead in using varargs.

Varargs Gotchas

As stated above java compiler removes elipsis (…) and replaces it with an array in bytecode. JVM is not aware of varargs and so when we use reflection there is no provision to pass variable arguments and we need to construct an array and pass it.

JDK’s use of Varargs

Some example use of varargs can be found in Oracle’s JDK in reflection and formatting.
In java.lang.Class we can find multiple methods using varargs and following is a sample:
    public Method getMethod(String name, Class... parameterTypes)
        throws NoSuchMethodException, SecurityException {
        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
        Method method = getMethod0(name, parameterTypes);
        if (method == null) {
            throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
        }
        return method;
    }
In java.io.PrintStream we have methods using varargs and following is a sample.
   public PrintStream printf(String format, Object ... args) {
        return format(format, args);
    }
We can use the above as,
package com.javapapers.corejava;

public class VarArgSample {

 public static void main(String[] args) {

  System.out.printf( "%25s %n %10s ", "Hello World!", "Java Varargs: Variable Arguments.");

 }

}
 
SOURCE 

Java Annotations

Annotation is code about the code, that is metadata about the program itself. In other words, organized data about the code, embedded within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too.
We have basic java comments infrastructure using which we add information about the code / logic so that in future, another programmer or the same programmer can understand the code in a better way. Javadoc is an additional step over it, where we add information about the class, methods, variables in the source code. The way we need to add is organized using a syntax. Therefore, we can use a tool and parse those comments and prepare a javadoc document which can be distributed separately.

Javadoc facility gives option for understanding the code in an external way, instead of opening the code the javadoc document can be used separately. IDE benefits using this javadoc as it is able to render information about the code as we develop. Annotations were introduced in JDK 1.5

Uses of Annotations

Annotations are far more powerful than java comments and javadoc comments. One main difference with annotation is it can be carried over to runtime and the other two stops with compilation level. Annotations are not only comments, it brings in new possibilities in terms of automated processing.

In java we have been passing information to compiler for long. For example take serialization, we have the keyword transient to tell that this field is not serializable. Now instead of having such keywords decorating an attribute annotations provide a generic way of adding information to class/method/field/variable. This is information is meant for programmers, automated tools, java compiler and runtime. Transient is a modifier and annotations are also a kind of modifiers.


More than passing information, we can generate code using these annotations. Take webservices where we need to adhere by the service interface contract. The skeleton can be generated using annotations automatically by a annotation parser. This avoids human errors and decreases development time as always with automation. Frameworks like Hibernate, Spring, Axis make heavy use of annotations. When a language needs to be made popular one of the best thing to do is support development of frameworks based on the language. Annotation is a good step towards that and will help grow Java.

When Not to Use Annotations

  • Do not over use annotation as it will pollute the code.
  • It is better not to try to change the behaviour of objects using annotations. There is sufficient constructs available in oops and annotation is not a better mechanism to deal with it.
  • We should not what we are parsing. Do not try to over generalize as it may complicate the underlying code. Code is the real program and annotation is meta.
  • Avoid using annotation to specify environment / application / database related information.

Annotation Structure

There are two main components in annotations. First is annotation type and the next is the annotation itself which we use in the code to add meaning. Every annotation belongs to a annotation type.
Annotation Type:
@interface  {
method declaration;
}
Annotation type is very similar to an interface with little difference.
  • We attach ‘@’ just before interface keyword.
  • Methods will not have parameters.
  • Methods will not have throws clause.
  • Method return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types.
  • We can assign a default value to method.

Meta Annotations

Annotations itself is meta information then what is meta annotations? As you have rightly guessed, it is information about annotation. When we annotate a annotation type then it is called meta annotation. For example, we say that this annotation can be used only for methods.
@Target(ElementType.METHOD)
public @interface MethodInfo { }

Annotation Types

  1. Documented
    When a annotation type is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool.
  2. Inherited
    This meta annotation denotes that the annotation type can be inherited from super class. When a class is annotated with annotation of type that is annotated with Inherited, then its super class will be queried till a matching annotation is found.
  3. Retention
    This meta annotation denotes the level till which this annotation will be carried. When an annotation type is annotated with meta annotation Retention, RetentionPolicy has three possible values:
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Developer {
     String value();
    }
    • Class
      When the annotation value is given as ‘class’ then this annotation will be compiled and included in the class file.
    • Runtime
      The value name itself says, when the retention value is ‘Runtime’ this annotation will be available in JVM at runtime. We can write custom code using reflection package and parse the annotation. I have give an example below.
    • Source
      This annotation will be removed at compile time and will not be available at compiled class.
  4. Target
    This meta annotation says that this annotation type is applicable for only the element (ElementType) listed. Possible values for ElementType are, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE.
    @Target(ElementType.FIELD)
    public @interface FieldInfo { }

Built-in Java Annotations

@Documented, @Inherited, @Retention and @Target are the four available meta annotations that are built-in with Java.
Apart from these meta annotations we have the following annotations.
@Override
When we want to override a method, we can use this annotation to say to the compiler we are overriding an existing method. If the compiler finds that there is no matching method found in super class then generates a warning. This is not mandatory to use @Override when we override a method. But I have seen Eclipse IDE automatically adding this @Override annotation. Though it is not mandatory, it is considered as a best practice.
@Deprecated
When we want to inform the compiler that a method is deprecated we can use this. So, when a method is annotated with @Deprecated and that method is found used in some place, then the compiler generates a warning.
@SuppressWarnings
This is like saying, “I know what I am doing, so please shut up!” We want the compiler not to raise any warnings and then we use this annotation.

Custom Annotations

We can create our own annotations and use it. We need to declare a annotation type and then use the respective annotation is java classes.
Following is an example of custom annotation, where this annotation can be used on any element by giving values. Note that I have used @Documented meta-annotation here to say that this annotation should be parsed by javadoc.
/*
 * Describes the team which wrote the code
 */
@Documented
public @interface Team {
    int    teamId();
    String teamName();
    String teamLead() default "[unassigned]";
    String writeDate();    default "[unimplemented]";
}

Annotation for the Above Example Type

... a java class ...
@Team(
    teamId       = 73,
    teamName = "Rambo Mambo",
    teamLead = "Yo Man",
    writeDate     = "3/1/2012"
)
public static void readCSV(File inputFile) { ... }
... java class continues ...

Marker Annotations

We know what a marker interface is. Marker annotations are similar to marker interfaces, yes they don’t have methods / elements.
/**
 * Code annotated by this team is supreme and need
 * not be unit tested - just for fun!
 */
public @interface SuperTeam { }
... a java class ...
@SuperTeam public static void readCSV(File inputFile) { ... }
... java class continues ...
In the above see how this annotation is used. It will look like one of the modifiers for this method and also note that the parenthesis () from annotation type is omitted. As there are no elements for this annotation, the parenthesis can be optionally omitted.

Single Value Annotations

There is a chance that an annotation can have only one element. In such a case that element should be named value.
/**
 * Developer
 */
public @interface Developer {
    String value();
}
... a java class ...
@Developer("Popeye")
public static void readCSV(File inputFile) { ... }
... java class continues ...

How to Parse Annotation

We can use reflection package to read annotations. It is useful when we develop tools to automate a certain process based on annotation.
Example:
package com.javapapers.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Developer {
 String value();
}
package com.javapapers.annotations;
public class BuildHouse {
 @Developer ("Alice")
 public void aliceMethod() {
  System.out.println("This method is written by Alice");
 }
 @Developer ("Popeye")
 public void buildHouse() {
  System.out.println("This method is written by Popeye");
 }
}
package com.javapapers.annotations;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class TestAnnotation {
 public static void main(String args[]) throws SecurityException,
   ClassNotFoundException {
  for (Method method : Class.forName(
    "com.javapapers.annotations.BuildHouse").getMethods()) {
   // checks if there is annotation present of the given type Developer
   if (method
     .isAnnotationPresent(com.javapapers.annotations.Developer.class)) {
    try {
     // iterates all the annotations available in the method
     for (Annotation anno : method.getDeclaredAnnotations()) {
      System.out.println("Annotation in Method '" + method
        + "' : " + anno);
      Developer a = method.getAnnotation(Developer.class);
      if ("Popeye".equals(a.value())) {
       System.out.println("Popeye the sailor man! "
         + method);
      }
     }
    } catch (Throwable ex) {
     ex.printStackTrace();
    }
   }
  }
 }
}
Output:
Annotation in Method 'public void com.javapapers.annotations.BuildHouse.aliceMethod()' : @com.javapapers.annotations.Developer(value=Alice)
Annotation in Method 'public void com.javapapers.annotations.BuildHouse.buildHouse()' : @com.javapapers.annotations.Developer(value=Popeye)
Popeye the sailor man! public void com.javapapers.annotations.BuildHouse.buildHouse()

apt / javac for Annotation Processing

In previous version of JDK apt was introduced as a tool for annotation processing. Later apt was deprecated and the capabilities are included in javac compiler. javax.annotation.processing and javax.lang.model contains the api for processing.

SOURCE

Java null and NullPointerException

NullPointerException: An attempt was made to use a null reference in a case where an object reference was required.
NullPointerException is more famous to Java programmers, than fashion to Paris. When you start breaking the beurette and Pipette in Java lab, first thing you will get is NullPointerException. In this tutorial lets discuss about, do we need NullPointerExceptions and why does it comes and how to solve a NullPointerException (NPE). Also we need to study about null, which causes the NullPointerException.
Before going into detail, is NullPointerException named correctly? i think it should have beed name as NullReferenceException as correctly done in dotNet. Hey, I heard there are no pointers in Java atleast for namesake! then how come it is NullPointerException. You might appreciate this after reading the complete story.

Why did NullPointerException became so famous?

Error description for NullPointerException doesn’t tells the name of the null variable, which caused the exception. The programmer, mostly beginner spends lot of time to figure out where the error is. Also it happens so frequently that you get annoyed. Error reported just says the line number at which it occurred. NullPointerException is a RuntimeException.
In a code block, if there is a possibility of null pointer exception it should be checked and reported at compile time. Yes there is language ‘Nice’ which does it and there is no chance of getting a NullPointerException.

Scenarios when we get NullPointerException:

Java API documentation says that NullPointerException can be thrown, when there is an attempt to use null where an object is required. That is you are trying to access a reference where there is no value. Main scenarios are when, calling the instance method of a null object and accessing or modifying the field of a null object. When you pass null to a method when it expects a real value. It means to say that null object is used illegally.
So how do we get a null object in place? When you create an object and not initializing it. When you access a method and it returns a null object.

How to solve a NullPointerException in Java?

It is simple, put a null check! Surround your object with if statement like
Object mayBeNullObj = getTheObjectItMayReturnNull();
if (mayBeNullObj != null) { // to avoid NullPointerException
mayBeNullObj.workOnIt();
}

If you think it is so easy and the subject is done, then you are caught wrong. I think the above method is ugly! Imagine a situation where you work using many third party components (methods), how many if conditions will you put to solve one NullPointerException? It will pollute the code. When you deal with third party components and it is supplied with poor javadoc (it always happens!), there is no other option available but to use this ugly way. If not, you can avoid this by using a better design of software. A simple example is to have proper ‘required field’ check at GUI level, when your business logic expects an operation on a given object. Then you can depend on your design and omit the if-null-check which beefs up your code.
There is a default value for all primitives in Java and it is initialized with it. Why not have something like that for objects? So that null will never exist and the whole world’s NullPointerException problem is solved. Why do we have null in Java? We need it to use in places where there is absense of information. We are depicting real world information in Java programming using OOPS. Zero is absense of information, can I use zero as a replacement for null. No! In mathematics itself zero can be used when there is absense of information, only when you are dealing with numbers. For example when you are working in real algebra, you have a null set not number zero. Of course the size of that is zero ;-) So in real world 0 and absense of existense are not same. Therefore one cannot use empty Sting “” or zero in place of null in java.
Too much techie information for the academics, you may omit this paragraph without loosing integrity of information.
Java Virtual Machine (JVM) specification gives 24 operations that throws NullPointerException. They are aaload, aastore, arraylength, athrow, baload, bastore, caload, castore, daload, dastore, faload, fastore, getfield, iaload, iastore, invokeinterface, invokespecial, laload, lastore, monitorenter, monitorexit, putfield, saload, sastore. Of those 21 would be supplemented by versions that would not throw NullPointerException. The 3 that wouldn’t be supplemented are athrow, monitorenter and monitorexit. 16 of the 21 involve loading or storing the primitive types from or in arrays; 2 involve the same with object references; 2 more: getfield & putfield; 2 for method invocation; and 1 for the length of the array.

Guidelines to solve or deal with NullPointerException:

  • Prune null at design level, and don’t allow the possibilty of having null value in object where the business scenario doesn’t allows.
  • Always declare variables just before where they are going to be used.
  • Always use if-null-check when you don’t have control over the object’s value. (Ugly but no choice!)
    Put the string constant first from left when comparing values with a String variable.
  • Religiously initialize (fill) arrays immediately after declaration. Arrays mostly causes NullPointerException.
  • Return Iterators instead of Lists. This allows to return empty Iterator and the consumer need not do if-null-check. NullPointerException will not creep into this pattern.
  • Erroneously don’t declare a variable inside a constructor, it will hide the instance variable.


SOURCE