Wednesday 18 November 2015

What is the difference between Shallow cloning and Deep cloning

S.No
Shallow Cloning
Deep Cloning
1
Here copied object points to the same location the previous object points to. So if u want to change anything for main object it will reflect for copied object also.
Here copied object points to the other location and points to other reference. So if u want to change anything it wont reflect for main object.
2
By default java supports shallow cloning
By default java does not support deep cloning.


What is Reflection and Interospection

"Reflection" refers to the low-level API with which you can ask "what are the methods of this class", "what parameters does this method accept", "what is the parent class of this class", and so on.

"Introspection" is a higher-level concept; it generally refers to using the reflection API to learn about a class. For example, the javax.beans.Introspector class will give you the list of JavaBeans properties of a class -- i.e., the pairs of matching "Y getX()"/"void setX(Y)" methods.

Difference between "== operator" and "equals() method" in java


S.No
= = Operator
equals() method
1
It is used for reference comparison.
It is also used for reference comparison but if we want we can override for content comparison
2
It can be apply for both primitives and object references.
It can be apply for only object references.
3
s1==s2 is true, iff both s1 & s2 are pointing to the same object on the heap.
In the object class, .equals() returns true, iff both s1& s2 are pointing to the same object.
4
We can't apply == operator for incompatible types of objects violation leads to compile time exception saying incompatible types.
Ex: String s1="getsure";
Student s2 = new Student("suresh");
SOP(s1==s2) --> C.E
It never rises any compile time / run time exception just it will simply returns false in the case of incompatible types.
5
In Identity Hashmap, JVM uses == operator to identify duplicate keys.
Ex: IdentityHashMap m=new IdentityHashMap(); Integer i1=new Integer(10);
Integer i2=new Integer(10);
m.put(i1, "GetSure");m.put(i2, "Infotech");
SOP(m) --> O/P: 10 - GetSure, 10 - Infotech
In Hashmap, the JVM uses .equals() method to identify duplicate keys.
Ex: HashMap m=new HashMap();
Integer i1=new Integer(10);
Integer i2=new Integer(10);
m.put(i1, "GetSure");m.put(i2, "Infotech");
SOP(m) --> O/P: Only 10 - Infotech

What is Serialization and Deserialization? Give me examples

Serialization : Serialization in java is a mechanism of writing the state of an object into a byte stream.It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies. The reverse operation of serialization is called deserialization. The String class and all the wrapper classes implements java.io.Serializable interface by default.

Advantages: It is mainly used to travel object's state on the network (known as marshaling).

Example:

Deserialization : Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of serialization.
Example:
More Explanation:

1.
Banking example: When the account holder tries to withdraw money from the server through ATM, the account holder information along with the withdrawl details will be serialized (marshalled/flattened to bytes) and sent to server where the details are deserialized (unmarshalled/rebuilt the bytes)and used to perform operations. This will reduce the network calls as we are serializing the whole object and sending to server and further request for information from client is not needed by the server.

2.
Stock example: Let’s say an user wants the stock updates immediately when he request for it. To achieve this, everytime we have an update, we can serialize it and save it in a file. When user requests the information, deserialize it from file and provide the information. This way we don’t need to make the user wait for the information until we hit the database, perform computations and get the result.

Why we need Serialization: To persist data for future use.

What are Java 8 & Java 9 Features

Java 5 Features:
    > For-each loop
    > Autoboxing and Unboxing
    > Covariant Return Type
    > Annotation
    > Generics
    > Enum
    > Static Import
    > Varargs
Java 6 Features:
    > Instrumentation (premain method)
Java 7 Features:
    > String in switch statement
    > Binary Literals
    > The try-with-resources
    > Caching Multiple Exceptions by single catch
    > Underscores in Numeric Literals
Java 8 Features:
    > Lambda Expressions
    > Pipelines and Streams
    > Date and Time API
    > Default Methods
    > Type Annotations
    > Nashhorn JavaScript Engine
    > Concurrent Accumulators
    > Parallel operations
    > PermGen Error Removed
    > TLS SNI

Java 9 Features:

 > A light-weight JSON API - which is a source of great speculation right now about how truly useful this feature will be (as proposed by the community process).

 > A HTTP 2 Client  - for HTTP 2.0 and websockets.

 > Process API Improvements  - to improve the API for controlling and     managing OS processes.

 > Improved contended locking -for increasing performance between threads.

 > Segmented Code Cache - to improved execution time for complicated            benchmarks.

 > Smart Java Compilation (Part 2) - Makes the sjavac tool available in the         default JDK.

 > Modular Source Code - organizes JDK source code into modules.

 

Difference between IdentityHashMap and HashMap

In Identity Hashmap, JVM uses == operator to identify duplicate keys.
Ex: IdentityHashMap m=new IdentityHashMap();
Integer i1=new Integer(10);
Integer i2=new Integer(10);
m.put(i1, "GetSure");m.put(i2, "Infotech");
SOP(m) --> O/P: 10 - GetSure, 10 - Infotech
In Hashmap, the JVM uses .equals() method to identify duplicate keys.
Ex: HashMap m=new HashMap();
Integer i1=new Integer(10);
Integer i2=new Integer(10);
m.put(i1, "GetSure");
m.put(i2, "Infotech");
SOP(m) --> O/P: Only 10 - Infotech
 

