Quantcast
Channel: Interview Questions – Web Development Tutorial
Viewing all articles
Browse latest Browse all 26

MUST Have Core Java Interview Questions – Part 2

$
0
0

Let’s continue with Part-2 of MUST Have Core Java Interview Questions and Detailed answers tutorial. Major topics covered in this Java Tutorial are Exception Handling in Java, Threading in Java and Synchronization, Access Modifiers and usage, thread pooling in Java, Complete Collection Framework and Inner Classes.

Java Interview Questions and Answers

Complete Java Interview Questions List

Courses Online

What are different kind of exceptions in java. Explain Runtime and complie time exceptions ? Explain try,catch,throw,throws,finally with example.

Exceptions start from the base class Throwable. Throwable has two hierarchies one is error and other is exceptions. An exception further has its own hierarchy and furthermore divides into Runtime (Unchecked) and all exceptions other than this runtime exception falls into Compile (Checked) exceptions.Exception Handing in Java

As we can see in the diagram above Throwable is the parent class from where all exception propagates. Error is basically an unwanted scenario in the code which will occur and the system will been able to recover from this. Like stack overflow or the heap dump error, which are not recoverable. On the other hand exceptions are the scenarios where in our system will be able to recover from it. I.e. we can handle these types of scenarios in our code.

Lets understand each of them with example.

Runtime (Unchecked) Exception:

Runtime exceptions are basically programming exceptions, which will occur during run of program. Lets say we are writing some mathematical programming code where we are have function which take two parameters , one as dividend and one as divisor.

package com.javatutorial.exceptionhandling;

public class RuntimeExceptionMain
{

    public static void main(String[] args)
    {
        int dividend = Integer.parseInt(args[0]);
        int divisor = Integer.parseInt(args[1]);
        double result = doDivide(dividend,divisor);
        System.out.println("Result is : "+result);
    }

    private static double doDivide(int dividend, int divisor)
    {
        return dividend/divisor;
    }

}

So we are taking parameters form console and passing them to the divide function, which divides and returns the result. By mistake someone has sent the divisor as zero. Ideally one should not send zero as divisor.Runtime Exceptions in Java

So we send two arguments as 12 and zero, lets run and see what we see in output.Output for Exceptions in Java

So we got divide by zero exception, which we got when we try to run the code with the arguments, we got the divide by zero exception, which is a kind of runtime exception in java. So in essence we got runtime exception when we try to run the code with wrong arguments and we don’t have any try/catch block.

Compiletime (Checked) Exception:

Checked exceptions are the exceptions which are occurred during compile time of the code. For example we are writing code where we are dealing with I/O. Some of the methods of File api throws exception which we need to handle in our code, if we don’t add handing for these exception by throws in the method signature or adding try/catch in the code fragment, our code will not compile. Lets take an example where in we will using the File api and we add the code from which we don’t have the handling for the thrown exception.

package com.javatutorial.exceptionhandling;

import java.io.File;

public class CompileTimeMain
{

    public static void main(String[] args)
    {
        File file = new File("c:/text.txt");
        file.createNewFile();
    }

}

Now if we try to compile the code using command prompt, it will not compile. If you are coding using IDE, the IDE will suggest us to handle the exception and mark this line of code as non-compliable. Lets try to compile the code using command prompt and see what happens:Compile Time Exceptions in Java

As we can see when trying to compile the code, compiler is explaining about the exception must be caught or declared to be thrown.

Lets talk about few keywords that are used in exception handling in java.

Try/catch: try/catch is used when there is possible exception in a code block and an exception is been thrown out of it or an exception can be occur out of this code block. In these kind of scenarios we use try/catch block. There can be multiple catch blocks with a try block, but the thumb rule is that exception can not be narrow down in the subsequent catch block. Example of try/catch block is below:

public class CompileTimeMain
{

