51 frequently asked java interview questions and answers for freshers (0-2 Years Experience) - Part 4(Q#31 to Q#40)

Previous posts of frequently asked Java interview questions and answers for freshers are Q#1-Q#10, Q#11-Q#20, Q#21-Q#30. This post follows from Q#31.
31. What is difference between String and StringBuffer, StringBuilder ?
Answer: String class represents character strings. Strings are constant(immutable), their values cannot be changed after they are created.
StringBuffer class represents mutable sequence of characters and it is thread safe.String buffers are safe for use by multiple threads because all of the methods are synchronized.
StringBuilder class also represents mutable sequence of characters however it is not thread safe. String builder performance is better than string buffer, so in single thread working environment String builder is recommended to use.

32. What is difference between these two declaration: String st1 = "abc"; String st2 = new String("abc");
Answer: String objects in Java are created at two places- String pool and Heap.The exact location of the string pool can vary from one JVM implementation to another.
In hotspot JVM, until Java 6, the string pool was in the permgen space of the heap. PermGen has a fixed size and can not be expanded at runtime, so string pool location was a great concern for Java 6. However, since Java 7, it has been moved to the main part of the heap (young and old generations). In Java 8 Hotspot, Permanent Generation has been completely removed.
The fundamental difference between "abc" and new String("abc") is that - "abc" is creates one object in sting pool, however new String("abc") creates two objects - one in string pool (if "abc" is not available there) and another one on heap.

33.What is "final" keyword in Java? How does it affect variable, method or class behavior?
Answer: final keyword in Java can be used with class and it member variables - fields and methods.
When final keyword is used with class, method and fields, this is how they affect their behavior : 
class -       class cannot be extended (String class is final in Java, we cannot extends String class )
method -  A method qualified with final cannot be overridden. 
field -       field value cannot be changed/re-assigned. Field can be two types:
Non-reference types (int,float, etc.):-  field value once assigned cannot be modified
Reference type:- Object value may be changed however reference pointing to that object cannot be modified. See below code lines: final int var is not modifiable, error thrown once modified it's value form 0 to 1. final map reference variable cannot be reassign different object, however map value can be modified.
/*Non-reference types*/
final int var = 0;
var = 1//Error: final local variable var value cannot be changed.

/*Reference types*/
final Map<String,String> map = new HashMap<String,String>();
map.put("Nik""Ranjan")//object can be modified 
map = new HashMap<String,String>();//Error:final variable map cannot be assigned. 

34. What is difference between IS-A and HAS-A in Java? Explain with an example. 
Answer: Code re-usability is one of the important features of OOP.In Java there are two ways we can achieve it - Inheritance implementation  (IS-A relationship) and  Object composition (HAS-A relationship).In OOP like Java, we can have Class Inheritance and Interface Inheritance - class inheritance (by extending class) and interface inheritance(by implementing interface).
For example: Apple is a fruit, Worker is an Employee - Apple class can extend Fruit class and exhibit IS-A relationship.Similarly Worker class with Employee.
On the other hand. if a class contains references of another object then that relationship is called Composition. For example, Employee has BankAccount, House has a Bathroom,

35. What is exception handing in Java? Explain with try, catch and finally keyword in Java ?
Answer: An exceptional condition is a problem that prevents the continuation of the current method . When an exceptional condition arises, method processing stops and it has two option to deal with it: 1. Either relegate that problem to higher context - Using throws keyword
2. deal with that problem in current context   -  Using try-catch block.
Lets write a sample program to understand how these two approaches can be used:
public class ExceptionHandling {
  public static int division(int num1, int num2throws NumberFormatException {
    int divResult = 0;
    try {

      divResult = num1 / num2;
    catch (ArithmeticException e) {
      System.out
          .println("Arithmatic exception occured, please check input");
    finally {
      // System.out.println("Executed always");

    }
    return divResult;
  }

  public static void main(String[] arg) {

    try {
      // case 1:
      System.out.println(ExceptionHandling.division(120));
      // case 2:
      System.out.println(ExceptionHandling.division(12,
          Integer.parseInt("A")));
    catch (NumberFormatException ex) {
      System.out
          .println("Number format exception occured, please 
            check your input.");
    }
  }
}
In the above program, when division method is called with argument (12, 0) ArithmeticException occurs and it is handled in current context and control reaches in catch block.
However, in second case, when division method is called with (12,Integer.parseInt("A")), A cannot be converted into integer, NumberFormatException arises and it is not handled in current context. With throws keyword we hint the calling method that division method will throw NumberFormatException. It is the responsibility of calling method to handle it.So,When NumberFormatException arises it is catched in main catch block.
Note: finally block is always executed (except in system failure). Solve this question related to try-catch-finally block.

36. What is difference between final and finally in Java ?
Answer: Their is no relationship between final and finally, it is matter of just a naming convention adopted by Java inventors.In above example we saw that, finally keyword when we are dealing with exception handling.Finally block is generally used for releasing resources and clean-up activity.
Refer question no 33 for detailed explanation of final keyword.

37.What is difference between ClassNotFoundException and NoClassDefFoundError?
Answer: The most fundamental difference is "classNotFoundException" is an exception and "NoClassDefFoundError" is an error. Exceptions are recoverable however Error are nor recoverable. One thing common with both of them is that this exception and error situation arises at run time. Lets understand the reason when do these exception and error arises.
ClassNotFoundException is run time exception arises when classLoader tries to load class specified as string in forName(), loadClass() method and it does not fine the definition of class.
i.e: Since at compile time, these method will just assume class name specified as string is available. However, at run time when classLoader ties to find the specified class in CLASSPATH and it is not available then, classNotFoundException will be reported.
We have following solution for that : 1. Just check the CLASSPATH, whether specified class is part of classpath directory.  2. Verify that whether a valid class name is passed to to the forname(), load()methods.
Consider the following example: It will compile without any failure. However, since com.dummy.Class1 is not present in classpath and when we run it , it will throw  java.lang.ClassNotFoundException: com.dummy.Class1 on console.In callMe() uncomment each of them one by one same exception will be reported.
class ClassNotFoundExceptionExample {

  public static void main(String[] arg) {
    try {
      ClassNotFoundExceptionExample.callMe();
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }

  static void callMe() throws ClassNotFoundException {
    Class.forName("com.dummy.Class1");
    //System.load("com.dummy.Class1");
    //ClassLoader.getSystemClassLoader().loadClass("com.dummy.Class1");
  }
}
NoClassDefFoundError is thrown when JVM or classloader tries to load a class as part of method invocation or creating an instance using new operator and JVM failed to locate actual physical representation of the class(definition of a class) - the .class file.
i.e: At compile time the referenced(searched-for) class was there in CLASSPATH, however at run time when an instance of that class was created definition of that class is not available.There might various reason of no-availability of definition of class. (XY is our searched-for class name)
1. XY has been loaded by another classloade and it is not visible to our code from where we are creating instance.
2. XY has static blocks or members which use a Class that's not found by the ClassLoader.
3. XY depends on class ABC which couldn't be loaded for any of the above reasons.
One important thing that needs special mention that- ClassNotFoundException is a root cause of NoClassDefFoundError.
 Oracle doc reference If the Java Virtual Machine ever attempts to load a class C during verification or resolution (but not initialization), and the class loader that is used to initiate loading of C throws an instance of ClassNotFoundException, then the Java Virtual Machine must throw an instance of NoClassDefFoundError whose cause is the instance of ClassNotFoundException.
Consider the following sample program, when we compile it generates two class files: NoClassDefFoundErrorExample.class and NoClassDefFoundErrorDepedentClass.class.Now we delete "NoClassDefFoundErrorDepedentClass.class" and run it. NoClassDefFoundError will be reported and same is evident from sample output NoClassDefFoundError caused by ClassNotFoundException.
public class NoClassDefFoundErrorExample {
  public static void main(String[] args) {
    NoClassDefFoundErrorDepedentClass instance = new NoClassDefFoundErrorDepedentClass();
  }
}

class NoClassDefFoundErrorDepedentClass {

}
Sample output:
==============================================================
Exception in thread "main" java.lang.NoClassDefFoundErrorExample: NoClassDefFoundErrorDepedentClass
        at NoClassDefFoundErrorExample.main(NoClassDefFoundErrorExample.java:4)
Caused by: java.lang.ClassNotFoundException: NoClassDefFoundErrorDepedentClass

38.What data structure have you used for holding Objects in Java ?
Answer: Java has various inbuilt data structures support like LinkedList, ArrayList, HashMap, HashSet,Stack, Array, etc. Array, HashMap, LinkedList and ArrayList are most commonly used data structure to hold objects. Following are the data structure declaration in Java:
String[] strArray= new String[12];
Map<String, Integer> map = new HashMap<String, Integer>(15);//initial capacity of HashMap is 15.
List<String> list = new LinkedList<String>();

39.What is difference between ArrayList and LinkedList in Java ? 
Answer : Arraylist and LinkedList are two concrete implementation of List interface.
  1. The fundamental difference between ArrayList and LinkedList is lies in internal data structure used for its implementation. ArrayList uses an array and LinkedList uses Entry class with two reference next and previous of type Entry.
  2. Index based get(index) operation takes O(1) constant time in ArrayList(because array list internally uses an array), however in linkedList it takes O(n) time - order of index position.
    Conclusion: If you are predominately performing search and get operation ArrayList is better than LinkedList.    
  3. In case of add() and remove() operation LinkedList take O(1) - constant time , however ArrayList take O(n) time (if first element is removed/added) and O(1) if last element is added/removed.
    Why ArrayList takes O(n) - linear time for add() and remove() operation? 
    For add() and remove() operation, after adding/removing element from array other elements are shifted accordingly. Suppose, if we have to remove first element , first element is removed and rest other elements are shifted one position back so it takes O(n) time. Similarly, if last element is removed, we do not have to shift any element so it takes O(1) time.  
  4. Memory overhead is more in LinkedList because it maintains two references previous and next in each Entry object while ArrayList just maintains an Object array. 
Common features of  LinkedList and ArrayList: 
  • Both ArrayList and LinkedList implements List interface.
  • Both ArrayList and LinkedList are not thread safe.If multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. Structural modification means : add and remove some elements not just update/re-assign elements.
  • Synchronized ArrayList and LinkedList can be created using Collections.synchronizedList() of collections algorithm. For example, syncronized linkedlist can be created like this :
    List list = Collections.synchronizedList(new LinkedList(...));
  • Fail-fast iterators - Iterators and ListIterator associated with lists are fail-fast. It means,If the list is structurally modified at any time after the iterator is created, in any way except through the Iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
    Note: fail-fast behavior of an iterator cannot be guaranteed, it throw ConcurrentModificationException on a best-effort basis.
    ListIterator: An iterator for lists that allows the programmer to traverse the list in either direction and modify the list during iteration. 

40.Have you used HashMap? Write a sample code to create a hashMap and iteration over it ?
Answer: HashMap is a concrete implementation of Map interface and uses hashing mechanism to disperse elements in memory. Characteristics of HashMap:
  1. HashMap stores elements key and value in from of Entry objects. Here is detailed discussion of Internal implementation of HashMap. One null key is allowed.
  2. It does not maintain order of insertion. It uses hash function to find bucket location for element storage. 
  3. HashMap is not synchronized.If multiple threads access a HashMap concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.Structural modification means : add and remove some elements, not just assign a value to a an existing key in map. 
  4. Syncronized hashMap can be created using Collections.synchronizedList() of collections algorithm.For example a synchronized map can be created like this : 
    Map m = Collections.synchronizedMap(new HashMap(...));
  5. It claims constant-time performance for the basic operations get() and put(), assuming the hash function disperses the elements properly among the buckets.
  6. Initial capacity and load factor are important factor which affects HashMap performance. default value of load factor is 0.75 and initial capacity is 16. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed. Rehashing means - internal data structures are rebuilt so that the hash table has approximately twice the number of buckets. 
  7. Iterators returned associated with collection view methods are fail-fast.It means,If the map is structurally modified at any time after the iterator is created, in any way except through the Iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
    Note: fail-fast behavior of an iterator cannot be guaranteed, it throw ConcurrentModificationException on a best-effort basis.
HashMap creation syntax and sample code to iterate it : Below is the syntax to create HashMap in Java. Instance of HashMap referenced by Map interface and key is of String type and value of Integer type.
Map<String, Integer> map = new HashMap<String, Integer>(20); // Initial capacity is optional
Map iteration can be performed in in various ways.Below is the sample program for the same.
From sample output we can conclude that order of insertion is not maintained.
In first approach, we iterated over keySet and displayed value of each key. In second approach,Entry object has been used (Remember, HashMap stores elements in the form of Entry object). And in third approach, we have used iterator of entrySet view and using hasNext()/next() method of iterator map is iterated.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HashMapIterationExample {
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(11"India");
    map.put(22"USA");
    map.put(33"SriLanka");
    map.put(44"USA");
    map.put(55"SriLanka");
    // First : Using map keySet
    System.out.println("+++++++First appraoch: Using map keySet++++");
    for (Integer keyObj : map.keySet()) {
      System.out.println(keyObj + " map value is- " + map.get(keyObj));
    }
    // Second: Using Entry Object 
    System.out.println("===Second appraoch: Using Entry Object ======");
    for (Entry<Integer, String> entryObj : map.entrySet()) {
      System.out.println(entryObj.getKey() " map value is- "
          + map.get(entryObj.getKey()));
    }
    // Third: Using iterator 
    System.out.println("===Third appraoch: Using iterator ======");
    Iterator<Entry<Integer, String>> it = map.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry<Integer, String> keyValpair = (Map.Entry<Integer, String>it
          .next();
      System.out.println(keyValpair.getKey() " map value is- "
          + map.get(keyValpair.getKey()));
    }
  }

}
Sample output: Have displayed just one output.(your output might be different from below sown)
+++++++First appraoch: Using map keySet++++
33 map value is- SriLanka
55 map value is- SriLanka
22 map value is- USA
11 map value is- India
44 map value is- USA
--------------------------------------
Here is an interesting HashMap puzzle- Test you understanding of  get()/put() method of HashMap?


Previous: Part 3(Q#21 to Q#30 ) - Interview Q&A Next: Part 5(Q#41 to Q#51 ) - Interview Q&A

2 Comments

Previous Post Next Post