29 Java Interview Questions and Answers

1. What is Java?

Answer: Java is an object-oriented, high-level, general-purpose programming language originally designed by James Gosling and further developed by the Oracle Corporation. It is one of the most popular programming languages in the world. 

2. What do you mean by Constructor?

Answer: A constructor is a method that has the same name as that of the class to which it belongs. As soon as a new object is created, a constructor corresponding to the class gets invoked. Although the user can explicitly create a constructor, it is created on its own as soon as a class is created. This is known as the default constructor. Constructors can be overloaded.

Note: - If an explicitly-created constructor has a parameter then it is necessary to create another constructor without a parameter.

3. What are the features of Java?

Answer: Following are the various features of the Java programming language:

  • High Performance– Using a JIT (Just-In-Time) compiler allows high performance in Java. The JIT compiler converts the Java bytecode into machine language code, which then gets executed by the JVM
  • Multi-threading– A thread is a flow of execution. The JVM creates a thread which is called the main thread. Java allows the creation of several threads by means of either extending the thread class or implementing the Runnable interface
  • OOPS Concepts– Java follows various OOPS concepts, namely abstraction, encapsulation, inheritance, object-oriented, and polymorphism
  • Platform Independency– Java makes use of the Java Virtual Machine or JVM which allows a single Java program to operate on multiple platforms without any modifications

4. How does Java enable high performance?

Answer: In the Just-in-Time compilation, the required code is executed at run time. Typically, it involves translating bytecode into machine code and then executing it directly. For enabling high performance, Java can make use of the Just-In-Time compilation. The JIT compiler is enabled by default in Java and gets activated as soon as a method is called. It then compiles the bytecode of the Java method into native machine code. Thereafter, the JVM calls the compiled code directly instead of interpreting it. This grants a performance boost.

5. What do you understand by Java IDEs?

Answer: A Java IDE is a software that allows Java developers to easily write as well as debug Java programs. It is basically a collection of various programming tools, accessible via a single interface, and several helpful features, such as code completion and syntax highlighting. Codenvy, Eclipse, and NetBeans are some of the most popular Java IDEs.

6. Please explain Local variables and Instance variables in Java.

Answer: Variables that are only accessible to the method or code block in which they are declared are known as local variables. Instance variables, on the other hand, are accessible to all methods in a class. While local variables are declared inside a method or a code block, instance variables are declared inside a class but outside a method. Even when not assigned, instance variables have a value that can be null, 0, 0.0, or false. This isn’t the case with local variables that need to be assigned a value, where failing to assign a value will yield an error. Local variables are automatically created when a method is called and destroyed as soon as the method exits. For creating instance variables, the new keyword must be used.

7. What is an Object?

Answer: An instance of a Java class is known as an object. Two important properties of a Java object are behavior and state. An object is created as soon as the JVM comes across the new keyword.

8. Could you explain the Oops concepts?

Answer: Following are the various OOPS Concepts:

  • Abstraction– Representing essential features without the need to give out background details. The technique is used for creating a new suitable data type for some specific application
  • Aggregation– All objects have their separate lifecycle but ownership is present. No child object can belong to some other object except for the parent object
  • Association– The relationship between two objects, where each object has its separate lifecycle. There is no ownership
  • Class– A group of similar entities
  • Composition– Also called the death relationship, it is a specialized form of aggregation. Child objects don’t have a lifecycle. As such, they automatically get deleted if the associated parent object is deleted
  • Encapsulation– Refers to the wrapping up of data and code into a single entity. Allows the variables of a class to be only accessible by the parent class and no other classes
  • Inheritance– When an object acquires the properties of some other object, it is called inheritance. It results in the formation of a parent-child relationship amongst classes involved. Offers a robust and natural mechanism of organizing and structuring software
  • Object– Denotes an instance of a class. Any class can have multiple instances. An object contains the data as well as the method that will operate on the data
  • Polymorphism– refers to the ability of a method, object, or variable to assume several forms

9. Please explain Method Overriding in Java?

Answer: Method Overriding in Java allows a subclass to offer a specific implementation of a method that has already provided by its parent, or super, class. Method overriding happens if the subclass method and the Superclass method have:

  • The same name
  • The same argument
  • The same return type

10. What do you mean by Overloading?

Answer: Overloading is the phenomenon when two or more different methods (method overloading) or operators (operator overloading) has the same representation. For example, the + operator adds two integer values but concatenates two strings. Similarly, an overloaded function called Add can be used for two purposes

  1. To add two integers
  2. To concatenate two strings

Unlike method overriding, method overloading requires two overloaded methods to have the same name but different arguments. The overloaded functions may or may not have different return types.

11. Please explain the difference between String, String Builder, and String Buffer.

Answer: String variables are stored in a constant string pool. With the change in the string reference, it becomes impossible to delete the old value. For example, if a string has stored a value “Old” then adding the new value “New” will not delete the old value. It will still be there, however, in a dormant state. In a String Buffer, values are stored in a stack. With the change in the string reference, the new value replaces the older value. The String Buffer is synchronized (and therefore, thread-safe) and offers slower performance than the String Builder, which is also a String Buffer but is not synchronized. Hence, performance is fast in String Builder than the String Buffer.

12. What is Set in Java? Also, explain its types in a Java Collections.

Answer: In Java, a Set is a collection of unique objects. It uses the equals() method to determine whether two objects are the same or not. Various types of Set in Java Collections are:

  1. Hash Set– An unordered and unsorted set that uses the hash code of the object for adding values. Used when the order of the collection isn’t important
  2. Linked Hash Set– This is an ordered version of the hash set that maintains a doubly-linked list of all the elements. Used when iteration order is mandatory. Insertion order is the same as that of the manner in which elements are added to the Set.
  3. Tree Set– One of the two sorted collections in Java, it uses Read-Black tree structure and ensures that the elements are present in the ascending order.

13. Please draw a comparison between notify() and notifyAll() methods.

Answer: The notify() method is used for sending a signal to wake up a single thread in the waiting pool. Contrarily, the notifyAll() method is used for sending a signal to wake up all threads in a waiting pool.

14. When is the Runnable interface preferred over thread class and vice-versa?

Answer: In Java, it is possible to extend only one class. Hence, the thread class is only extended when no other class needs to be extended. If it is required for a class to extend some other class than the thread class, then we need to use the Runnable interface.

15. Please explain the various types of garbage collectors in Java?

Answer: The Java programming language has four types of garbage collectors:

  1. Serial Garbage Collector– Using only a single thread for garbage collection, the serial garbage collector works by holding all the application threads. It is designed especially for single-threaded environments. Because serial garbage collector freezes all application threads while performing garbage collection, it is most suitable for command-line programs only. For using the serial garbage collector, one needs to turn on the -XX:+UseSerialGC JVM argument.
  2. Parallel Garbage Collector – Also known as the throughput collector, the parallel garbage collector is the default garbage collector of the JVM. It uses multiple threads for garbage collection and like serial garbage collector freezes all application threads during garbage collection.
  3. CMS Garbage Collector– Short for Concurrent Mark Sweep, CMS garbage collector uses multiple threads for scanning the heap memory for marking instances for eviction, followed by sweeping the marked instances. There are only two scenarios when the CMS garbage collector holds all the application threads:
    1. When marking the referenced objects in the tenured generation space
    2. If there is some change in the heap memory while performing the garbage collection CMS garbage collector ensures better application throughput over parallel garbage collector by using more CPU. For using the CMS garbage collector, the XX:+USeParNewGC JVM argument needs to be turned on.
  4. G1 Garbage Collector  Used for large heap memory areas, G1 garbage collector works by separating the heap memory into multiple regions and then executing garbage collection in them in parallel. Unlike the CMS garbage collector that compacts the memory on STW (Stop The World) situations, G1 garbage collector compacts the free heap space right after reclaiming the memory. Also, the G1 garbage collector prioritizes the region with the most garbage. Turning on the –XX:+UseG1GC JVM argument is required for using the G1 garbage collector.

16. How will you differentiate HashMap from HashTable?

Answer: HashMap in Java is a Map-based collection class, used for storing key & value pairs. It is denoted as HashMap<Key, Value> or HashMap<K, V> HashTable is an array of a list, where each list is called a bucket. Values contained in a HashTable are unique and depend on the key. Methods are not synchronized in HashMap while key methods are synchronized in HashTable. However, HashMap doesn’t have thread safety while HashTable has the same. For iterating values, HashMap uses iterator and HashTable uses enumerator. HashTable doesn’t allow anything that is null while HashMap allows one null key and several null values. In terms of performance, HashTable is slow. Comparatively, HashMap is faster.

17. What do you mean by Collections in Java? What are the constituents of Collections in Java?

Answer: A group of objects in Java is known as collections. Java.util package contains, along with date and time facilities, internationalization, legacy collection classes, etc., the various classes and interfaces for collecting. Alternatively, collections can be considered as a framework designed for storing the objects and manipulating the design in which the objects are stored. You can use collections to perform the following operations on objects:

  • Deletion
  • Insertion
  • Manipulation
  • Searching
  • Sorting

Following are the various constituents of the collections framework:

  • Classes – Array List, Linked List, Lists, and Vector
  • Interfaces – Collection, List, Map, Queue, Set, Sorted Map, and Sorted Set
  • Maps – HashMap, HashTable, LinkedHashMap, and TreeMap
  • Queues – Priority Queue
  • Sets – Hash Set, Linked Hash Set, and Tree Set

18. Please explain Map and their types in Java.

Answer: A Java Map is an object that maps keys to values. It can’t contain duplicate keys and each key can map to only one value. In order to determine whether two keys are the same or distinct, Map makes use of the equals() method. There are 4 types of Map in Java, described as follows:

  • HashMap - It is an unordered and unsorted map and hence, is a good choice when there is no emphasis on the order. A HashMap allows one null key and multiple null values and doesn’t maintain any insertion order.
  • HashTable – Doesn’t allow anything null and has methods that are synchronized. As it allows for thread safety, the performance is slow.
  • LinkedHashMap – Slower than a HashMap but maintains insertion order and has a faster iteration.
  • TreeMap – A sorted Map providing support for constructing a sort order using a constructor.

19. What do you mean by Priority Queue in Java?

Answer: Priority queue, like a regular queue, is an abstract data type with the exception of having a priority associated with each element contained by it. The element with the high priority is served before the element with low priority in a priority queue. Elements in a priority queue are ordered either according to the comparator or naturally. The order of the elements in a priority queue represents their relative priority.

20. How is an Abstract class different from an Interface?

Answer: There are several differences between an Abstract class and an Interface in Java, summed up as follows:

  • Constituents – An abstract class contains instance variables, whereas an interface can contain only constants.
  • Constructor and Instantiation – While an interface has neither a constructor nor it can be instantiated, an abstract class can have a default constructor that is called whenever the concrete subclass is instantiated.
  • Implementation of Methods – All classes that implement the interface need to provide an implementation for all the methods contained by it. A class that extends the abstract class, however, doesn’t require implementing all the methods contained in it. Only abstract methods need to be implemented in the concrete subclass.
  • Type of Methods – Any abstract class has both abstract as well as non-abstract methods. Interface, on the other hand, has only a single abstract method.

21. Could you explain various types of Exceptions in Java? Also, tell us about the different ways of handling them.

Answer: Java has provision for two types of exceptions:

  • Checked Exceptions – Classes that extend Throwable class, except Runtime exception and Error, are called checked exceptions. Such exceptions are checked by the compiler during the compile time. These types of exceptions must either have appropriate try/catch blocks or be declared using the throws keyword. ClassNotFoundException is a checked exception.
  • Unchecked Exceptions – Such exceptions aren’t checked by the compiler during the compile time. As such, the compiler doesn’t necessitate handling unchecked exceptions. Arithmetic Exception and ArrayIndexOutOfBounds Exception are unchecked exceptions.

Exceptions in Java are handled in two ways:

  • Declaring the throws keyword – We can declare the exception using throws keyword at the end of the method. For example,

·        class ExceptionCheck{

·        public static void main(String[] args){

·        add();

·        }

·        public void add() throws Exception{

·        addition();

·        }

·        }

  • Using try/catch – Any code segment that is expected to yield an exception is surrounded by the try block. Upon the occurrence of the exception, it is caught by the catch block that follows the try block. For example,

·        class ExceptionCheck{

·        public static void main (String[] args) {

·        add();

·        }

·        public void add(){

·        try{

·        addition();

·        }catch(Exception e){

·        e.printStacktrace();

·        }

·        }

·        }

22. Could you draw the Java Exception Hierarchy?

 

Answer:Java Exception Hierarchy

23. What role does the final keyword play in Java? What impact does it have on a variable, method, and class?

Answer: The final keyword in Java is a non-access modifier that is applicable only to a class, method, or variable. It serves a different purpose based on the context where it is used.

  • With a class:

When a class is declared as final then it is disabled from being subclassed i.e. no class can extend the final class.

  • With a method:

Any method accompanying the final keyword is restricted from being overridden by the subclass.

  • With a variable:

A variable followed by the final keyword is not able to change the value that it holds during the program execution. So, it behaves like a constant.

24. How do you make a thread in Java? Give examples.

Answer: In order to make a thread in Java, there are two options:

  • Extend the Thread Class  The thread is available in the java.lang.Thread class. In order to make a thread, you need to extend a thread class and override the run method. For example,

public class Addition extends Thread {

public void run() {

}

}

A disadvantage of using the thread class is that it becomes impossible to extend any other classes. Nonetheless, it is possible to overload the run() method in the class

  • Implement Runnable Interface – Another way of making a thread in Java is by implementing a runnable interface. For doing so, there is the need to provide the implementation for the run() method that is defined in the

interface. For example,

public class Addition implements Runnable {

public void run() {

}

}

25. Why do we use the yield() method?

Answer: The yield() method belongs to the thread class. It transfers the currently running thread to a runnable state and also allows the other threads to execute. In other words, it gives equal priority threads a chance to run. Because yield() is a static method, it does not release any lock.

26. Can you explain the thread lifecycle in Java?

Answer: The thread lifecycle has the following states and follows the following order:

  • New – In the very first state of the thread lifecycle, the thread instance is created and the start() method is yet to be invoked. The thread is considered alive now.
  • Runnable – After invoking the start() method but before invoking the run() method, a thread is in the runnable state. A thread can also return to the runnable state from waiting or sleeping state.
  • Running – The thread enters the running state after the run() method is invoked. This is when the thread begins execution.
  • Non-Runnable – Although the thread is alive, it is not able to run. Typically, it returns to the runnable state after some time.
  • Terminated – The thread enters the terminated state once the run() method completes its execution. It is not alive now.

27. Take a look at the two code snippets below:

i.

class Adder {

Static int add(int a, int b)

{

return a+b;

}

Static double add( double a, double b)

{

return a+b;

}

public static void main(String args[])

{

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(12.3,12.6));

}}

ii.

class Car {

void run(){

System.out.println(“car is running”);

}

Class Audi extends Car{

void run()

{

System.out.prinltn(“Audi is running safely with 100km”);

}

public static void main( String args[])

{

Car b=new Audi();

b.run();

}

}

What is the important difference between the two?

Answer: Code snippet i. is an example of method overloading while the code snippet ii. demonstrates method overriding.

28. What do you understand by Synchronization in Java? What is its most significant disadvantage?

Answer: If several threads try to access a single block of code then there is an increased chance of producing inaccurate results. To prevent this, synchronization is used. Using the synchronization keyword makes a thread to need a key in order to access the synchronized code. Simply, synchronization allows only one thread to access a block of code at a time. Each Java object has a lock and every lock has only one key. A thread is able to access a synchronized method only if it can get the key to the lock of the object. Following example demonstrates synchronization:

public class ExampleThread implements Runnable {

public static void main (String[] args){

Thread t = new Thread();

t.start();

}

public void run(){

synchronized(object){

{

}

}

Note: It is recommended to avoid implementing synchronization for all methods. This is because when only one thread is able to access the synchronized code, the next thread needs to wait. Consequently, it results in slower performance of the program.

29. Is it possible to write multiple catch blocks under a single try block?

Answer: Yes, it is possible to write several catch blocks under a single try block. However, the approach needs to be from specific to general. Following example demonstrates the same:

public class Example {

public static void main(String args[]) {

try {

int a[]= new int[10];

a[10]= 10/0;

}

catch(ArithmeticException e)

{

System.out.println("Arithmetic exception in first catch block");

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Array index out of bounds in second catch block");

}

catch(Exception e)

{

System.out.println("Any exception in third catch block");

}

}

 

 

Oldest

ConversionConversion EmoticonEmoticon

:)
:(
=(
^_^
:D
=D
=)D
|o|
@@,
;)
:-bd
:-d
:p
:ng