    public static void main(String[] args)
    {
        File file = new File("c:/text.txt");
        try
        {
            file.createNewFile();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

throw/throws:

throw/throws is used when in a method we want to indicate the calling method that the code is throwing some exception. Throw used mostly when we want to wrap an exception to a particular kind of user defined exception.

Finally:

Finally keyword is used when we want to do some particular kind of task even after the exception is thrown out of the code. Finally code is always executed, except some particular scenarios where we use System.exit in any of the catch block.

Back to top

How to create thread in java, what are different ways to create a thread? Explain synchronization with example.

To create thread in java, there are two ways:

  • By extending Thread class
  • By implementing runnable interface

Let’s understand the same with example:

package com.javatutorial.multithreading;

public class Main
{

    public static void main(String[] args)
    {
        Thread t1 = new PrintThread();
        Thread t2 = new Thread(new PrintRunnable());

        t1.start();
        t2.start();
    }

}

class PrintThread extends Thread{

    public void run(){
        System.out.println("In there !! Creating thread with extending Thread class");
    }
}

class PrintRunnable implements Runnable{

    @Override
    public void run()
    {
        System.out.println("In there !! Creating thread with implementing Runnable interface !! ");
    }
}

In the example above we are creating thread with both extending Thread class and also implementing Runnable interface. We have created a class PrintThread which is extending the Thread class and in the run method we have printed a string. On the other hand we have also created  class PrintRunnable which is implementing runnable interface and we have overridden the run method of this interface and in the run method we did some dummy text.

If you see the code thoroughly, in the main method where we have instantiated both Thread, the class with is extending the thread class we have created direct object, since it is extending the thread class, where as the class which is implementing the Runnable interface, we have created a Thread object and passed Runnable object to it.

One we are done with the initiation part, all we need to do is to start the threads.

Upon running the code what we got as output is:Threading in Java

Synchronization in Java:

Synchronization is the concept of acquiring lock on an object. In java each object has a lock and to acquire the lock on an object we need to use a keyword that is used for this purpose only, that is synchronized.

By using this keyword we can acquire lock on an object, the scope of lock can be on method or on a particular piece of code.  It is always advisable to lock a particular piece of code instead of locking the entire method. Since if there will be lock on the method level then all objects will be kept on waiting stating until unless the running thread does not completes its task.

A part of synchronized keyword, Lock api does the same task. So we can use Lock api as well instead of synchronized keyword.

Back to top

What are different access modifiers in java, explain with example?

Access modifiers are the modifiers which provides access/visibility to class, method, field.

In java there are four access modifiers :

  • Public
  • Private
  • Protected
  • Default

Public access modifier provides object visibility to anywhere. Any object can access public class, public interface from anywhere. When we are saying anywhere it means from any class from any package. Public access modifier can be applied on class, methods, fields , constructor, interfaces and inner classes.

Private access modifier provides object visibility to no-where, other than the class. It is just reverse of public access modifier. Private access modifier can be applied on methods, fields, and constructor and inner classes.

Protected access modifier provides object visibility to same package or any other package where the class is been sub classed. Protected access modifier can be applied on methods, fields and constructor.

Default access modifier provides object visibility to same package only. Default access modifier can be applied on class, methods, fields, constructor and inner classes.

Lets check the same with some code stuff. We will be creating two packages to check the access, also we will add one class with four methods with four different access modifiers and we try to check how the visibility goes.

Lets start with creating CheckAccess class which has four methods with all four modifiers.

package com.javatutorial.accessmodifiers;

public class CheckAccess
{
    public void doCheckPublicAcccess(){
        System.out.println("Method with public access modifier, Accessed from outer class");
    }

    private void doCheckPrivateAcccess(){
        System.out.println("Method with private access modifier");
    }

    void doCheckDefaultAccess(){
        System.out.println("Method with Default access modifier");
    }

    protected void doCheckProtectedAccess(){
        System.out.println("Method with Protected access modifier");
    }
}

Lets create a Main class and try to access these four methods.

package com.javatutorial.accessmodifiers;

public class MainCheckAccess
{
    public static void main(String[] args)
    {
        CheckAccess access = new CheckAccess();

        access.doCheckDefaultAccess();

        access.doCheckProtectedAccess();

        access.doCheckPublicAcccess();

        access.doCheckPrivateAcccess();

    }
}

So we have added all four methods, lets try and run the code.

Upon running the code what we got is:Private Access Modifier in Java

So we got exception, since doCheckPrivateAccess has the private access modifier and doesnot have visibility to outer class other then the class itself where it is declared.

Lets test the same with other package. So we will be creating the same main class in other package and try to run the code.Main Check Access

So as we can see other than method with public access modifier, no methods can be accessed in this class which is other package. So it is as expected, now check for protected modifier which are accessible from other package where class is sub classed. Let’s modify our code and check:

package com.javatutorial.accessmodifierotherpackage;

import com.javatutorial.accessmodifiers.CheckAccess;

public class MainCheckAccess extends CheckAccess
{
    public void testAccess(){
        doCheckProtectedAccess();

        doCheckPublicAcccess();

        doCheckPrivateAcccess();

        doCheckDefaultAccess();
    }

    public static void main(String[] args)
    {
        new MainCheckAccess().testAccess();
    }
}

Upon compilation of this code what we got is:Java Access Modifiers

Only public and protected modifiers have visibility in this class. Public one because public has visibility all over and protected because protected access modifier has visibility in same package and other package where it sub classed.

Back to top

What is thread pool in java? Explain executor framework with different types of thread pools in java?

Thread pool, as the name suggests, it is a special kind of pool that maintains threads. Thread pool keep threads alive and not let them die. Whenever a task needs a thread, thread pool fetches the thread from thraedpool and allocates to task. Thread does its task and again comes into the pool.

So we are talking about die of thread, what is that special thing in thread that don’t keep threads to die. Or if we take the same in other way, when a thread dies. When we call thread has completed the task and it is no more alive now.

So we are talking about the run() method of thread. This method is responsible for keeping the thread alive, when a thread exits from the run method it is died. What thread pool does specially is that it don’t get the thread exit from the run method. This is so special about the thread pools.

To create thread in java is not an easy task behind the scene for vm. What thread pool does specially for vm is it just removes the extra thing that vm needs to do for creating threads separately. In java there is something called executor framework, which provides some special kind of thread pools. Using the executor framework the same can be achieved.

Let’s talk about the thread pools that executor framework provides. There are four kind of threadpools in java:

  • Fixed Size Thread Pool
  • Cached Thread Pool
  • Single Thread executor
  • Scheduled Thread Pool

Fixed Size Thread Pool

Fixed size thread pool is a thread pool, where a fix number of threads are available. Whenever any task arrives it is been allocated to a thread whichever is free at that point of time. If no thread is free at that point of time the task is kept on waiting until a thread is free. If any thread dies during run, then it’s executor functionality to ensure that the thread will be created.

Signature to create service with this kind of thread pool is:

ExecutorService executorService = Executors.newFixedThreadPool(<number of threads>);

Here 10 is number of threads that we want as part of this service. These can very as per requirement.

Threads in this thread pool dies once shutdown() is called, till then all threads in the threadpool are kept alive and they keep picking tasks.

Cached Thread pool:

Cached thread pool is a thread pool, where threads are kept in cache and they are created as and when needed.  If there are threads available and a task arrives then the threads are reused. Once a thread is done with the task then the same thread is kept into the pool. In order to make is more efficient and less resource consumption, the threads in pool are terminated after every 60 seconds, which are idle.

Signature to create service with this kind of thread pool is:

ExecutorService executorService = Executors.newCachedThreadPool();

This piece of code will create an executor where threads will be created as and when needed and idle threads will be terminated after a minute.

Single Thread Executor :

Single thread  executor is a thread executor  where exactly one thread executes a task. So it is guaranteed that one task will be executed at one point of time. If any task arrives when the executor is executing a task, then the arrived task is kept in a queue and as soon the executor completes the running task, new task got picked and is executed. This kind of thread pool is used when tasks are required to run sequentially.

Signature to create service with this kind of thread pool is:

ExecutorService executorService = Executors.newSingleThreadExecutor();

The above line of code will create an executor with a single thread.

Scheduled Thread Pool :

Scheduled thread pool is a kind of thread pool where threads can be scheduled to run at certain amount of time. Threads can also be triggered to run at certain period. In this case threads will run at a certain period.

Back to top

Continue with Java Interview Questions Preparation

What is collection framework, explain collection hierarchy? Briefly explain List, Set, Map, Comparator and comparable.

Collections in Java

Above is the diagram of collection framework. Collection interface sits on the top of the hierarchy, below this there are interfaces like List, Set, Queue that extends this Collection interface.  Below this in hierarchy are the Classes that implement these interfaces. Like ArrayList, LinkedList etc classes implements List interface. Whereas Hash Set etc classes implements Set interface. LinkedList, PriorityQueue implements Queue interface.

Interesting to see there is no Map interface in this hierarchy, isn’t it ? Map interface has its own hierarchy, and the reason behind it that Map works on key, value pair rest all collection classes works on value part only and not key value.

Let’s see how Map hierarchy goes: Map Heirarchy in Java

As we can see in the diagram, classes like HashMap, HashTable implements Map interface, since Map stores in key, value pair and not only the elements.

Lets start with List interface :

Whenever one wants to store elements in ordered sequence, that can be accessed based on index or based on iteration, List interface is used there. List maintains the insertion order and retrieval on list is also based on the iteration of the list. List store any type of objects and based on the object type if it is primitive List automatically box unbox the primitive data types. One more property of list interface is that list allows the null and duplicate elements that are not allowed in some of the data structures that we will talk later on.

Most common and most used implementation of list interface are LinkedList and ArrayList.List Interface in Java

The above are the methods available in list interface. Implementation of the same can be found in each and every implementation of List interface.

Lets move to set interface:

Generally we use set where we want no duplicate elements, HashSet is most common implementation of Set interface and most widely used.

Set has the property that is does not allows any duplicate elements, one null element is allowed but not more than one null element.

One more important thing to keep in mind is that, whenever we are using any custom object in Set, we must override the equals and hash code methods from object class these are utter important when dealing with the hash based collection.

Let’s now move to Map interface:

Map interface is used when we want some key value kind of relationship. This is the only reason that map does not fall into the standard Collection hierarchy. Since if you can see all the implementation of the Collection interface have only the value part and none of them has the key value mapping. So what if one needs key value mapping, here Map comes to rescue, Map provides key value mapping of the objects.

As we talked in the Set part, while dealing with Maps as well one must override the equals and hash code methods from object class and provide the implementation accordingly.

Whenever one dealing with sorting of collection, Comparable and Comparator are the collection that we needs to use. Both are used for sorting of the underlying collection.

It is all about the collection interface in brief.

Back to top

Explain are Inner classes in Java? When will you use an Inner Class?

Inner classes as the name suggests are the classes within classes. So there will be outer classes and inner classes concept. Inner classes will always be a part of outer class and they will be enclosed in outer classes.

Inner classes behave much more similar to a method in a class or a field in a class. Like there are members of a class same as inner classes will also be part of class within which the inner class in enclosed.

Usually we should avoid to use inner classes because class within a class and to read such kind of code is a bit hard, inner classes are good to write but at the same time they make your code less readable.

Also to maintain the code with such properties is not an easy task, like if there are some modifications in the class than one should have the full knowledge about the class how it was written and what the inner class in is has intended to.

Lets take an example of inner class:

package com.javatutorial.innerclass;

public class Employee
{
    String name;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    static class Department{
        int id;

        public int getId()
        {
            return id;
        }

        public void setId(int id)
        {
            this.id = id;
        }

    }
}

So we have created a class named Employee and there is an inner class called Department. Outer class have one field name and inner class also have one field id that is of type integer.

Lets see how this class can be used.

We will be creating a main class and we will try to use this class:

package com.javatutorial.innerclass;

public class MainInner
{
    public static void main(String[] args)
    {
        Employee emp = new Employee();
        emp.setName("Ahmad");
        Employee.Department department = new Employee.Department();
        department.setId(12);
    }
}

This is how the inner class can be used. As we can see the Department class is property of Employee class then the Department will be accessed can be only accessed with reference of Employee class only.

There is one more concept as well to create anonymous inner classes, let see how to create and use them.

This is how inner classes are created and used in java.

Back to top

This Java Tutorial Series is continued and you can find more Java Interview Questions in next Web Development Tutorial here.

Top Technical Interview Questions and Answers Series:

The post MUST Have Core Java Interview Questions – Part 2 appeared first on Web Development Tutorial.


Viewing all articles
Browse latest Browse all 26

Trending Articles