Saturday 1 August 2015

Core java interview question and answer

Cohesion and Coupling deal with the quality of an OO design. Generally, good OO design should be loosely coupled and highly cohesive. Lot of the design principles, design patterns which have been created are based on the idea of “Loose coupling and high cohesion”.


The aim of the design should be to make the application:
  • easier to develop
  • easier to maintain
  • easier to add new features
  • less Fragile.

Coupling:

Coupling is the degree to which one class knows about another class. Let us consider two classes class A and class B. If class A knows classB through its interface only i.e it interacts with class B through its API then class A and class B are said to be loosely coupled.
If on the other hand class apart from interacting class B by means of its interface also interacts through the non-interface stuff of class Bthen they are said to be tightly  coupled. Suppose the developer changes the class B‘s non-interface part i.e non API stuff then in case of loose coupling class A does not breakdown but tight coupling causes the class to break.
So its always a good OO design principle to use loose coupling between the classes i.e all interactions between the objects in OO system should use the APIs. An aspect of good class and API design is that classes should be well encapsulated.
Another related thoughts on Coupling.

Cohesion:

Cohesion is used to indicate the degree to which a class has a single, well-focused purpose. Coupling is all about how classes interact with each other, on the other hand cohesion focuses on how single class is designed. Higher the cohesiveness of the class, better is the OO design.
Benefits of Higher Cohesion:
  • Highly cohesive classes are much easier to maintain and less frequently changed.
  • Such classes are more usable than others as they are designed with a well-focused purpose.
Single Responsibility principle aims at creating highly cohesive classes.

public static void main (String args[])
 
The method is public because it is accessible to the JVM to begin execution of the program.

It is Static because it is available for execution without an object instance. You may know that you need an object instance to invoke any method. So you cannot begin execution of a class without its object if the main method was not static.

It returns only a void because, once the main method execution is over, the program terminates. So there can be no data that can be returned by the Main method

The last parameter is String args[]. This is used to signify that the user may opt to enter parameters to the java program at command line.

What are Checked and Unchecked Exception?
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. e.g., IOException
Unchecked exceptions are Runtime Exception. With an unchecked exception, however, the compiler doesn't force programmers to catch the exception or declare it in a throws clause. In fact, programmers may not even know that the exception could be thrown. E.g. StringIndexOutOfBoundsException.

What are different types of inner classes?
Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. e.g., outer.Inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface. Because local classes are not members, the modifiers public, protected, private, and static are not usable.
Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.



Interface VS Abstract class
S.No
Abstract
Interface
1
May or maynot contain constructor
Cannot contain constructor
2
May or maynot have abstract methods
All methods are public and abstract by default
3
May or maynot contain static/final fields
All fields are public, static and final by default
4
Abstract class is extended by a class
Interface is implemented by a class
5
Cannot
An interface can extend multiple interfaces
6
Keyword is Abstract
Keyword is Interface
An interface can only extend another Interface; an interface can only be implemented by a class.
Serialization
Serialization is simply turning an existing object into a byte array.
This byte array represents:
·   the class of the object
·   the version of the object
·   The internal state of the object.

This byte array can then be used between JVM's running the same code to transmit/read the object, Serialization is used in below cases:
·    
    Persistence: If you want to store the state of a particular operation in a database, it can be easily serialized to a byte array, and stored in the database for later retrieval.

·   Deep Copy: If you need an exact replica of an Object, and don't want to go to the trouble of writing your own specialized clone() class, simply serializing the object to a byte array, and then de-serializing it to another object achieves this goal.

·   Caching: Really just an application of the above, but sometimes an object takes 10 minutes to build, but would only take 10 seconds to de-serialize. So, rather than hold onto the giant object in memory, just cache it out to a file via serialization, and read it in later when it's needed.

·   Cross JVMSynchronization: Serialization works across different JVMs that may be running on different architectures.

Difference between Serializable and Externalizable in Java?

Instead of implementing Serializable interface,  a developer can also implement Externizable interface which thus extends Serializable, developer is responsible for implementing writeExternal() and readExternal() methods to have control over reading and writing serialized objects.By implementating java.io.Serializable, you get "automatic" serialization capability for objects of your class. No need to implement any other logic, it'll just work. The Java runtime will use reflection to figure out how to marshal and unmarshal your objects.In earlier version of Java, reflection was very slow, and so serializaing large object graphs(e.g. in client-server RMI applications) was a bit of a performance problem. To handle this situation, the java.io.Externalizable interface was provided, which is like java.io.Serializable but with custom-written mechanisms to perform the marshalling and unmarshalling functions (you need to implement readExternal and writeExternal methods on your class). This gives you the means to get around the reflection performance bottleneck.

