Java Read Blogs Java Interview

http://javahungry.blogspot.com/2013/08/singleton-design-pattern-use-in-java.html

http://tutorials.jenkov.com/java-concurrency/volatile.html

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm

http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

http://www.journaldev.com/1321/java-string-interview-questions-and-answers

http://www.journaldev.com/797/what-is-java-string-pool

http://www.journaldev.com/588/java-switch-case-string

HashSet

  1. There’s no need to call equals if hashCode differs
  2. There’s no need to call hashCode if (obj1 == obj2)
  3. There’s no need for hashCode and/or equals just to iterate – you’re not comparing objects
  4. When needed to distinguish in between objects.

Java coding tricks

1) To copy array

In System class:
public static void arraycopy(Object src,
             int srcPos,
             Object dest,
             int destPos,
             int length)

eg.  System.arraycopy(arr, 0, arr1, 0, arr.length);

2) To print array
eg. System.out.println(Arrays.toString(arr));

3) Sorting : To sort collections and array

// Collections.sort

List list = new ArrayList();
Collections.sort(list, new Comparator() {
	public int compare(ObjectName o1, ObjectName o2) {
		return o1.toString().compareTo(o2.toString());
	}
});
// Arrays.sort
ObjectName[] arr = new ObjectName[10];
Arrays.sort(arr, new Comparator() {
	public int compare(ObjectName o1, ObjectName o2) {
		return o1.toString().compareTo(o2.toString());
	}
});

4) Using sorted data structure

If it is a list or set, use TreeSet to sort.

// TreeSet

Set sortedSet = new TreeSet(new Comparator() {
	public int compare(ObjectName o1, ObjectName o2) {
		return o1.toString().compareTo(o2.toString());
	}
});
sortedSet.addAll(unsortedSet);

If it is a map, use TreeMap to sort. TreeMap is sorted by key.

// TreeMap - using String.CASE_INSENSITIVE_ORDER which is a Comparator that orders Strings by compareToIgnoreCase
Map sortedMap = new TreeMap(String.CASE_INSENSITIVE_ORDER);
sortedMap.putAll(unsortedMap);

 

//TreeMap - In general, defined comparator
Map sortedMap = new TreeMap(new Comparator() {
	public int compare(ObjectName o1, ObjectName o2) {
		return o1.toString().compareTo(o2.toString());
	}
});
sortedMap.putAll(unsortedMap);

This approach is very useful, if you would do a lot of search operations for the collection. The sorted data structure will give time complexity of O(logn), which is lower than O(n).

5) Sort a Map with Values

Java – Sort Map By Value

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
 
public class Solution {
	public static void main(String[] args) {
		HashMap map = new HashMap();
		map.put("a", 10);
		map.put("b", 30);
		map.put("c", 50);
		map.put("d", 40);
		map.put("e", 20);
		System.out.println(map);
 
		Map sortedMap = sortByValue(map);
		System.out.println(sortedMap);
	}
 
	public static Map sortByValue(Map unsortedMap) {
		Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));
		sortedMap.putAll(unsortedMap);
		return sortedMap;
	}
 
}
 
class ValueComparator implements Comparator {
	Map map;
 
	public ValueComparator(Map map) {
		this.map = map;
	}
 
	public int compare(Object keyA, Object keyB) {
		Comparable valueA = (Comparable) map.get(keyA);
		Comparable valueB = (Comparable) map.get(keyB);
		return valueB.compareTo(valueA);
	}
}

6) Comparator for sorting the string in case insensitive manner

Map map = new TreeMap(String.CASE_INSENSITIVE_ORDER);

7) Comparing strings

Commonly used String methods such as:

String.equalsIgnoreCase(String) //Ignores case while comparing
String.compareTo(String) // To compare two strings

8) Choosing the right java data structure: http://www.javapractices.com/topic/TopicAction.do;jsessionid=4430DA53231A3B560F0BE08F4C48CD54?Id=65

Serialization in Java

Serialization enables us to represent an object as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

Classes and methods for serialization:

ObjectOutputStream class contains many write methods for serializing an object.
public final void writeObject(Object x) throws IOException

Above method serializes an Object and sends it to the output stream.

