Java Questions Part3 - Exception Handling and Multi Threading and Collections

1. What is Exception and what is the base class of it?
Answer: Few definitions:
-- An exception is known as an unusual or unprecedented event that occurs during the execution of a software program or application. It is a runtime error of an unexpected result or event which influence and disrupt usual program flow. An exception is also considered as a fault.
--An exception is a problem that arises during the execution of a program.
--It’s an event that disrupts the normal flow of the program.
How exception occurs?
Following are some scenarios where an exception occurs.
1. A user has entered an invalid data.
2. A file that needs to be opened cannot be found.
3. A network connection has been lost in the middle of communications or the JVM has run out of memory.
Base class of Exception is Throwable. 
Please refer below link for more details on exception:

2. What is the difference between checked and unchecked exceptions in Java?
Answer: Types of java exceptions:
1. Checked Exception - Checked exceptions are checked at compile-time so this is also called compile time exceptions. Example of checked exceptions are : ClassNotFoundException, IOException, SQLException and so on.They occur usually interacting with outside resources/network resources e.g. database problems, network connection errors, missing files etc.
2. UnChecked Exception - Unchecked exceptions are not checked at compile-time, but they are checked at runtime. Also Called Run time Exceptions. Example of unchecked exceptions are :ArithmeticException, ArrayStoreException, ClassCastException and so on.
3. Error - Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

3. Which all method throw TimeOutExecption:
Answer:  Exception thrown when a blocking operation times out. Blocking operations for which a timeout is specified need a means to indicate that the timeout has occurred. For many such operations it is possible to return a value that indicates timeout; when that is not possible or desirable then TimeoutException should be declared and thrown.

4. What is the difference between throws and throw?