What is Transient?
The keyword transient in Java used to indicate that the variable is not serialized.
By default all the variables in the object is converted to persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the necessity to transfer across the network.
For example, you may have fields that are derived from other fields, and should only be done so programmatically, rather than having the state be persisted via serialization.

Intern method in String pool
intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.

interning is automatic for String literals, the intern() method is to be used on Strings constructed with new String().
String s1 = "Rakesh";
String s2 = new String("Rakesh").intern();
 
s1==s2 return true in above case now.
 
Immutable objects

Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include Stringand Integer.
Immutable objects greatly simplify your program since they:

1) Are simple to construct, test, and use.
2)      Are automatically thread-safeand have no synchronization issues.
3)      Do not need a copy constructor.
4)      Allow hashCodeto use lazy initialization, and to cache its return value
5)      Do not need to be copied defensively when used as a field

 You can make a class immutable by following these guidelines:
1)      Ensure the class cannot be overridden- make the class final, or use static factories and keep constructors private
2)      Make fields private and final
3)      Do not provideany methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state

Singleton Class
The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objectsif the situation changes.
Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets. For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.
Implementing Singletons:
The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance:

// File Name: Singleton.java
public class Singleton {
   private static Singleton singleton = new Singleton( );
   /* A private Constructor prevents any other class from instantiating.   */
   private Singleton(){ }
      /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton");
   }
}

// File Name: SingletonDemo.java
public class SingletonDemo {
   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}
This would produce following result:
demoMethod for singleton

Operator overloadingbasically means to use the same operator for different data types. And get different but similar behavior because of this.
Java indeed doesn't support this but any situation where something like this could be useful, you can easily work around it in Java.
The only overloaded operator in Java is the arithmetic + operator. When used with numbers (int, long, double etc.), it adds them, just as you would expect. When used with String objects, it concatenates them

What is the benefit of Generics in Collections Framework?
Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.
This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator.
The Java Classloader
It is a part of the JRE that dynamically loads Java classes into the JVM, The class loader is responsible for locating libraries, reading their contents, and loading the classes contained within the libraries,
When the JVM is started, three class loaders are used:
·The bootstrap class loader loads the core Java libraries located in the <JAVA_HOME>/jre/libdirectory. This class loader, which is part of the core JVM, is written in native code.
·The extensions class loader loads the code in the extensions directories (<JAVA_HOME>/jre/lib/ext,or any other directory specified by the java.ext.dirs system property). It is implemented by the sun.misc.Launcher$ExtClassLoader class.
·The system class loader loads code found on java.class.path, which maps to the CLASSPATH environment variable. This is implemented by the sun.misc.Launcher$AppClassLoader class.

JAR hellis a term similar to DLL hell used to describe all the various ways in which the classloading process can end up not working. Three ways JAR hell can occur are:
·A developer or deployer of a Java application has accidentally made two different versions of a library available to the system. This will not be considered an error by the system. Rather, the system will load classes from one or the other library. Adding the new library to the list of available libraries instead of replacing it, may see the application still behaving as though the old library is in use, which it may well, be.
·Two libraries (or a library and the application) require different versions of the same third library. If both versions of the third library use the same class names, there is no way to load both versions of the third library with the same classloader.
·The most complex JAR hell problems arise in circumstances that take advantage of the full complexity of the classloading system. A Java program is not required to use only a single "flat" classloader, but instead may be composed of several (potentially very many) nested, cooperating classloaders.


Difference in throws and throw
throwsis used with method definition to throw if any exception caught in the method
throwis use for explicitly throwing a particular exception.

Can we overload methods that differ only by static keyword?
We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is same).

Output: Compiler Error, cannot redefine foo()

Can we Override static methods in java?
We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is ‘No’.
If a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class

Polymorphism
Capability of a method to do different things based upon the object it is acted upon.
·Method Overloading(Compile time): Same method name but different arguments
·Method Overriding(Run Time): Same method name as well as same arguments, used in case of Inheritance

Rules for method overriding:
·The argument list should be exactly the same as that of the overridden method.
·The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.
·The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass method is declared public then the overridding method in the sub class cannot be either private or protected.
·Instance methods can be overridden only if they are inherited by the subclass.
· A method declared final cannot be overridden.
· A method declared static cannot be overridden but can be re-declared.
·If a method cannot be inherited, then it cannot be overridden.
·A subclass in a different package can only override the non-final methods declared public or protected.
·An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method.
·Constructors cannot be overridden.

Throwable Class Hierarchy