ObjectInputStream class contains the following method for deserializing an object:
public final Object readObject() throws IOException, ClassNotFoundException
The return value is Object, so you will need to cast it to its appropriate data type.

 

For a class to be serialized successfully, two conditions must be met:

  • The class must implement the java.io.Serializable interface.
  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

 

When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

Serialization of class
public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name + " " + address);
   }
}

Serializing an object
import java.io.*;
public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      
      try
      {
         FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

Deserializing an object:
import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Employee e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}


The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method.

For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class.

If the JVM can’t find a class during the deserialization of an object, it throws a ClassNotFoundException.

 

Class Refactoring with Serialization and serialVersionUID

Serialization in java permits some changes in the java class if they can be ignored. Some of the changes in class that will not affect the deserialization process are:

  • Adding new variables to the class
  • Changing the variables from transient to non-transient, for serialization it’s like having a new field.
  • Changing the variable from static to non-static, for serialization it’s like having a new field.

But for all these changes to work, the java class should have serialVersionUID defined for the class.

If the class doesn’t define serialVersionUID, it’s getting calculated automatically and assigned to the class. Java uses class variables, methods, class name, package etc to generate this unique long number. If you are working with any IDE, you will automatically get a warning that “The serializable class Employee does not declare a static final serialVersionUID field of type long”.

We can use java utility “serialver” to generate the class serialVersionUID, for Employee class we can run it with below command.

SerializationExample/bin$serialver -classpath . com.journaldev.serialization.Employee

serialVersionUID tells the deserialization process that the new class is the new version of the same class and should be deserialized of possible.

Declaration of serialVersionUID in a class:
private static final long serialVersionUID = 2087368867376448459L;

 

Java Externalizable Interface:

Sometimes we want to obscure the object data to maintain it’s integrity. We can do this by implementing java.io.Externalizable interface and provide implementation of writeExternal() and readExternal() methods to be used in serialization process.

@Override
public void writeExternal(ObjectOutput out) throws IOException {
	out.writeInt(id);
	out.writeObject(name+"xyz");
	out.writeObject("abc"+gender);
}

@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
	id=in.readInt();
	//read in the same order as written
	name=(String) in.readObject();
	if(!name.endsWith("xyz")) throw new IOException("corrupted data");
	name=name.substring(0, name.length()-3);
	gender=(String) in.readObject();
	if(!gender.startsWith("abc")) throw new IOException("corrupted data");
	gender=gender.substring(3);
}

If these methods are present in the class, they are used for serialization purposes.

readObject(ObjectInputStream ois): If this method is present in the class, ObjectInputStream readObject() method will use this method for reading the object from stream.

writeObject(ObjectOutputStream oos): If this method is present in the class, ObjectOutputStream writeObject() method will use this method for writing the object to stream. One of the common usage is to obscure the object variables to maintain data integrity.

Object writeReplace(): If this method is present, then after serialization process this method is called and the object returned is serialized to the stream.

Object readResolve(): If this method is present, then after deserialization process, this method is called to return the final object to the caller program. One of the usage of this method is to implement Singleton pattern with Serialized classes.

Links for further details: http://www.journaldev.com/2452/serialization-in-java, http://www.tutorialspoint.com/java/java_serialization.htm

Object Cloning in Java

A clone is an exact copy of the original. In java, it essentially means the ability to create an object with similar state as the original object.


By default, java cloning is ‘field by field copy’
i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked. So, JVM when called for cloning, do following things:

1) If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.

2) If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

 

How to clone in Java??
A) You must implement Cloneable interface.
B) You must override clone() method from Object class. [Its weird. clone() method should have been in Cloneable interface.]

public class Employee implements Cloneable{

    private int empoyeeId;
    private String employeeName;
    private Department department;

    public Employee(int id, String name, Department dept)
    {
        this.empoyeeId = id;
        this.employeeName = name;
        this.department = dept;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    //Accessor/mutators methods will go there
}

// Department class
public class Department
{
    private int id;
    private String name;
 
    public Department(int id, String name)
    {
        this.id = id;
        this.name = name;
    }
    //Accessor/mutators methods will go there
}


public class TestCloning {
 