Answer:  Below are the differences between throw and throws:
1) Java throw keyword is used to explicitly throw an exception.
Java throws keyword is used to declare an exception.
2) Checked exception cannot be propagated using throw only.
Checked exception can be propagated with throws.
3) Throw is followed by an instance.
Throws is followed by class.
4) Throw is used within the method.
Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.
void myMethod() {
   try {
      //throwing arithmetic exception using throw
      throw new ArithmeticException("Something went wrong!!");
   catch (Exception exp) {
      System.out.println("Error: "+exp.getMessage());
//Declaring arithmetic exception using throws
void sample() throws ArithmeticException{

Other throw Example:
public class Example1{ 

voidcheckAge(int age){ 


                throw new ArithmeticException("Not Eligible for voting"); 


                System.out.println("Eligible for voting"); 


public static void main(String args[]){ 

                Example1 obj = new Example1();


                System.out.println("End Of Program"); 



throws example:
public class Example1{ 

int division(int a, int b) throws ArithmeticException{ 

                int t = a/b;

                return t;


public static void main(String args[]){ 

                Example1 obj = new Example1();




                catch(ArithmeticException e){

                System.out.println("You shouldn't divide number by zero");




5. How to handle exceptions in Java?
Answer: How to handle exception?
Java exception handling is managed via five keywords:
try: this keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone.
catch:  this block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
finally: this block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throw: this keyword is used to throw an exception.
throws: this keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.
try catch syntax:
//code that may throw an exception 
}catch(ExceptionClassName ref){
try finally block
//code that may throw an exception 

6. Can we have finally block without Try & Catch blocks?
Answer: Yes, we can have try without catch block by using finally block. ... As you know finally block always executes even if you have exception or return statement in try block except in case of System.

7. Give some examples for compile time errors in Java Programs?
Answer: Syntax errors are also a type of compile time error, for example, invalid variable names or mismatched brackets. A runtime error happens while the program is running, for example, a division by zero error, or a network connection refused error.

8. What is thread in java?
Answer: A thread is the smallest unit of processing that can be performed in an OS. In most modern operating systems, a thread exists within a process - that is, a single process may contain multiple threads.
Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.
Multithreading has several advantages over Multiprocessing such as;
Threads are lightweight compared to processes
Threads share the same address space and therefore can share both data and code
Context switching between threads is usually less expensive than between processes
Cost of thread intercommunication is relatively low that that of process intercommunication
Threads allow different tasks to be performed concurrently.

9. How does multi-threading achieved?
Answer:  Multithreading in java is a process of executing two or more threads simultaneously to maximum utilization of CPU.
Multithreaded applications are where two or more threads run concurrently; hence it is also known as Concurrency in Java. This multitasking is done, when multiple processes share common resources like CPU, memory, etc.

Each thread runs parallel to each other. Threads don't allocate separate memory area; hence it saves memory. Also, context switching between threads takes less time.
There are two ways to create a thread in Java:
1) By extending Thread class.
2) By implementing Runnable interface.
Before we begin with the programs(code) of creating threads, let’s have a look at these methods of Thread class. We have used few of these methods in the example below.
getName(): It is used for Obtaining a thread’s name
getPriority(): Obtain a thread’s priority
isAlive(): Determine if a thread is still running
join(): Wait for a thread to terminate
run(): Entry point for the thread
sleep(): suspend a thread for a period of time
start(): start a thread by calling its run() method

Method 1: Thread creation by extending Thread class
class MultithreadingDemo extends Thread{ 

  public void run(){ 

    System.out.println("My thread is in running state."); 


  public static void main(String args[]){ 

     MultithreadingDemo obj=new MultithreadingDemo();  





My thread is in running state.

Method 2: Thread creation by implementing Runnable Interface
class MultithreadingDemo implements Runnable{ 

  public void run(){ 

    System.out.println("My thread is in running state."); 


  public static void main(String args[]){ 

     MultithreadingDemo obj=new MultithreadingDemo(); 

     Thread tobj =new Thread(obj); 





My thread is in running state.

10. How to initiate a thread in java?
Answer: Java lets you create a thread one of two ways:

By implementing the Runnableinterface.
By extending the Thread.
Let's look at how both ways help in implementing the Java thread.
Runnable Interface
The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable interface, a class need only implement a single method called run( ), which is declared like this:
public void run( )

Inside run( ), we will define the code that constitutes the new thread. 


public class TestClass implements Runnable {

public void run(){

System.out.println("TestClass  running");



To execute the run() method by a thread, pass an instance of TestClass to a Thread in its constructor (A constructor in Java is a block of code similar to a method that's called when an instance of an object is created). Here is how that is done:
Thread t1 = new Thread(new TestClass ());

When the thread is started it will call the run() method of the TestClass instance instead of executing its own run() method. The above example would print out the text "TestClass running ".
Extending Java Thread:
The second way to create a thread is to create a new class that extends Thread, then override the run() method and then to create an instance of that class. The run() method is what is executed by the thread after you call start(). 
Here is an example of creating a Java Thread subclass:
public class TestClass extends Thread {

public void run(){

System.out.println("TestClass running");



To create and start the above thread:

TestClass t1 = new TestClass ();


When the run() method executes it will print out the text " TestClass running ".

11. What do you mean by thread safe?
Answer: Thread-safe code is code that will work even if many Threads are executing it simultaneously. A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time.

12. What is a Collection and what are the types of collections?
Answer:  1. A Collection is a group of individual objects represented as a single unit
2. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
3. The Java Collections Framework is a collection of interfaces and classes which helps in storing and processing the data efficiently.
ArrayList, LinkedList, Vector, Stack, PriorityQueue, HashSet, LinkedHashSet, TreeSet, HashMap, LinkedHashMap, TreeMap and HashTable.
Collection Interface:
1. Root interface with basic methods like add(), remove(), contains(), isEmpty(), addAll(), clear().. etc.
2. All other collection interfaces and classes (except Map) either extend or implement this interface. For example, List (indexed, ordered) and Set (sorted) interfaces implement this collection.

13. Collection are what type?
Answer: A collection is a concept applicable to abstract data types.
Fixed-size arrays (or tables) are usually not considered a collection because they hold a fixed number of data items, although they commonly play a role in the implementation of collections. Variable-size arrays are generally considered collections.

14. What is the difference between collection and collections?
Answer: Collection is a root level interface of the Java Collection Framework. Most of the classes in Java Collection Framework inherit from this interface. List, Set and Queue are main sub interfaces of this interface. JDK doesn’t provide any direct implementations of this interface. But, JDK provides direct implementations of it’s sub interfaces. ArrayList, Vector, HashSet, LinkedHashSet, PriorityQueue are some indirect implementations of Collection interface. Map interface, which is also a part of java collection framework, doesn’t inherit from Collection interface. Collection interface is a member of java.util package.
Collections is an utility class in java.util package. It consists of only static methods which are used to operate on objects of type Collection. For example, it has the method to find the maximum element in a collection, it has the method to sort the collection, it has the method to search for a particular element in a collection. Below is the list of some important methods of Collections class.
1. Collections.max() - This method returns maximum element in the specified collection.
2. Collections.min() - This method returns minimum element in the given collection.
3. Collections.sort() - This method sorts the specified collection.
4. Collections.shuffle() - This method randomly shuffles the elements in the specified collection.
5. Collections.synchronizedCollection() -This method returns synchronized collection backed by the specified collection.
6. Collections.binarySearch() - This method searches the specified collection for the specified object using binary search algorithm.
7. Collections.disjoint() - This method returns true if two specified collections have no elements in common.
8. Collections.copy() - This method copies all elements from one collection to another collection.
9. Collections.reverse() -This method reverses the order of elements in the specified collection.

15. What is the difference between heap and stack?
Answer: Differences Between Stack and Heap Allocations
1. In a stack, the allocation and deallocation is automatically done by whereas, in heap, it needs to be done by the programmer manually.
2. Handling of Heap frame is costlier than handling of stack frame.
3. Memory shortage problem is more likely to happen in stack whereas the main issue in heap memory is fragmentation.
4. Stack frame access is easier than the heap frame as the stack have small region of memory and is cache friendly, but in case of heap frames which are dispersed throughout the memory so it cause more cache misses.
5. Stack is not flexible, the memory size allotted cannot be changed whereas a heap is flexible, and the allotted memory can be altered.
6. Accessing time of heap takes is more than a stack.

16. Difference between Array and ArrayList?
Answer: 1. Array: Simple fixed sized arrays that we create in Java, like below:

 Example: int arr[] = new int[10]
2. ArrayList : Dynamic sized arrays in Java that implement List interface.
ArrayList<Type> arrL = new ArrayList<Type>();
Differences between Array and ArrayList:
1. An array is basic functionality provided by Java.
ArrayList is part of collection framework in Java. Therefore array members are accessed using [], while ArrayList has a set of methods to access elements and modify them.

import java.util.ArrayList;

import java.util.Arrays;

  class Test


    public static void main(String args[])


        /* ........... Array............. */

        int[] arr = new int[2];

        arr[0] = 1;

        arr[1] = 2;




        // Create an arrayList with initial capacity 2

        ArrayList<Integer> arrL = new ArrayList<Integer>(2);


        // Add elements to ArrayList




        // Access elements of ArrayList





2. Array is a fixed size data structure while ArrayList is not. One need not to mention the size of Arraylist while creating its object.
Even if we specify some initial capacity, we can add more elements.
3. Array can contain both primitive data types as well as objects of a class depending on the definition of the array. However, ArrayList only supports object entries, not the primitive data types.
Note: When we do arraylist.add(1); : it converts the primitive int data type into an Integer object.
4. Since ArrayList can’t be created for primitive data types, members
of ArrayList are always references to objects at different memory locations. Therefore in ArrayList, the actual objects are never stored at contiguous locations. References of the actual objects are stored at contiguous locations.
In array, it depends whether the arrays is of primitive type or object type. In case of primitive types, actual values are contiguous locations, but in case of objects, allocation is similar to ArrayList.

5. Multi-dimensional :  Array can be multi dimensional , while ArrayList is always single dimensional.

17. What is the difference between ArrayList and LinkedList?
Answer: Below are the differences between ArrayList and LinkedList.

1) ArrayList internally uses a dynamic array to store the elements.       
LinkedList internally uses a doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory.        
Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
3) An ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data.     
LinkedList is better for manipulating data.

18. Difference between Set and HashSet?
Answer: A Set is a generic set of values with no duplicate elements. A TreeSet is a set where the elements are sorted.

A HashSet is a set where the elements are not sorted or ordered. It is faster than a TreeSet. The HashSet is an implementation of a Set.
Set is a parent interface of all set classes like TreeSet, HashSet, etc.

19. Difference between HashMap and HasTable?
Answer: Below are the differences between HashMap and HasTable.

1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.                   
Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2) HashMap allows one null key and multiple null values.
Hashtable doesn't allow any null key or value.
3) HashMap is a new class introduced in JDK 1.2.
Hashtable is a legacy class.
5) We can make the HashMap as synchronized by calling this code::
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can't be unsynchronized.
6) HashMap is traversed by Iterator.
Hashtable is traversed by Enumerator and Iterator.
7) Iterator in HashMap is fail-fast.
Enumerator in Hashtable is not fail-fast.
8) HashMap inherits AbstractMap class.
Hashtable inherits Dictionary class.

20. How do you use Map collection your project?
Answer: Map is nothing but a key value pair mappings; every in the map has a value, and every value has a key. Map keys follow Set interface and allow only unique values; Map Values are following List interface and allows duplicates. It is similar to the attendance system, the roll number is Keys, and names are Values. Roll Number is unique, but the names could be duplicates.

21. Can we have duplicate key value in HasMap?
Answer:  HashMap doesn't allow duplicate keys but allows duplicate values. That means A single key can't contain more than 1 value but more than 1 key can contain a single value. HashMap allows null key also but only once and multiple null values.

22. How to fetch values from a hashmap?

23. How to convert array in to collection ?

Answer: Following example demonstrates to convert an array into a collection Arrays.asList(name) method of Java Util class.
import java.util.*;


public class ArrayToCollection{

   public static void main(String args[]) throws IOException {

      BufferedReader in = new BufferedReader (new InputStreamReader(;

      System.out.println("How many elements you want to add to the array: ");

      int n = Integer.parseInt(in.readLine());

      String[] name = new String[n];

      for(int i = 0; i < n; i++) {

         name[i] = in.readLine();


      List<String> list = Arrays.asList(name);


      for(String li: list) {

         String str = li;

         System.out.print(str + " ");




How many elements you want to add to the array:
red white green

red white green

24. What is the relationship between Iterator interface and iterator() method in Java?
Answer: The iterator() method returns an Iterator which then can be used to iterate over an object of that class. Any class implementing the Iterator interface needs to override the hasNext() and next() methods provided by the Iterator interface.

1 comment:

  1. Question 23: following step is throwing up an numberformat exception ?
    int n = Integer.parseInt(in.readLine());