Category Archives: Java

Interview questions on JAVA Annotations

Interview questions on JAVA annotations can be found at the below link

http://saravananmtech.wordpress.com/2014/08/16/java-interview-questions-annotations/

1) What is Java Annotations and why we need it?
2) How to create a basic Annotation?
3) What is Retention or Retention Policy in Annotations?
4) What is Target in Annotations?
5) How to define an annotation is only applicable to methods and fields?
6) How to print annotations in run-time?
7) What is marker annotations?
8) How to define default values to the members of the custom annotations?

With answers for the above questions, is available at the following link

http://saravananmtech.wordpress.com/2014/08/16/java-interview-questions-annotations/

Happy interviews 🙂

Advertisements

How a Java pass by reference to an object works into a method as argument?

Please click on the below link

https://saravananmtech.wordpress.com/2014/08/13/how-a-java-pass-by-reference-to-an-object-works-into-a-method-as-argument/

 

 

Serialization and Deserialization of an Object in JAVA

Follow the below link:

 

http://saravananmtech.wordpress.com/2012/11/03/serialization-and-deserialization-of-an-object-in-java/

Sort custom objects using Java Comparable interface!!

http://saravananmtech.wordpress.com/2012/10/22/sort-custom-objects-using-java-comparable-interface/

Final method inlining optimization in JAVA

http://saravananmtech.wordpress.com/2012/10/22/final-method-inlining-optimization-in-java/

Generic Programming in JAVA – Very Simple!!

http://saravananmtech.wordpress.com/2012/10/21/generic-programming-in-java-very-simple/

Custom Annotation using JAVA Annotation

Annotations

–          To embed meta-data in source file. (data about data is called as meta-data)

User for:

  1. Code Analysis
  2. Compiler checking
  3. Documentation

 Program that demonstrates the custom annotation and how to find the annotation types associated with a method.

import java.lang.annotation.*;

import java.lang.reflect.*;

 

/*

 * My custom annotation ‘Complete’

 */

@Retention(RetentionPolicy.RUNTIME)

@Target (ElementType.METHOD)

@interface Complete {

      int percentage() default 100;

      boolean isComplete() default false;

}

 

/*

 * My custom annotation ‘Author’

 */

@Retention(RetentionPolicy.RUNTIME)

@Target (ElementType.METHOD)

@interface Author {

      String name() default “SARAVANAN SIVAJI”;

}

 

/*

 * My custom annotation ‘Dummy’. Discarded by Compiler.

 */

@Retention(RetentionPolicy.SOURCE)

@Target (ElementType.METHOD)

@interface Dummy {

      String name() default “SARAVANAN SIVAJI”;

}

 

/*

 * This class finds annotation type associated with a method display(), at runtime using Reflection.

 */

public class CustomAnnotation {

      //Method annotated with ‘Author’, ‘Dummy’ and ‘Complete’ annotation type     

      @Author

      @Dummy

      @Complete (percentage=200, isComplete=true)

      public void display() {      

      }

      public static void main(String [] args) {

            try {

                  // Use reflection to retrieve a reference to the specified methods

                  Method method = CustomAnnotation.class.getMethod(“display”,null);

                  // Check which methods, if any, are tagged by Complete

                  boolean yes = method.isAnnotationPresent(Complete.class);

                  if(yes){

                        Annotation ann = method.getAnnotation(Complete.class);

                        //Print the members of this annotation

                        System.out.println(“The percentage attribute of Complete annotation on ” + method.getName() + ” method is ” + ((Complete)ann).percentage());

                        System.out.println(“The isComplete attribute of Complete annotation on ” + method.getName() + ” method is ” + ((Complete)ann).isComplete());

                        // Print all annotations against this method

                        printAnnotations(method);

 

                  }

            }

            catch(NoSuchMethodException cnse) {

                  System.out.println(cnse);

            }

      }

      static public void printAnnotations(AnnotatedElement e) {

            //Following line prints method signature

            System.out.println(“Printing annotations for method “+ e.toString());

            //Fetch all the annotation type associated with this method

            Annotation[] annotations = e.getAnnotations();

            for (Annotation a : annotations) {

                  System.out.println(“Annotation found: ” + a.annotationType().getName());

            }

      }

 

 

}

 

Output:

The percentage attribute of Complete annotation on display method is 200

The isComplete attribute of Complete annotation on display method is true

Printing annotations for method public void CustomAnnotation.display()

Annotation found: Author

Annotation found:Complete

 

 

 

 

 

Generic Programming in JAVA- An overview

Generics

–          Ensures Type safety.

–          Type check performed by compiler at compile-time.

–          No type casting required in most cases.

–          Minimize run-time error ClassCastException highly.

–          Ensures backward compatibility by means of Type Erasure.

Erasure

Erasure is the process occurs at compile time, which converts the Generic code to legacy code.  Type Erasure erases all type parameter information and inserts appropriate casts in the code.

Key Points:

Type parameters must be class types.  Using primitive types will cause compiler error.

Declaring and initializing a generic collection:

Prior to Java 5, a collection can take any kind of objects and when you retrieve, you will get only objects of type ‘Object’ always.

With reference to below code, list must be both declared and initialized with the generic type. The below code compiles successfully. Here list can accept any arbitrary object.

List list = new ArrayList<Integer>();

list.add(5);

list.add(4);

list.add(“10”);

for(Iterator<Integer> it = list.iterator(); it.hasNext(); ) {

int value = it.next()*10;

System.out.println(value);

}

The above code throws ClassCastException during Runtime.

The Object class:

With reference to below code, List<T> cannot be assigned to List<Object>. If allowed, an object of any type could be inserted into the list.

public class GenericIssue2 {

public static void main(String[] args) {

List<Employee> list = new ArrayList<Employee>();

List<Object> olist = list; //compiler error

List list1 = new ArrayList<Employee>(); //Warning: Raw assignment

olist = list1;    //Warning

}

}

class Employee {}

Casting:

Sometimes manual casting required when using generics.

With reference to below code, objects can be added or retrieved into the list, which are treated as Employee.

public class GenericIssue3 {

public static void main(String[] args) {

List<Employee> list = new ArrayList<Employee>();

list.add(new Developer()); //we can add child objects

Developer d = list.get(0); //compiler error

}

}

class Employee {}

class Developer extends Employee {}

Manual casting required as like below

List<Employee> list = new ArrayList<Employee>();

list.add(new Developer()); //we can add child objects

Developer d = (Developer) list.get(0); //Manual casting required

Adding subclasses:

public class GenericIssue4 {

public static void main( String [] args ) {

List<Developer> dlist = new ArrayList<Developer>();

dlist.add(new Developer());

List<Tester> tlist = new ArrayList<Tester>();

tlist.add(new Tester());

List<Employee> elist = new ArrayList<Employee>();

elist.add(new Developer());//type casting required when retrieved.

elist.add(new Tester());//type casting required when retrieved.

elist.addAll(dlist); //add any subclasses of Employee

elist.addAll(tlist); //add any subclasses of Employee

System.out.println(elist);

}

}

class Employee {}

class Developer extends Employee {}

class Tester extends Employee {}

Using subclasses:

List<Employe> list = new ArrayList<Employe>();

List<Object> olist = list; //compiler error

User wildcard syntax here: ?

List<Employe> list = new ArrayList<Employe>();

List<? extends Object> olist = list; //works now!!

Bounded types and wildcards:

See the below code, specially Sum class

 

public class GenericBoundedDemo {

public static void main(String[] args) {

Integer intArray[] = new Integer[] {1,2,3,4,5};

Sum<Integer> si = new Sum<Integer>(intArray);

System.out.println(si.getSumTotal());

Float flotArray[] = new Float[] {20.0f, 30.0f};

Sum<Float> sf = new Sum<Float>(flotArray);

System.out.println(sf.getSumTotal());

}

}

class Sum<T extends Number> {

T [] numberArray;

Sum(T[] objArray) {

numberArray = objArray;

}

double getSumTotal() {

double result = 0.0;

for(T t : numberArray) {

result = result + t.doubleValue();

}

return result;

}

}

Output:

15.0

50.0

Here the Sum class is bound by Number.  The object of type T can call any method of Number.

The objective of this program is, I want a generic class which gives the sum of array of numbers of any type. The result of total must be in double.

Java wildcard element <?> specifies an unknown type.  We can write a generic method that can accept any type of object.

See the revised code below, added a generic Compare method

public class GenericBoundedDemo {

public static void main(String[] args) {

Integer intArray[] = new Integer[] {1,2,3,4,5};

Sum<Integer> si = new Sum<Integer>(intArray);

System.out.println(si.getSumTotal());

Float flotArray[] = new Float[] {20.0f, 30.0f};

Sum<Float> sf = new Sum<Float>(flotArray);

System.out.println(sf.getSumTotal());

System.out.println( si.Compare(sf) );

}

}

class Sum<T extends Number> {

T [] numberArray;

Sum(T[] objArray) {

numberArray = objArray;

}

double getSumTotal() {

double result = 0.0;

for(T t : numberArray) {

result = result + t.doubleValue();

}

return result;

}

String Compare(Sum<?> ob) { //accepts any type of Sum object

if(this.getSumTotal() > ob.getSumTotal())

return “greater”;

else if(this.getSumTotal() < ob.getSumTotal())

return “smaller”;

else

return “equal”;

}

}

Wildcard element acts on collection and which is the supertype of all kinds of collections. The wildcard element itself can be bounded as like below,

String Compare(Sum<? extends Number> ob) {

if(this.getSumTotal() > ob.getSumTotal())

return “greater”;

else if(this.getSumTotal() < ob.getSumTotal())

return “smaller”;

else

return “equal”;

}

Method Overloading in JAVA – A demo

Follow the below URL

http://saravananmtech.wordpress.com/2012/10/16/method-overloading-demo/

How to create immutable objects in JAVA?

Follow the below URL:

http://saravananmtech.wordpress.com/2012/10/12/how-to-create-immutable-objects-in-java/

cool!!