    public static void main(String[] args) throws CloneNotSupportedException
    {
        Department dept = new Department(1, "Human Resource");
        Employee original = new Employee(1, "Admin", dept);
        //Lets create a clone of original object
        Employee cloned = (Employee) original.clone();
        //Let verify using employee id, if cloning actually workded
        System.out.println(cloned.getEmpoyeeId());
 
        //Verify JDK's rules
 
        //Must be true and objects must have different memory addresses
        System.out.println(original != cloned);
 
        //As we are returning same class; so it should be true
        System.out.println(original.getClass() == cloned.getClass());
 
        //Default equals method checks for refernces so it should be false. If we want to make it true,
        //we need to override equals method in Employee class.
        System.out.println(original.equals(cloned));
    }
}
Output:
1
true
true
false



public class TestCloning { 
    public static void main(String[] args) throws CloneNotSupportedException {
        Department hr = new Department(1, "Human Resource");
        Employee original = new Employee(1, "Admin", hr);
        Employee cloned = (Employee) original.clone();
 
        //Let change the department name in cloned object and we will verify in original object
        cloned.getDepartment().setName("Finance");
 
        System.out.println(original.getDepartment().getName());
    }
}
Output: Finance


 

Shallow Cloning

This is default implementation in java. In overridden clone method, if you are not cloning all the object types (not primitives), then you are making a shallow copy.

All above examples are of shallow copy only, because we have not cloned the Department object on Employee class’s clone method.

 

Deep cloning

It is the desired behavior in most the cases. We want a clone which is independent of original and making changes in clone should not affect original.

//Modified clone() method in Employee class
@Override
protected Object clone() throws CloneNotSupportedException {
    Employee cloned = (Employee)super.clone();
    cloned.setDepartment((Department)cloned.getDepartment().clone());
    return cloned;
}

I modified the Employee classes clone() method and added following clone method in Department class.
//Defined clone method in Department class.
@Override
protected Object clone() throws CloneNotSupportedException {
    return super.clone();
}

Now testing our cloning code gives desired result and name of department will not be modified.
public class TestCloning {
    public static void main(String[] args) throws CloneNotSupportedException {
        Department hr = new Department(1, "Human Resource");
        Employee original = new Employee(1, "Admin", hr);
        Employee cloned = (Employee) original.clone();
 
        //Let change the department name in cloned object and we will verify in original object
        cloned.getDepartment().setName("Finance");
 
        System.out.println(original.getDepartment().getName());
    }
}
Output:
Human Resource

 

So deep cloning requires satisfaction of following rules.

*  No need to separately copy primitives.
*  All the member classes in original class should support cloning and in clone method of  original class in context should call super.clone() on all member classes.
*  If any member class does not support cloning then in clone method, one must create a new instance of that member class and copy all its attributes one by one to new member class object. This new member class object will be set in cloned object.

 

 

Using copy constructors

Copy constructors are special constructors in a class which takes argument for its own class type. So, when you pass an instance of class to copy constructor, then constructor will return a new instance of class with values copied from argument instance. Lets see this in example:

public class PointOne {
    private Integer x;
    private Integer y;
 
    public PointOne(PointOne point){
        this.x = point.x;
        this.y = point.y;
    }
}

This method looks simple and it is until comes inheritance. When you define a class by extending above class, you need to define a similar constructor there also. In child class, you need to copy child specific attributes and pass the argument to super class’s constructor. Lets see how?

public class PointTwo extends PointOne{
    private Integer z;
 