What is the difference between JAR and WAR files?
JAR files (Java ARchive) allows aggregating many files into one, it is usually used to hold Java classes in a library. WAR files (Web Application aRchive) stores XML, java classes, and JavaServer pages for Web Application purposes.
What is Marker Inteface?
Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface. Marker interface in Java is used to indicate something to compiler or JVM.Example of market interface is Serializable, Clonnable and Remote interface.

Difference in Error and Exception?
An Error is an irrecoverable condition occurring at runtime like out of memory error. These kinds of jvm errors cannot be handled at runtime.Exceptions are because of condition failures, which can be handled easily at runtime.

Why is String immutable?
·   It is mainly for security reasons. String is used as parameter in network connection, database urletc. It can be easily attacked if it is mutable·Immutability of String solves some synchronization issues, it makes the String thread safe· To support StringPool facility· To cache the hashcode of String To support class loading mechanism in which String is used as arguments. String being mutable results in wrong class being loaded

Java Annotations
 Annotations provide data about a class that is not part of the programming logic itself. Annotations are defined via the @interface annotation before the class name.
·         @Retention you define if the annotation should be retained at runtime or not.
RetentionPolicy.SOURCE
RetentionPolicy.CLASS
RetentionPolicy.RUNTIME
· The @Target annotation lets you define where this annotation can be used, e.g. the class, fields, methods, etc.
ElementType.ANNOTATION_TYPE
ElementType.CONSTRUCTOR
ElementType.FIELD
ElementType.LOCAL_VARIABLE
ElementType.METHOD
ElementType.PACKAGE
ElementType.PARAMETER
ElementType.TYPE
· The @Inherited annotation signals that a custom annotation used in a class should be inherited by subclasses inheriting from that class.
·The @Documentedannotation is used to signal to the JavaDoc tool that your custom annotation should be visible in the JavaDoc for classes using your custom annotation

Java provides three built-in annotations:
· @Override – When we want to override a method of Super class, we should use this annotation to inform compiler that we are overriding a method. So when super class method is removed or changed, compiler will show error message. Learn why we should always use java override annotation while overriding a method.
·@Deprecated – when we want the compiler to know that a method is deprecated, we should use this annotation. Java recommends that in javadoc, we should provide information for why this method is deprecated and what is the alternative to use.
·@SuppressWarnings – This is just to tell compiler to ignore specific warnings they produce, for example using raw types in java generics. Its retention policy is SOURCE and it gets discarded by compiler.

Difference in String, StringBuilder and StringBuffer?
·Since String is an immutable class every time a new String is created and older one is discarded which creates lots of temporary garbage in heap. If String are created using String literal they remain in String pool.
·To resolve this problem Java provides us two Classes StringBuffer and StringBuilder. Both are mutable means you can modify a StringBuffer/StringBuilder object once you created it without creating any new object.
·String Buffer is an older class but StringBuilder is relatively new and added in JDK 5. StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization
Methods in Object Class
· protected Object clone() throws CloneNotSupportedException
      Creates and returns a copy of this object.
·public boolean equals(Object obj)
      Indicates whether some other object is "equal to" this one.
· protected void finalize() throws Throwable
      Called by the garbage collector on an object when garbage collection determines that there are no more references to the object
· public final Class getClass()
      Returns the runtime class of an object.
·public int hashCode()
      Returns a hash code value for the object.
·public String toString()
      Returns a string representation of the object.
·           public final void notify()
·           public final void notifyAll()
·           public final void wait()
Clone method
If a class, or one of its superclasses, implements the Cloneableinterface, you can use the clone() method to create a copy from an existing object. To create a clone, you write:
aCloneableObject.clone();
Object's implementation of this method checks to see whether the object on which clone() was invoked implements the Cloneable interface. If the object does not, the method throws a CloneNotSupportedException exception.
public Object clone() throws CloneNotSupportedException

Types of Cloning
Shallow Cloning: it is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects. By default shallow copy is used in Java. Shallow clone only copies the top level structure of the object not the lower levels.
If  a = clone(b) , then b.equals(a)
Deep Cloning: Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.
Singleton in Threads
From Java 5 onwards volatile variable guarantee can be used to write thread safe singleton by using double checked locking pattern but there are many other simpler alternatives to write thread-safe singleton are available like using static fieldto initialize Singleton instance or using Enum as Singleton in Java.
1)      Since Enum instances are by default final in Java, it also provides safety against multiple instances due to serialization. One point worth remembering is that, when we talk about thread-safe Singleton, we are talking about thread-safety during instance creation of Singleton class and not when we call any method of Singleton class.
public enum Singleton{
    INSTANCE;
    public void show(){
        System.out.println("Singleton using Enum in Java");
    }
}
//You can access this Singleton as Singleton.INSTANCE
Singleton.INSTANCE.show();
2)      You can also create thread safe Singleton in Java by creating Singleton instance during class loading. Static fields are initialized during class loading and Classloaderwill guarantee that instance will not be visible until it’s fully created. Only disadvantage of using static field is that this is not a lazy initialization and Singleton is initialized even before any clients call there getInstance() method

