Wednesday 29 February 2012

Annotations






What is Annotation?
Annotations are nothing but  meta-data added to the Java Elements.   Annotations define a java type exactly similar to Classes,Enums,Interfaces and they can be applied to several Java Elements.

How Custom Annotation are created?
Annotation is defined using @ along with interface keyword.There are two meta annotations required to create custom annotationas shown in example below.

          @Target(ElementType.CLASS)
          @Retention(RetentionPolicy.CLASS)
          public @interface Author
          {
                   String name();
          }

The Meta-Annotations that would be covered in the forthcoming sections are,
  • Target Annotation @Target: It specifies to which java elements annotation can be applied. Different java elements to which annotations can be applied are

1.    FIELD :can be applied only to Java Fields

2.    METHOD: can be applied only to methods.

3.    PARAMETER : can be applied only  to method parameters

4.    CONSTRUCTOR: can be applied only to constructor.

5.    LOCAL_VARIABLE : can be appliedonly  to Local variable

6.    TYPE: can be applied to java Type. e.g. It can be applied to Classes,interfaces,Enum .

7.    ANNOTATION_TYPE: can be applied only to Annotation Types.

8.    PACKAGE: can be applied to a Package.

  • Retention Annotation @Retention :This meta annotation specifies till what time annotations can be retained and when they can be discarded

1.    SOURCE :Retain annotation in source file and discard them at compile time

2.    CLASS : Retain annotation in class file and discard them at run time

3.    RUNTIME : Retain annotation at runtime and never discard them



How annotations are retrieved or read?
Annoations onece defined and used in some class we can read them using reflection package methods like getAnnotations().We have to first obtain the refrence to the class which contains or uses the Annotaions then we cane write code like given below
Class classObj = MyAnnotedClass.class;
Annotation[] annotations = classObj.getAnnotations();
for (Annotation annotation : annotations) {
 }


Inner Classes


What is inner class and what are types of inner classes

Inner class is a class which is defined in other class or method. Inner class shares special relationship with outer class. As inner class is defined within class it can access private variables of outer class

There are four types of inner classes

                1) Member Inner Class: First outer class instance needs to be created then inner class instance is created on outer class instance .i.e new Outer().new Inner();

2) Static Inner Class: To access static inner class we don’t need to create instance of outer class. Static inner class can be directly accessed as static variables of class. i.e. new Outer. Inner();

3) Method local Inner Class: These classes are defined within method

4) Anonymous Inner Class: Anonymous inner classes are created and instantiated on the fly. They don’t have any name. They can’t use keywords like extends or implement. Therefore they can either subclass of any class or implementer of any interface. They are terminated with semicolon.

e.g.

Runnable myRunnable=new Runnable(){

public void run()

{

}

};

We can define new methods in inner class, but due to polymorphism we can only call methods defined in supertype reference either interface or class

Anonymous inner class can be passesd as arguments to methods




Java Basics

What are class declaring rules?
  • Every Java File has single Public class declared in it
  • Java File can have multiple non public classes declared in it
  • If there is a Public class declared in Java File then name of java file must be same as Public class name
  • If there are only non public classe in java file then name of Java file can be anything
  • Java File can have multiple non public classes containing main method in each one of them
  • At the top of Java File there is a package statement then thre are import statements and then the class declartaion

What is constructor?

Constructor is special kind of method which initialize the instance of class.Constructor don't have any return type even void also.When class is instatiated constructor is called first and it initialize the instance variables of class.If we don't provide any constructor jvm provides the default no argumant constructor.The first call in constructor is this() call to same class constructor or super() call to super class constructor.If we add parameterized constructor then jvm don't provide the default constructor


Differences between method overloading and method overriding?



Overloading

Overriding
Arguments or Parameters
Must change
Number and Type of parameters must be same
Return type
Can change
No except Covariant return types which are available from Java 1.5 version
Access
Can change
Accessibility cannot be narrowed but it can be broaden.
Exceptions
Can change
Can throw all,none or only subset of exception thrown by overridden method.Can’t throw broader or new checked exceptions
Method Invocation
Method invocation happens at compile time.
Method invocation happens at runtime time.


Can Static methods be overriden?
No Static method cann't be ovveriden
Can Super Class Method be called from Overriden Method in its Subclass ?
Yes Using super Keyword in subclass method we can call the super class verison
What is super and this


If subclass contains extra methods which are not there in super class tehn can we invoke these methods on superclass reference?