    public PointTwo(PointTwo point){
        super(point); //Call Super class constructor here
        this.z = point.z;
    }
}

So, are we fine now? NO. The problem with inheritance is that exact behavior is identified only in run time. So, in our case if some class passed the instance of PointTwo in constructor of PointOne. In this case, you will get the instance of PointOne in return where you passed instance of PointTwo as argument. Lets see this in code:

class Test
{
    public static void main(String[] args)
    {
        PointOne one = new PointOne(1,2);
        PointTwo two = new PointTwo(1,2,3);
 
        PointOne clone1 = new PointOne(one);
        PointOne clone2 = new PointOne(two);
 
        //Let check for class types
        System.out.println(clone1.getClass());
        System.out.println(clone2.getClass());
    }
}
Output:
class corejava.cloning.PointOne
class corejava.cloning.PointOne

 
Links: http://mrbool.com/how-to-implement-cloning-in-java-using-cloneable-interface/28410,
http://stackoverflow.com/questions/4081858/about-java-cloneable, http://www.artima.com/intv/bloch13.html,
http://coderevisited.com/cloneable-interface-in-java/,

Good article on object cloning in java: http://howtodoinjava.com/core-java/cloning/a-guide-to-object-cloning-in-java/

Fail fast vs fail safe iterator

What is Concurrent Modification ?

When one or more thread is iterating over the collection, in between, one thread changes the structure of the collection (either adding the element to the collection or by deleting the element in the collection or by updating the value at particular position in the collection) is known as Concurrent Modification

 

Fail fast Iterator

Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification  of the collection . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Fail-fast iterator can throw ConcurrentModificationException in two scenarios :

Single Threaded Environment : After the creation of the iterator , structure is modified at any time by any method other than iterator’s own remove method.
 
Multiple Threaded Environment:  If one thread is modifying the structure of the collection while other thread is iterating over it.

According to  Oracle docs , the fail-fast behavior of an iterator cannot be guarantee, fail-fast behavior of iterators should be used only to detect bugs.

 

How  Fail  Fast Iterator  come to know that the internal structure is modified ?

Iterator read internal data structure (object array) directly . The internal data structure(i.e object array) should not be modified while iterating through the collection. To ensure this it maintains an internal  flag “mods” .Iterator checks the “mods” flag whenever it gets the next value (using hasNext() method and next() method). Value of mods flag changes whenever there is an structural modification. Thus indicating iterator to throw ConcurrentModificationException.

 

Fail Safe Iterator :

Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure.  So , original data structure remains  structurally unchanged .Hence , no ConcurrentModificationException throws by the fail safe iterator.

Two  issues associated with Fail Safe Iterator are :

1. Overhead of maintaining the copied data structure i.e memory.

2.  Fail safe iterator does not guarantee that the data being read is the data currently in the original data structure.

 

Fail safe iterator is ordinarily too costly, but may be more efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don’t want to synchronize traversals, yet need to preclude interference among concurrent threads.

The “snapshot” style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.

The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove(), set(), and add()) are not supported. These methods throw UnsupportedOperationException.

 

eg. HashMap has a fail fast iterator while ConcurrentHashMap uses a fail slow iterator.

 

For detail description and examples please refer to the post: http://javahungry.blogspot.com/2014/04/fail-fast-iterator-vs-fail-safe-iterator-difference-with-example-in-java.html

Java Generics

Java Genrics was introduced in Java 5.

Java Generics provide compile-time type checking and remove risk of ClassCastException

// Compile Time type checking provided by generics
List list1 = new ArrayList(); // In java 7 we can intialize with List list1 = new ArrayList<>(); 
list1.add("abc");
//list1.add(new Integer(5)); //throws compiler error

 

Java Generic Classes, Interfaces & Methods:

Java Generic Classes

public class GenericsType<T> {
	private T t;	
	public T get(){
		return this.t;
	}	
	public void set(T t1){
		this.t=t1;
	}	
	public static void main(String args[]){
		GenericsType<String> type = new GenericsType<>();
		type.set("Pankaj"); //valid
		
		GenericsType type1 = new GenericsType(); //raw type
		type1.set("Pankaj"); //valid
		type1.set(10); //valid and autoboxing support
	}
}

If we don’t provide the type at the time of creation, compiler will produce a warning that “GenericsType is a raw type. If we don’t provide type, the type becomes Object and hence it’s allowing both String and Integer objects but we should always try to avoid this because we will have to use type casting while working on raw type that can produce runtime errors.

 

Java Generic Interface

public interface Comparable<T> {
public int compareTo(T o);
}

 

Java Generic Method

//Java Generic Method
public static <T> boolean isEqual(GenericsType<T> g1, GenericsType<T> g2){
	return g1.get().equals(g2.get());
}

We can call the above method:
boolean isEqual = GenericsMethods.<String>isEqual(g1, g2);
boolean isEqual = GenericsMethods.isEqual(g1, g2); // Type Inference

 

Invoking a generic method as an ordinary method, without specifying a type between angle brackets is known as Type Inference. Compiler will infer the type that is needed.

 