public class Singleton{
    private static finalSingleton INSTANCE = new Singleton();
 
    private Singleton(){ }

    public static Singleton getInstance(){
        returnINSTANCE;
    }
    public void show(){
        System.out.println("Singleon using static initialization in Java");
    }
}
//Here is how to access this Singleton class
Singleton.getInstance().show();

Java Sorting Algorithms
A sorting algorithm is an algorithm that puts elements of a list in a certain order.
1. Bubble sort in java: Also referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.

2.The selection sort is a combination of searching and sorting. During each pass, the unsorted element with the smallest (or largest) value is moved to its proper position in the array. The number of times the sort passes through the array is one less than the number of items in the array. In the selection sort, the inner loop finds the next smallest (or largest) value and the outer loop places that value into its proper location.


3.Insertion sort is a simple sorting algorithm; it builds the final sorted array one item at a time. It is very efficient for small data sets. Insertion sort iterates through the list by consuming one input element at each repetition, and growing a sorted output list. On a repetition, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

The worst case input is an array sorted in reverse order. The set of all worst case inputs consists of all arrays where each element is the smallest or second-smallest of the elements before it. In these cases, every iteration of the inner loop will scan and shift the entire sorted subsection of the array before inserting the next element.

4. Quicksort or partition-exchange sort is a fast sorting algorithm, which is using divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists.

Steps to implement Quick sort:
1) Choose an element, called pivot, from the list. Generally pivot can be the middle index element.
2) Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way).
3) Recursively apply the above steps to the sub-list of elements with smaller values and separate the sub-list of elements with greater values.


5.Merge sortis a divide and conquer algorithm.

Steps to implement Merge Sort:
1) Divide the unsorted array into n partitions, each partition contains 1 element. Here the one element is considered as sorted.

2) Repeatedly merge partitioned units to produce new sub lists until there is only 1 sub list remaining. This will be the sorted list at the end.


Merge sort is a fast, stable sorting routine with guaranteed O(n*log(n)) efficiency. When sorting arrays, merge sort requires additional scratch space proportional to the size of the input array. Merge sort is relatively simple to code and offers performance typically only slightly below that of quicksort.

Which sort algorithm does Java follow?

Arrays.sort()method uses quicksort for arrays of primitives and merge sort for arrays of objects.
· Quicksort is faster than merge sort and costs less memory.
· Quicksort is not stable, i.e. equal entries can change their relative position during the sort, this means that if you sort an already sorted array, it may not stay unchanged.
· Merge sort requires making a clone of the array.
· Quicksort is O(nlogn) on average and O(n2) in the worst case. At the same time, other sorting algorithms are studied which are O(nlogn) in the worst case (like mergesort and heapsort).


Java Search Algorithms
1.Linear search or sequential search is a method for finding a particular value in a list that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found.
·Linear search is the simplest search algorithm. For a list with n items, the best case is when the value is equal to the first element of the list, in which case only one comparison is needed. The worst case is when the value is not in the list (or occurs only once at the end of the list), in which case n comparisons are needed.
·Linear searches don't require the collection to be sorted.

2. A binary search or half-interval search algorithm finds the position of a specified value (the input "key") within a sorted array. In each step, the algorithm compares the input key value with the key value of the middle element of the array. If the keys match, then a matching element has been found so its index, or position, is returned. Otherwise, if the sought key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special "Not found" indication is returned.
· Every iteration eliminates half of the remaining possibilities. This makes binary searches very efficient - even for large collections.
· Binary search requires a sorted collection. Also, binary searching can only be applied to a collection that allows random access (indexing).
·Worst case performance: O(log n)
· Best case performance: O(1)

XML Parser
XML Parser provides way how to access or modify data present in an XML document. Java provides multiple options to parse XML document.
1) Dom Parser - DOM parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal and we iterate through the Node and Node List to get the content of the XML. DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data
2)      SAX Parser - SAX parser doesn’t load the complete XML into the memory, instead it parses the XML line by line triggering different events as and when it encounters different elements like: opening tag, closing tag, character data and comments and so on. This is the reason why SAX Parser is called an event based parser.

3) StAX Parser - StAX stands for Streaming API for XML. The SAX Parser pushes the data but StAX parser pulls the required data from the XML. StAX is a "pull" API. SAX is a "push" API.
StAX can do both XML reading and writing. SAX can only do XML reading.



1 comment: