Saturday 3 January 2015

Java 7:Basic Features

Java 7 features:
1.       Strings allowed in Switch condition. 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-then-else statements.
2.       Catch multiple exceptions in single catch block using ‘|’,hence lesser byte code.
e.g. Catch narrower exception then use pipe “|” and then broader execption.
catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}


3.       try with resources:
a.       Automatic resource management.
                                                               i.      Resource is automatically closed after code exits from try block normally or due to exception. Resource must implement new interface java.lang.AutoCloseable which is extended by java.io.Closeable ,otherwise code will not compile.
                                                             ii.      The main thing to be noted
b.      Due to automatic resource management we don’t need finally to close the resource connection hence lesser byte code
c.       In old try-finally if the exception is thrown in both try and finally the exception which gets propagated to calling method is exception from finally block not the exception from try block. Whereas in case of try with resource the exception which gets propagated to calling method is exception occurred in try block.

e.g.
static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}


d. If try contains multiple resources then ,when try block is executed or exception occurs the resources are closed in reverse order to to manage dependency.

4. Diamond Operator : Type inference for generic instance creation
e.g.
List<String> list = new ArrayList<>();

Saturday 27 December 2014

SOAP_VS_REST

Sr. No. SOAP(Simple object access protocol) REST(Representational State Transfer)
1 Soap is protocol REST is architectural style
2 Function driven. Data driven.
To login, add/delete data we have different services Login add/delete can be done in single service
3 Use WSDL(Web Service Description Language) as contract. WADL(Web Application Description Language)
4 Stateful. Stateless.
Server maintenance the state of every client request as apart of session. Server does not maintain the state of every client request.State is transferred by client to server as part of every request.
5 Heavy weight. As depends on XML markup Light weight.
6 Supports different web protocols like HTTP,TCP,SMTP Support only HTTP
7 Support only XML format Support XML,JSON,TEXT,YAML formats
8 Distributed.Communication through multiple endpoints. Point to point communication.
9 SOAP has successful/retry logic built in  clients to deal with communication failures by retrying
10 Strongly typed language. Not strongly typed.

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