Java Generics & Inheritance

MyClass<String> myClass1 = new MyClass<String>();
MyClass<Object> myClass2 = new MyClass<Object>();
//myClass2=myClass1; // Compilation Error since MyClass<String> is not a MyClass<Object>

Object obj = new Object();
obj = myClass1; // Valid MyClass<T> parent is Object

This is Valid
ArrayList<E> implements List<E> that extends Collection<E>, so ArrayList<String> is a subtype of List<String> and List<String> is subtype of Collection<String>.

interface MyList<E,T> extends List{
}

 

Java Generics Wildcards

Question mark (?) is the wildcard in generics and represent an unknown type. The wildcard can be used as the type of a parameter, field, or local variable and sometimes as a return type.

 

Java Generics Upper Bounded Wildcard: We use generics wildcard with extends keyword

public static double sum(List<? extends Number> list){
	double sum = 0;
	for(Number n : list){
		sum += n.doubleValue();
	}
	return sum;
}

Invocation:
List<Integer> ints = new ArrayList<>();
ints.add(3); ints.add(5); ints.add(10);
double sum = sum(ints);

Can be used as List doubless= new ArrayList<>();

 

Java Generics Unbounded Wildcard

public static void printData(List<?> list){
	for(Object obj : list){
		System.out.print(obj + "::");
	}
}

 

Java Generics Lower Bounded Wildcard : We use generics wildcard (?) with super keyword and lower bound class to achieve this.

public static void addIntegers(List<? super Integer> list){
	list.add(new Integer(50));
}

 

Java Generics Type Erasure

Generics in Java was added to provide type-checking at compile time and it has no use at run time, so java compiler uses type erasure feature to remove all the generics type checking code in byte code and insert type-casting if necessary. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

 

Java Generics Concept:

1)
List<Number> numbers = new ArrayList<Integer>(); // Invalid can cause ClassCastException

2)
We can’t create generic array? or write code as 
List<Integer>[] array = new ArrayList<Integer>[10]; // Invalid
because Java Generics Type Erasure


 

Links to refer to: Post 1 , Post 2;

Java Collections Questions

I)  http://www.javatpoint.com/java-collections-interview-questions

Few Questions from it:

1) What is the difference between Collection and Collections?

Collection is an interface whereas Collections is a class.

Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

Both are present in java.util package and  part of java collections framework.

2) What is the difference between Comparable and Comparator?

No. Comparable Comparator
1) Comparable provides only one sort of sequence. Comparator provides multiple sort of sequences.
2) It provides one method named compareTo(). It provides one method named compare().
3) It is found in java.lang package. it is found in java.util package.
4) If we implement Comparable interface, actual class is modified. Actual class is not modified.

 

3) What is the advantage of generic collection?

If we use generic class, we don’t need typecasting. It is typesafe and checked at compile time.

 

4) What is the difference between Iterator and ListIterator?

Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction.

No. Iterator ListIterator
1) Iterator traverses the elements in forward direction only. ListIterator traverses the elements in backward and forward directions both.
2) Iterator can be used in List, Set and Queue. ListIterator can be used in List only.

 

II) http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

1) What is Collection ? What is a Collections Framework ? What are the benefits of Java Collections Framework ?

Collection : A collection (also called as container) is an object  that groups multiple elements into a single unit.

Collections Framework : Collections framework provides unified architecture for manipulating and representing collections.

Benefits of Collections Framework :

1. Improves program quality and speed
2. Increases the chances of reusability of software
3. Decreases programming effort.

2) What is the root interface in collection hierarchy ? 

Root interface in collection hierarchy is Collection interface . Few interviewer may argue that
Collection interface extends Iterable interface. So iterable should be the root interface. But you should reply iterable interface present in java.lang package not in java.util package.

3)  Which collection classes are synchronized or thread-safe ?

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe).

4) Name the core Collection  interfaces ?

The list of core collection interfaces are : the important ones
Important : Collection , Set , Queue , List , Map
Other interface also in the list :  SortedSet, SortedMap , Deque, ListIterator etc.


5) What is an iterator ?

Iterator is an interface . It is found in java.util package. It provides methods to iterate over any Collection.

