100+ Most Important Java Interview Questions And Answers

By – HtmlCssMonk

100+ Most Important Java Interview Questions and Answers with examples.

In this tutorial, we have covered almost 100+ important core Java interview questions for freshers and experienced candidates.

This post on JAVA Interview Questions is prepared to help you understand the basic concepts of Java programming for interview purposes. All the important JAVA concepts are explained here with examples for your easy understanding.

Following is a list of JavaScript interview questions and answers, which are likely to be asked during the interview.

Also Try-Test your Skills with Amazing Quizzes.

Let’s get started.

1- What is Java?

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 are the features of JAVA?

Features of Java are as follows:

  • OOP concepts
    • Object-oriented
    • Inheritance
    • Encapsulation
    • Polymorphism
    • Abstraction
  • Platform independent: A single program works on different platforms without any modification.
  • High Performance: JIT (Just In Time compiler) enables high performance in Java. JIT converts the bytecode into machine language and then JVM starts the execution.
  • Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread which is called the main thread. The user can create multiple threads by extending the thread class or by implementing the Runnable interface.

3- Why Java is called platform independent?

Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying operating system.

4- What are the differences between C++ and Java?

Comparison IndexC++Java
Platform-independentC++ is platform-dependent.Java is platform-independent.
Mainly used forC++ is mainly used for system programming.Java is mainly used for application programming. It is widely used in window, web-based, enterprise and mobile applications.
Design GoalC++ was designed for systems and applications programming. It was an extension of C programming language.Java was designed and created as an interpreter for printing systems but later extended as a support network computing. It was designed with a goal of being easy to use and accessible to a broader audience.
GotoC++ supports the goto statement.Java doesn’t support the goto statement.
Multiple inheritanceC++ supports multiple inheritance.Java doesn’t support multiple inheritance through class. It can be achieved by interfaces in java.
Operator OverloadingC++ supports operator overloading.Java doesn’t support operator overloading.
PointersC++ supports pointers. You can write pointer program in C++.Java supports pointer internally. However, you can’t write the pointer program in java. It means java has restricted pointer support in Java.
Compiler and InterpreterC++ uses compiler only. C++ is compiled and run using the compiler which converts source code into machine code so, C++ is platform dependent.Java uses compiler and interpreter both. Java source code is converted into bytecode at compilation time. The interpreter executes this bytecode at runtime and produces output. Java is interpreted that is why it is platform independent.
Call by Value and Call by referenceC++ supports both call by value and call by reference.Java supports call by value only. There is no call by reference in java.
Structure and UnionC++ supports structures and unions.Java doesn’t support structures and unions.
Thread SupportC++ doesn’t have built-in support for threads. It relies on third-party libraries for thread support.Java has built-in thread support.
Documentation commentC++ doesn’t support documentation comment.Java supports documentation comment (/** … */) to create documentation for java source code.

5- How does Java enable high performance?

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. After that, the JVM calls the compiled code directly instead of interpreting it. This grants a performance boost.

6- Name the Java IDE’s?

Eclipse and NetBeans are the IDE’s of JAVA.

7- What are constructors in Java?

In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.

There are two types of constructors:

  • Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other words, default constructors are the no argument constructors which will be created by default in case you no other constructor is defined by the user. Its main purpose is to initialize the instance variables with the default values. Also, it is majorly used for object creation. 
  • Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable of initializing the instance variables with the provided values. In other words, the constructors which take the arguments are called parameterized constructors.

8- Why Java is not 100% Object-oriented?

Java is not 100% Object-oriented because it makes use of eight primitive data types such as boolean, byte, char, int, float, double, long, short which are not objects.

9- What are wrapper classes in Java?

Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the below image which displays different primitive type, wrapper class and constructor argument.

10- What is singleton class in Java and how can we make a class singleton?

Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.

11- What is the difference between an Inner Class and a Sub-Class?

An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.

A sub-class is a class which inherits from another class called super class. Sub-class can access all public and protected methods and fields of its super class.

12- What are the various access specifiers for Java classes?

In Java, access specifiers are the keywords used before a class name which defines the access scope. The types of access specifiers for classes are:

  • Public : Class, Method, Field is accessible from anywhere.
  • Protected: Method, Field can be accessed from the same class to which they belong or from the sub-classes and from the class of same package, but not from outside.
  • Default: Method, Field, class can be accessed only from the same package and not from outside of it’s native package.
  • Private: Method, Field can be accessed from the same class to which they belong.

13- Explain what are static methods and variables?

A class has two sections one declares variables, and other declares method, and these are called instance variables and instance methods, respectively. They are termed so because every time a class is instantiated, a new copy of each of them is created. 

Variables and methods can be created that are common to all objects and accessed without using a particular object by declaring them static. Static members are also available to be used by other classes and methods. 

14- What is data encapsulation and what’s its significance?

Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a single unit.

It helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independent of other objects. Encapsulation also serves data hiding purpose.

15- What are Loops in Java? What are three types of loops?

Looping is used in programming to execute a statement or a block of statement repeatedly. There are three types of loops in Java:

  • For Loops

These are used in java to execute statements repeatedly for a given number of times. For loops are used when number of times to execute the statements is known to programmer.

  • While Loops

While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In while loops, condition is checked first before execution of statements.

  • Do While Loops

Do While Loop is same as While loop with only difference that condition is checked after execution of block of statements. Hence in case of do while loop, statements are executed at least once.

16- What is the JIT compiler?

JIT compiler runs after the program is executed and compiles the code into a faster form, hosting CPU’s native instructing set. JIT can access dynamic runtime information, whereas a standard compiler doesn’t and can make better optimizations like inlining functions that are used frequently. 

17- Explain Typecasting.

The concept of assigning a variable of one data type to a variable of another data type. It is not possible for the boolean data type.

It is of two types:

  • Implicit
  • Explicit

18- What is Object-Oriented Programming? 

OOPs is a programming paradigm centred around objects rather than functions. It is not a tool or a programming language it is a paradigm that was designed to overcome the flaws of procedural programming. There are many languages that follow OOPs concepts, some popular ones are Java, Python, Ruby and more. Some frameworks also follow OOPs concepts, Angular is one such framework.

19- Could you explain the Oops concepts?

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

20- What is the difference between Array list and vector in Java?

Array List is not synchronized. Vector is synchronized.
Array List is fast as it’s non-synchronized.Vector is slow as it is thread safe.
If an element is inserted into the Array List, it increases its Array size by 50%.Vector defaults to doubling size of its array.
Array List does not define the increment size.Vector defines the increment size.
Array List can only use Iterator for traversing an Array List.Vector can use both Enumeration and Iterator for traversing.

21- What is the difference between equals() and == in Java?

Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.

“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.

22- What are the differences between Heap and Stack Memory in Java?

The major difference between Heap and Stack memory are:

MemoryStack memory is used only by one thread of execution.Heap memory is used by all the parts of the application.
AccessStack memory can’t be accessed by other threads.Objects stored in the heap are globally accessible.
Memory ManagementFollows LIFO manner to free memory.Memory management is based on the generation associated with each object.
LifetimeExists until the end of execution of the thread.Heap memory lives from the start till the end of application execution.
UsageStack memory only contains local primitive and reference variables to objects in heap space.Whenever an object is created, it’s always stored in the Heap space.

23- What is an infinite Loop? How infinite loop is declared?

An infinite loop runs without any condition and runs infinitely. An infinite loop can be broken by defining any breaking logic in the body of the statement blocks.

Infinite loop is declared as follows:

for (;;)
    // Statements to execute

    // Add any loop breaking logic

24- What is the difference between double and float variables in Java?

In java, float takes 4 bytes in memory while Double takes 8 bytes in memory. Float is single precision floating point decimal number while Double is double precision decimal number.

25- What is Final Keyword in Java? Give an example.

In java, a constant is declared using the keyword Final. Value can be assigned only once and after assignment, value of a constant can’t be changed.

In below example, a constant with the name const_val is declared and assigned a value:

Private Final int const_val=100

When a method is declared as final,it can NOT be overridden by the subclasses.This method are faster than any other method,because they are resolved at complied time.

When a class is declares as final, it cannot be subclassed. Example String, Integer and other wrapper classes.

26- Differentiate between break and continue.

Used with both loop and switch statementUsed with only loop statements.
It terminates the loop or switch block.It does not terminate but skips to the next iteration.

27- What is an Object?

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

28- Define classes in Java .

 class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language. 

Syntax of a class: 

class Sample{
member variables

Example of Class:

public class Shape
String Shape name;
void area()
void volume ()
void num_sides()

29- Please explain Method Overriding in Java?

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

  • The same name, argument and return type.

30- What do you mean by Overloading?

Overloading is the phenomenon when two or more different methods (method overloading) or operators (operator overloading) have 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.

31- What is a package in Java? List down various advantages of packages.

Packages in Java, are the collection of related classes and interfaces which are bundled together. By using packages, developers can easily modularize the code and optimize its reuse. Also, the code within the packages can be imported by other classes and reused. Below I have listed down a few of its advantages:

  • Packages help in avoiding name clashes
  • They provide easier access control on the code
  • Packages can also contain hidden classes which are not visible to the outer classes and only used within the package
  • Creates a proper hierarchical structure which makes it easier to locate the related classes

32- Why pointers are not used in Java?

Java doesn’t use pointers because they are unsafe and increases the complexity of the program. Since, Java is known for its simplicity of code, adding the concept of pointers will be contradicting. Moreover, since JVM is responsible for implicit memory allocation, thus in order to avoid direct access to memory by the user,  pointers are discouraged in Java.

33- What is JIT compiler in Java?

JIT stands for Just-In-Time compiler in Java. It is a program that helps in converting the Java bytecode into instructions that are sent directly to the processor. By default, the JIT compiler is enabled in Java and is activated whenever a Java method is invoked.

The JIT compiler then compiles the bytecode of the invoked method into native machine code, compiling it “just in time” to execute. Once the method has been compiled, the JVM summons the compiled code of that method directly rather than interpreting it. This is why it is often responsible for the performance optimization of Java applications at the run time.

34- What is ternary operator? Give an example.

Ternary operator , also called conditional operator is used to decide which value to assign to a variable based on a Boolean value evaluation. It’s denoted as ?

In the below example, if rank is 1, status is assigned a value of “Done” else “Pending”.

public class conditionTest {
    public static void main(String args[]) {
        String status;
        int rank = 3;
        status = (rank == 1) ? "Done" : "Pending";

35- How can you generate random numbers in Java?

There are 2 ways like –

  • Using Math.random() you can generate random numbers in the range greater than or equal to 0.1 and less than 1.0
  • Using Random class in package java.util

36- What is default switch case? Give example.

In a switch statement, default case is executed when no other switch condition matches. Default case is an optional case .It can be declared only once all other switch cases have been coded.

In the below example, when score is not 1 or 2, default case is used.

public class switchExample {
    int score = 4;
    public static void main(String args[]) {
        switch (score) {
            case 1:
                system.out.println("Score is 1");
            case 2:
                system.out.println("Score is 2");
                system.out.println("Default Case");

37- What’s the base class in Java from which all classes are derived?


38- Can main() method in Java can return any data?

In java, main() method can’t return any data and hence, it’s always declared with a void return type.

39- Differentiate between String, String Builder, and String Buffer.

Storage AreaConstant String PoolHeap AreaHeap Area
Thread SafetyYesNoYes
PerformanceFastMore efficientLess efficient

40- What is String Pool in Java?

The collection of strings stored in the heap memory refers to the String pool. Whenever a new object is created, it is checked if it is already present in the String pool or not. If it is already present, then the same reference is returned to the variable else new object is created in the String pool, and the respective reference is returned.

41- What do you know about Interface in Java?

A Java interface is a template that has only method declarations and not method implementations. It is a workaround for achieving multiple inheritances in Java. Some worth remembering important points regarding Java interfaces are:

  • A class that implements the interface must provide an implementation for all methods declared in the interface
  • All methods in an interface are internally public abstract void
  • All variables in an interface are internally public static final
  • Classes do not extend but implement interfaces

42- How is an Abstract class different from an Interface?

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.

43- What is multiple inheritance? Does Java support multiple inheritance? If not, how can it be achieved?

If a subclass or child class has two parent classes, that means it inherits the properties from two base classes, it is multiple inheritances. Java does not multiple inheritances as in case if the parent classes have the same method names, then at runtime, it becomes ambiguous, and the compiler is unable to decide which method to execute from the child class.

44- What are the main concepts of OOPs in Java?

Object-Oriented Programming or OOPs is a programming style that is associated with concepts like:

  1. Inheritance: Inheritance is a process where one class acquires the properties of another.
  2. Encapsulation: Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit.
  3. Abstraction: Abstraction is the methodology of hiding the implementation details from the user and only providing the functionality to the users. 
  4. Polymorphism: Polymorphism is the ability of a variable, function or object to take multiple forms.

45- Differentiate between the constructors and methods in Java?

1. Used to represent the behavior of an object1. Used to initialize the state of an object
2. Must have a return type2. Do not have any return type
3. Needs to be invoked explicitly3. Is invoked implicitly
4. No default method is provided by the compiler4. A default constructor is provided by the compiler if the class has none
5. Method name may or may not be same as class name5. Constructor name must always be the same as the class name

46- What is the difference between this() and super() in Java?

In Java, super() and this(), both are special keywords that are used to call the constructor. 

1. this() represents the current instance of a class1. super() represents the current instance of a parent/base class
2. Used to call the default constructor of the same class2. Used to call the default constructor of the parent/base class
3. Used to access methods of the current class3. Used to access methods of the base class
4.  Used for pointing the current class instance4. Used for pointing the superclass instance
5. Must be the first line of a block5. Must be the first line of a block

47- Differentiate between static and non-static methods in Java.

Static MethodNon-Static Method
1. The static keyword must be used before the method name1. No need to use the static keyword before the method name
2. It is called using the class (className.methodName) 2. It is can be called like any general method
3. They can’t access any non-static instance variables or methods3. It can access any static method and any static variable without creating an instance of the class

48- What is constructor chaining in Java?

In Java, constructor chaining is the process of calling one constructor from another with respect to the current object. Constructor chaining is possible only through legacy where a subclass constructor is responsible for invoking the superclass’ constructor first. There could be any number of classes in the constructor chain. Constructor chaining can be achieved in two ways:

  1. Within the same class using this()
  2. From base class using super()

49- What is a classloader in Java?

The Java ClassLoader is a subset of JVM (Java Virtual Machine) that is responsible for loading the class files. Whenever a Java program is executed it is first loaded by the classloader. Java provides three built-in classloaders:

  1. Bootstrap ClassLoader
  2. Extension ClassLoader
  3. System/Application ClassLoader

50- Does Importing a package imports its sub-packages as well in Java?

In java, when a package is imported, its sub-packages aren’t imported and developer needs to import them separately if required.

For example, if a developer imports a package university.*, all classes in the package named university are loaded but no classes from the sub-package are loaded. To load the classes from its sub-package ( say department), developer has to import it explicitly as follows:

Import university.department.*

51- Can we declare the main method of our class as private?

In java, main method must be public static in order to run any application correctly. If main method is declared as private, developer won’t get any compilation error however, it will not get executed and will give a runtime error.

52- How an object is serialized in java?

In java, to convert an object into byte stream by serialization, an interface with the name Serializable is implemented by the class. All objects of a class implementing serializable interface get serialized and their state is saved in byte stream.

53- When we should use serialization?

Serialization is used when data needs to be transmitted over the network. Using serialization, object’s state is saved and converted into byte stream .The byte stream is transferred over the network and the object is re-created at destination.

54- Why do we use the yield() method?

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.

55- Can you explain the thread lifecycle in Java?

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.

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

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.

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

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.

58- How will you distinguish processes from threads?

There are several fundamental differences between a process and a thread, stated as follows:

  • Definition – A process is an executing instance of a program whereas, a thread is a subset of a process.
  • Changes – A change made to the parent process doesn’t affect child processes. However, a change in the main thread can yield changes in the behavior of other threads of the same process.
  • Communication – While processes require inter-process communication for communicating with sibling processes, threads can directly communicate with other threads belonging to the same process.
  • Control – Processes are controlled by the operating system and can control only child processes. On the contrary, threads are controlled by the programmer and are capable of exercising control over threads of the same process to which they belong.
  • Dependence – Processes are independent entities while threads are dependent entities
  • Memory – Threads run in shared memory spaces, but processes run in separate memory spaces.

59- What is a Map in Java?

In Java, Map is an interface of Util package which maps unique keys to values. The Map interface is not a subset of the main Collection interface and thus it behaves little different from the other collection types. Below are a few of the characteristics of Map interface: 

  1. Map doesn’t contain duplicate keys.
  2. Each key can map at max one value.

60- What is Polymorphism?

Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more than one form. There are two types of polymorphism:

  1. Compile time polymorphism
  2. Run time polymorphism

Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.

61- What is runtime polymorphism or dynamic method dispatch?

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. Let’s take a look at the example below to understand it better.

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();    //upcasting;

62- What is abstraction in Java?

Abstraction refers to the quality of dealing with ideas rather than events. It basically deals with hiding the details and showing the essential things to the user. Thus you can say that abstraction in Java is the process of hiding the implementation details from the user and revealing only the functionality to them. Abstraction can be achieved in two ways:

  1. Abstract Classes (0-100% of abstraction can be achieved)
  2. Interfaces (100% of abstraction can be achieved)

63- What are the different types of inheritance in Java?

Java supports four types of inheritance which are:

  1. Single Inheritance: In single inheritance, one class inherits the properties of another i.e there will be only one parent as well as one child class.
  2. Multilevel Inheritance: When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance.
  3. Hierarchical Inheritance: When a class has more than one child classes (subclasses) or in other words, more than one child classes have the same parent class, then such kind of inheritance is known as hierarchical.
  4. Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance.

64- What is method overloading and method overriding?

Method Overloading :

  • In Method Overloading, Methods of the same class shares the same name but each method must have a different number of parameters or parameters having different types and order.
  • Method Overloading is to “add” or “extend” more to the method’s behavior.
  • It is a compile-time polymorphism.
  • The methods must have a different signature.
  • It may or may not need inheritance in Method Overloading.

Method Overriding:  

  • In Method Overriding, the subclass has the same method with the same name and exactly the same number and type of parameters and same return type as a superclass.
  • Method Overriding is to “Change” existing behavior of the method.
  • It is a run time polymorphism.
  • The methods must have the same signature.
  • It always requires inheritance in Method Overriding.

65- Is it compulsory for a Try Block to be followed by a Catch Block in Java for Exception handling?

Try block needs to be followed by either Catch block or Finally block or both. Any exception thrown from try block needs to be either caught in the catch block or else any specific tasks to be performed before code abortion are put in the Finally block.

66- Is there any way to skip Finally block of exception even if some exception occurs in the exception block?

If an exception is raised in Try block, control passes to catch block if it exists otherwise to finally block. Finally block is always executed when an exception occurs and the only way to avoid execution of any statements in Finally block is by aborting the code forcibly by writing following line of code at the end of try block:


67- Can a class have multiple constructors?

Yes, a class can have multiple constructors with different parameters. Which constructor gets used for object creation depends on the arguments passed while creating the objects.

68- Can we override static methods of a class?

We cannot override static methods. Static methods belong to a class and not to individual objects and are resolved at the time of compilation (not at runtime).Even if we try to override static method,we will not get an complitaion error,nor the impact of overriding when running the code.

69- Is String a data type in java?

String is not a primitive data type in java. When a string is created in java, it’s actually an object of Java.Lang.String class that gets created. After creation of this string object, all built-in methods of String class can be used on the string object.

70- Why Strings in Java are called as Immutable?

In java, string objects are called immutable as once value has been assigned to a string, it can’t be changed and if changed, a new object is created.

In below example, reference str refers to a string object having value “Value one”.

String str="Value One";

When a new value is assigned to it, a new String object gets created and the reference is moved to the new object.

str="New Value";

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

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){
public void add() throws Exception{

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) {
public void add(){
catch(Exception e)

72- Is it possible to write multiple catch blocks under a single try block?

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");

73- How does the throw keyword differ from the throws keyword?

While the throws keyword allows declaring an exception, the throw keyword is used to explicitly throw an exception. Checked exceptions can’t be propagated with throw only, but throws allow doing so without the need for anything else. The throws keyword is followed by a class, whereas the throw keyword is followed by an instance. The throw keyword is used within the method, but the throws keyword is used with the method signature. Furthermore, it is not possible to throw multiple exceptions, but it is possible to declare multiple exceptions.

74- Explain various exceptions handling keywords in Java?

There is two crucial exception handling keywords in Java, followed by the third keyword final, which may or may not be used after handling exceptions.


If and when a code segment has chances of having and abnormality or an error, it is placed within a try block. When the exception is raised, it is handled and caught by the catch block.

Try block must have a catch() or a final() or both blocks after it.


When an exception is raised in the try block, it is handled in the catch block.


This block is executed regardless of the exception. It can be placed either after try{} or catch {} block.

75- Does an empty file name with .java extension a valid file name?

Yes, Java permits to save our java file by .java only. It is compiled by javac .java and run by java class name.

Let’s take a simple example:

public class Any()
public static void main(String args[])
System.out.println("Hello Java File here!");

To compile:

To run: Java Any

76- What do you mean by Collections in Java? What are the constituents of Collections in Java?

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

77- How will you differentiate HashMap from HashTable?

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.

78- Please explain Map and their types in Java.

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.

79- What is an association?

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take the example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. These relationships can be one to one, one to many, many to one and many to many.

80- What do you mean by aggregation?

An aggregation is a specialized form of Association where all object has their own lifecycle but there is ownership and child object can not belong to another parent object. Let’s take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department teacher object will not destroy.

81- What is composition in Java?

Composition is again a specialized form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of a relationship between House and rooms.

House can contain multiple rooms there is no independent life of room and any room can not belongs to two different houses if we delete the house room will automatically delete.

82- What’s the difference between an array and Vector?

An array groups data of same primitive type and is static in nature while vectors are dynamic in nature and can hold data of different data types.

83- Why Runnable Interface is used in Java?

Runnable interface is used in java for implementing multi threaded applications. Java.Lang. Runnable interface is implemented by a class to support multi threading.

84- How garbage collection is done in Java?

In java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection java calls either System.gc() method or Runtime.gc() method.

85- How we can execute any code even before main method?

If we want to execute any statements before even creation of objects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before creation of objects in the main method.

86- How objects of a class are created if no constructor is defined in the class?

Even if no explicit constructor is defined in a java class, objects get created successfully as a default constructor is implicitly used for object creation. This constructor has no parameters.

87- How can we make copy of a java object?

We can use the concept of cloning to create copy of an object. Using clone, we create copies with the actual state of an object.

Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies.

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

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 how 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.

89- What is ordered and sorted concerning collections?

  1. Ordered

It means that values are stored in a collection in a specific order, but the order is independent of the value.

Eg. List

  1. Sorted

It means the collection has an order which is dependent on the value of an element.

Eg. SortedSet

90- Can you tell the difference between execute(), executeQuery(), and executeUpdate()?

  • execute() – Used for executing an SQL query. It returns TRUE if the result is a ResultSet, like running Select queries, and FALSE if the result is not a ResultSet, such as running an Insert or an Update query.
  • executeQuery() – Used for executing Select queries. It returns the ResultSet, which is not null, even if no records are matching the query. The executeQuery() method must be used when executing select queries so that it throws the java.sql.SQLException with the ‘executeQuery method cannot be used for update’ message when someone tries to execute an Insert or Update statement.
  • executeUpdate() – Used for executing Delete/Insert/Update statement or DDL statements that returns nothing. The output varies depending on whether the statements are Data Manipulation Language (DML) statements or Data Definition Language (DDL) statements. The output is an integer and equals the total row count for the former case, and 0 for the latter case.

91- Please compare Serialization with Deserialization in Java.

Serialization is the process by which Java objects are converted into the byte stream. Deserialization is the exact opposite process of serialization where Java objects are retrieved from the byte stream. A Java object is serialized by writing it to an ObjectOutputStream and deserialized by reading it from an ObjectInputStream.

92- What are the differences between Get and Post methods?

Limited amount of data can be sent because data is sent in header.Large amount of data can be sent because data is sent in body.
 Not Secured because data is exposed in URL bar. Secured because data is not exposed in URL bar.
 Can be bookmarked Cannot be bookmarked
 Idempotent Non-Idempotent
 It is more efficient and used than Post It is less efficient and used

93- How does cookies work in Servlets?

  • Cookies are text data sent by server to the client and it gets saved at the client local machine.
  • Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.
  • HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.
  • Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

94- What are the differences between ServletContext vs ServletConfig?

The difference between ServletContext and ServletConfig in Servlets JSP is in below tabular format.

Servlet config object represent single servletIt represent whole web application running on particular JVM and common for all the servlet
Its like local parameter associated with particular servletIts like global parameter associated with whole application
It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scopeServletContext has application wide scope so define outside of servlet tag in web.xml file.
getServletConfig() method is used to get the config objectgetServletContext() method is  used to get the context object.
for example shopping cart of a user is a specific to particular user so here we can use servlet configTo get the MIME type of a file or application session related information is stored using servlet context object.

95- What is JDBC Driver?

JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:

  1. JDBC-ODBC bridge driver
  2. Native-API driver (partially java driver)
  3. Network Protocol driver (fully java driver)
  4. Thin driver (fully java driver)

96- What are the steps to connect to a database in java?

  • Registering the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection

97- What are the JDBC API components?

The java.sql package contains interfaces and classes for JDBC API.


  • Connection
  • Statement
  • PreparedStatement
  • ResultSet
  • ResultSetMetaData
  • DatabaseMetaData
  • CallableStatement etc.


  • DriverManager
  • Blob
  • Clob
  • Types
  • SQLException etc.

98- What will be the output of Round(3.7) and Ceil(3.7)?

Round(3.7) returns 4 and Ceil(3.7) returns 4.

99- Can we use goto in Java to go to a particular line?

In Java, there is not goto keyword and java doesn’t support this feature of going to a particular labeled line.

100- Is JDK required on each machine to run a Java program?

JDK is development Kit of Java and is required for development only and to run a Java program on a machine, JDK isn’t required. Only JRE is required.

101- How are destructors defined in Java?

In Java, there are no destructors defined in the class as there is no need to do so. Java has its own garbage collection mechanism which does the job automatically by destroying the objects when no longer referenced.

102- What are wrapper classes in Java?

Wrapper classes are responsible for converting the Java primitives into the reference types (objects). A class is dedicated to every primitive data type. They are known as wrapper classes because they wrap the primitive data type into an object of that class. It is present in Java.lang package. The table below displays the different primitive types, wrapper class.

Simple TypeWrapper Class

103- Explain the concept of boxing, unboxing, autoboxing, and auto unboxing.

  • Boxing: The concept of putting a primitive value inside an object is called boxing.
  • Unboxing: Getting the primitive value from the object.
  • Autoboxing: Assigning a value directly to an integer object.
  • Auto unboxing: Getting the primitive value directly into the integer object.
public class BoxUnbox
public static void main(String args[])
int i = 5;
Integer ii = new Integer(i);            /*Boxing*/
Integer jj = i; /*Unboxing*/
int j = jj.intValue();      /*Unboxing*/
int k = jj; /*AutoUnboxing*/

104- Which API is provided by Java for operations on set of objects?

Java provides a Collection API which provides many useful methods which can be applied on a set of objects. Some of the important classes provided by Collection API include ArrayList, HashMap, TreeSet and TreeMap.

105- Can we cast any other type to Boolean Type with type casting?

No, we can neither cast any other primitive type to Boolean data type nor can cast Boolean data type to any other primitive data type.

Start learning HTMLCSS and JavaScript.

Test your skills with Amazing Quizzes.

Also Read :

Leave a Comment

Your email address will not be published. Required fields are marked *