No. At compile time we will get error

e.g.

Class A

{

Public void getX(){}

}

Class B

{

Public void getX(){}

Public void getY(){}

}

A a=new B();

a.getX(); //Compiles

a.getY();//Compilation fails
Differentiate between Interface and Abstract class?
Abstract Class
Interfaces
Abstract class can have both abstract and non abstarct methods
Interface have only abstract methods




If class contains one or more abstract methods that class must be declared as abstract

Interface is by default abstract.All methods are in interfaces are abstract by default
Class can extend single abstract class
Class can implement multiple interfaces
Abstract class can be public ,private ,protected
Interface can only be Public
Abstract class can contain instance variables
Interface contain only static variable
Abstract class has a constructor as it falls in Object class hierarchy
Interface don’t have constructor
Abstract classes are faster
Interfaces are slow because there is extra level of indirection in calling the actual class’s method
Can Interface implement any other interface or extend any other Interfaces?
Interface cannot implement any other interface but Interface can extend any number of other interfaces

Can a class be decalred as abstarct withot any abstarct methods?
Yes. Abstract class can have zero or more abstract methods

Can abstract class contains main() method?
Yes as main() method is static it don't require the instance of class to invoke it
Can we declare interface methods as private?
No :Implicitly methods of interface are public and member variables are implicitly public static

Can we declare interface methods as static?
No. Interface contains only non static abstarct methods


What if main method is declared as private?
Program compiles fine but at run time ‘Main method not public’ exception will be thrown

What if static is removed from main method?
Program compiles and at run time throws error ‘NoSuchMethodError’

What if we declare public void static main()?
Nothing order doesn’t matter. Program compiles and runs properly

What happens if we don’t pass string array as argument to main method?
Program compiles and at run time throws error ‘NoSuchMethodError’

If we don’t provide the argument to main method at runtime then the String array will be empty or null ?
String array will be empty but never null we can test by printing args.length which prints ‘0’

Can there be multiple nonpublic calluses in java file each containing main method
Yes

Can abstract class contain main method ?
Yes

What is final?
Final means constant
We can use Final in below three places
1) Final Classes: Can’t be sub classed
2) Final methods: Can’t be overridden
3)Final variables : value once assigned while declaring final variable cannot be changed

If object reference marked as final can we change the state of final object
Yes Object reference is marked as final means we cannot assign new object to that object reference.
But we can change the internals (state) of object whose reference is marked as final
Analogy :We can change the internals of our home but not the address of our home


Java Execption Handling

1) What is Exception hierarchy?
At the top there is Throwable class .It has two Su classes Exception and Error.

Exception: It is defined as some unwanted condition which abnormally terminates the program flow. Recovery from exceptions occurred is possible using java exception handling

Error: It is a condition from which recovery is not possible.e.g. OutOFMemor Error



2) What are different types of Exception

Three are basically two types of Exceptions

1) Checked Exception: Checked Exceptions are those which compiler forces to user to handle or declare. It excludes RuntimeExceptions and its subclasses

2)Unchecked Exceptions :All exceptions extending RunTimeException are unchecked .As Java programmers cannot judge at compile time whether these Runtime exceptions will occur or not therefore Runtime Exceptions are unchecked Also Error and its subclasses are unchecked. As recovery from Error is not possible Error is unchecked

3) How the exception is handled in java

1) Using try-catch-finally

2) Using throws clause with method

3) Using throw keyword

4) What are rule about try-catch-finally

1) Every try must have either catch or finally

2) try-catch-finally must be in sequence i.e first try then catch then finally

3) There should not be any piece of code between try block and catch block or finally block

4)If there are multiple catch blocks having parent child relationship of Exception then first subclass exception must be caught then the super class exception is to be caught

5) What is finally block

Finally block is guaranteed to be executed .All clean up code goes into finally block.e.g.code for closing database connection

6)If try block contains return or break statement as last line whether the finally block executed

Yes. Return or break statement will execute of finally block



7) If try block contains System. exit statement as last line whether the finally block executed

No.JVM will terminate no further execution after System.exit

8) How custom Exceptions are created

By extending the Exception class

9) What is difference between throw and throws

Throw is used to throw exception at any line in java code

Throws is use with method to declare that this method doesn’t handle the exception its delegating task of exception handling to calling method

10)What is difference between NoClassDefFoundError Vs ClassNotFoundException


ClassNotFoundException is exception.It occurs when class is not found in classpath


NoClassDefFoundError is an error.It does not mena that the required class not found in classpath. Class was found but it may contain some static block which tries to load some another class whose definition jvm is not able to load at runtime




Serialization

1) What is Serialization?In order to transfer object over network or store the object in file system it must be converted in to byte stream. Serialization converts object to byte steram.To Serialize an object our class must implement Serializable interface.Serializable is a Marker interface i.e. has no methods to override. It must be implemented to tell the JVM that object of this class must be converted to byte stream

2) How to customize serialization
To customize serialization we can implement Externalizable interface and override readExternal() and writeExternal() methods

3) Can object having references to no serialized objects be serialized
No.In this case NotSerializableException will be thrown at runtime.

4)Whether static variable are also serialized
No. Static variables are not serialized
5)What is transient variable
Transient variables are skipped from serialization. Transient variables take default value after deserialization

4) If subclass is serializable but super class is not serializable what will happen?
In this case during deserialization super class constructor runs and the inherited variables from super class gets initialized with default values

5) If we want to serialize array or collection whether all members needs to be serialized?
Yes

Object class methods (Overriding equals() and hashCode())

What are the methods in object class
equals()
toString()
hashCode()
wait ()
notify()
notifyAll()
clone()
finalize()

Why toString needs to be overridden
If we use the object class’s toString method and try to print our object then it will print something like ClassName@hashcode which doesn’t provide any meaningful information
In order to provide meaningful information when object .toString is called toString must be overridden

Why equals need to be overridden?
If we create two objects having same state and compare it using obj1.equals(obj2) then it will always return false as these two objects are distinct object even though meaningfully they are equal as their state is equal
Therefore meaningfully compare two objects on their state we need to override equals method

What is hashCode?
As per Object class implementation of hashCode,HashCode is memory address of an object mapped to integer
Why we need to override hashCode method?
Actual hashCode is in symmetry with equals. There are some rules about symmetry
If equals returns true for two objects hashcode must be same
If equals returns false then hashCode can be same or different

If we are using our custom object as a key in hash base collection then it’s necessary to implement equals and hashCode methods
Because when we use put() method in hash based collection some hashing algorithm is applied over hashCode and the location of bucket to store the key value is identified
When we use get() method of hash based collections then first the location of bucket is found out using hashCode then the equals method is invoked to found out the actual equal object in the bucket

What the bucket implements?
Bucket actually implements the linked list

What if equals method is overriden and hashCode is not overridden?
If equals is overridden but hashCode is not then hashCode will inherit the implementation from Object class.
In Object class hashCode() is nothing but memory address of an object mapped to integer
Therefore even though two objects are meaningfully equal as equal returns true their hashCode will be always different as these are two different objects with different memory locations.
Therefore in hashbased collections if we use such object as a key then we will not able to retrieve the value. We will get null when we try to retrieve the value


What if equals method is overriden and returns false and hashCode is overridden but returns the same value 1?
This is perfectly valid.In this case different objects will be placed in same bucket in the next node of linked list
This will affect the performance while retrieving elements using get() from hash based collection
As get() method has to iterate through whole linked list and check the equals() method to find out actual object


OOPS Basics

1.What are the basic four principle concepts of OOPS?
The Basic four OOPS Concepts are

  • Abstraction :Abstarction means showing only the essential features of a class and hiding the all background details.It is Design Time Concept
  • Polymorphism : Single Name Multiple Forms
There are three ways by which Polymorphism can be achived in Java
1)Method Overloading
2)Method Overriding of Classes
3)Method Overriding of Interfaces

There are two types of Polymorphism
1)RunTime Polymorphism:As which methods to call is decided at runtime it is also know as late binding or Dynamic binding e.g Method Overriding
2)Compile Time Polymorphism :As call to methods are resolved at compile time it is known as Early Binding or Static binding.e.g. Method Overloading
  • Inheritance :It is a IS-A relationship.Inheritance enables code reuse.Child Class Inherites traits of its Parent class.Thus child class can reuse functionality of its Parent class and can aslo add extr features
  • Encapsulation :Encapsulation enables data hiding.Object encapsulates Attributes and Properties.Access to these Attributes and Properties are restricted from outside world and provided only the appropriate access
2.What is Aggreagtion and Composition
  • Aggregation.: Class contains object of another class as its member.Its a HAS-A relationship
  • Composition : Its special type of Aggragation.Differnce from Aggragation is that the member object must exist for existance of Main Class object