6) What is the difference between Iterator and Enumeration ?

The main difference between Iterator and Enumeration is that Iterator has remove() method while Enumeration doesn’t.
Hence , using Iterator we can manipulate objects by adding and removing the objects from the collections. Enumeration behaves like a read only interface as it can only traverse the objects and fetch it.


7)
Which methods you need to override to use any object as key in HashMap ?

To use any object as key in HashMap , it needs to implement equals() and hashCode() method .
8) How to reverse the List in Collections ?

There is a built in reverse method in Collections class . reverse(List list) accepts list as parameter.

Collections.reverse(listobject);

9) How to convert the array of strings into the list ?

Arrays class of java.util package contains the method asList() which accepts the array as parameter.
So,

String[]  wordArray =  {“Love Yourself”  , “Alive is Awesome” , “Be in present”};
List wordList =  Arrays.asList(wordArray);

10) What is the difference between ArrayList and Vector ?

1). Vector is synchronized while ArrayList is not .
2). Vector is slow while ArrayList is fast .
3). Every time when needed, Vector increases the capacity twice of its initial size while ArrayList increases its ArraySize by 50%.11) What is the difference between HashMap and Hashtable ?

1) HashMap allows one null key and any number of null values while Hashtable does not allow null keys and null values.
2) HashMap is not synchronized or thread-safe while Hashtable is synchronized or thread-safe.

12) What is the difference between peek(),poll() and remove() method of the Queue interface ?

Both poll() and remove() method is used to remove head object of the Queue. The main difference lies when the Queue is empty().
If Queue is empty then poll() method will return null . While in similar case , remove() method will throw NoSuchElementException .
peek() method retrieves but does not remove the head of the Queue. If queue is empty then peek() method also returns null.

13) What is the difference between HashSet and TreeSet ?

1)  HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order
2) HashSet can store null object while TreeSet can not store null object.

14)  What is the difference between HashMap and ConcurrentHashMap ?

1) HashMap is not synchronized while ConcurrentHashMap is synchronized.
2) HashMap can have one null key and any number of null values while ConcurrentHashMap does not allow null keys and null values .

15) Arrange the following in the ascending order (performance):
HashMap , Hashtable , ConcurrentHashMap and Collections.SynchronizedMap Hashtable  <  Collections.SynchronizedMap  <  ConcurrentHashMap  <  HashMap

16) What is the difference between LinkedList and ArrayList in Java ?

1) LinkedList is the doubly linked list implementation of list interface , while , ArrayList is the resizable array implementation of list interface.
2) LinkedList can be traversed in the reverse direction using descendingIterator() method  provided by the Java Api developers , while , we need to implement our own method to traverse ArrayList in the reverse direction

17) Why Map interface does not extend the Collection interface in Java Collections Framework ?

Map interface is not compatible with the Collection interface.
Explanation : Since Map requires key as well as value , for example , if we want to add key-value pair then we will use put(Object key , Object value) . So there are two parameters required to add element to the HashMap object  . In Collection interface add(Object o) has only one parameter.
The other reasons are Map supports valueSet , keySet as well as other appropriate methods which have just different views from the Collection interface.

18)When to use ArrayList and when to use LinkedList in application?

ArrayList has constant time search operation O(1) .Hence, ArrayList is preferred when there are more get() or search operation .

Insertion , Deletion operations take constant time O(1) for LinkedList. Hence, LinkedList is preferred when there are more insertions or deletions involved in the application.

 

Post to look into : http://www.journaldev.com/1330/java-collections-interview-questions-and-answers

Java Memory Management

Java Heap Vs Stack Memory

Java Heap Space:

  • Java Heap space is used by java runtime to allocate memory to Objects and JRE classes.
  • Whenever we create any object, it’s always created in the Heap space.
  • Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference.
  • Any object created in the heap space has global access and can be referenced from anywhere of the application.

Java Stack Memory:

  • Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method.
  • Stack memory is always referenced in LIFO (Last-In-First-Out) order.
  • Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method.
  • Stack memory size is very less compared to Heap memory.

 

Difference btw Stack & Heap Memory

  • We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.
  • When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
  • Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
  • Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
  • Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc.
  • Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.

 

Detailed Explanation at this post.