What is CopyOnWriteArrayList, how it is different than ArrayList

CopyOnWriteArrayList is a thread-safe counterpart of ArrayList. All mutable operations like add and set are implement by using a copy of the underlying array. Write operation is slower when compared the ArrayList as it takes a snapshot of the instance and does the write. This is useful when the traversal of the collection need not be synchronized during traversal with the original instance and the traversal is larger in count than the updates. This provides a fail safe iterator as it does not throw exception when the underlying collection is modified. At the same time the iterator will not reflect the modifications done to the collection, it just shows the snapshot of state taken at the moment when the iterator is created.

When do you use ConcurrentHashMap

ConcurrentHashMap as an example for fail safe iterator. It allows complete concurrency for retrievals and updates. When there is a scenario where a high number of concurrent updates are expected then ConcurrentHashMap can be used. This is very similar to a Hashtable but does not lock the entire table to provide concurrency and so it is better performance point of view. When there are high number of updates and less number of read concurrently, then ConcurrentHashMap should be used.

Difference between Comparable and Comparator

A class can implement the Comparable interface to define the natural ordering of the objects. If you take a list of Strings, generally it is ordered by alphabetical comparisons. So when a String class is created, it can be made to implement Comparable interface and override the compareTo method to provide the comparison definition. We can use them as,

str1.compareTo(str2);

Now, what will you do if you want to compare two strings based on it length. We go for the Comparator. We create a class and let it implement the Comparator interface and override compare method. We can use them as,

Collections.sort(listOfStrings, comparatorObj);

The natural ordering is up to the person designing the classes. Comparator can be used in that scenario also and it can be used when we need multiple sorting options. Imagine a situation where a class is already available and we cannot modify it. In that case also, Comparator is the choice.

What is Java Priority Queue

Java PriorityQueue is a data structure that is part of Java collections framework. It is an implementation of a Queue wherein the order of elements will be decided based on priority of each elements. A comparator can be provided in the constructor when a PriorityQueue is instantiated. That comparator will decide the sort order of elements in the PriorityQueue collection instance.

Explain Java hashCode() and equals() method.

equals() method is used to determine the equality of two Java objects. When we have a custom class we need to override the equals() method and provide an implementation so that it can be used to find the equality between two instance of it. By Java specification there is a contract between equals() and hashCode().

It says, "if two objects are equal, that is obj1.equals(obj2) is true then, obj1.hashCode() and obj2.hashCode() must return same integer".

Whenever we choose to override equals(), then we must override the hashCode() method. hashCode() is used to calculate the position bucket and keys.

How to format Date in Java


Difference between java.sql.Date() and java.util.Date()

sql date represent only Date information (e.g. year, month, day) while util Date represent both date and time information.

Difference b/w ConcurrentHashMap and Collections.synchronizedMap(HashMap)

The main difference between these two is that ConcurrentHashMap will lock only portion of the data which are being updated while other portion of data can be accessed by other threads. However, Collections.synchronizedMap() will lock all the data while updating, other threads can only access the data when the lock is released. If there are many update operations and relative small amount of read operations, you should choose ConcurrentHashMap.

Also one other difference is that ConcurrentHashMap will not preserve the order of elements in the Map passed in. It is similar to HashMap when storing data. There is no guarantee that the element order is preserved. While Collections.synchronizedMap(0 will preserve the elements order of the Map passed in. For example, if you pass a TreeMap to ConcurrentHashMap, the elements order in the ConcurrentHashMap may not be the same as the order in the TreeMap, but Collections.synchronizedMap() will preserve the order.

Note: Collections.synchronizedMap(HashMap) is equals to Hashtable

Difference b/w HashMap and ConcurrentHashMap


S.No
HashMap
ConcurrentHashMap
1
It is not a thread safe
It is a thread safe
2
Performance is high
Performance is low
3
It allows only one null key
It doesn't allow null key and null value

What are different ways to iterate over a list

We can iterate over a list in two different ways - using iterator and using for-each loop.

Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException.

What is CopyOnWriteArrayList, how it is different than ArrayList and Vector

CopyOnWriteArrayList is new List implementation introduced in Java 1.5 which provides better concurrent access than Synchronized List. better concurrency is achieved by Copying ArrayList over each write and replace with original instead of locking. Also CopyOnWriteArrayList doesn't throw any ConcurrentModification Exception. Its different than ArrayList because its thread-safe and ArrayList is not thread safe and its different than Vector in terms of Concurrency. CopyOnWriteArrayList provides better Concurrency by reducing contention among readers and writers.

Difference b/w HashMap and LinkedHashMap



S.No
HashMap
LinkedHashMap
1
Underlying data structure is Hashtable
Underlying data structure is Hashtable & LinkedList
2
Insertion order is not preserved
Insertion order is preserved

Difference b/w HashSet and LinkedHashSet


S.No
HashSet
LinkedHashSet
1
Underlying data structure is Hashtable
Underlying data structure is Hashtable & LinkedList
2
Insertion order is not preserved
Insertion order is preserved