Java Interview Questions

By YuwebDesign

Java Core Interview Questions

  1. Java is a high-level programming language.
  2. Java is platform independent.
  3. Java is a statically typed language.
  4. Java is a collection of objects.
  5. It was developed by Sun Microsystems.
  6. There are a lot of applications, websites and Games that are developed using Java.

Java is statically typed – variables are given data types up front (before compiling).
In dynamically typed languages variables do not have types.

stands for Java Development Kit stands for Java Runtime Environment stands for Java Virtual Machine
It is the tool necessary to compile, document and package Java programs. JRE refers to a runtime environment in which Java bytecode can be executed. It is an abstract machine. It is a specification that provides a run-time environment in which Java bytecode can be executed.
It contains JRE + development tools. It’s an implementation of the JVM which physically exists. JVM follows three notations: Specification, Implementation, and Runtime Instance.

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.

  1. By default, the JIT compiler is enabled in Java and is activated whenever a Java method is invoked.
  2. The JIT compiler then compiles the bytecode of the invoked method into native machine code.
  3. Jit compiles it “just in time” to execute.
  4. Once the method has been compiled, the JVM summons the compiled code of that method directly rather than interpreting it.
  5. This is why it is often responsible for the performance optimization of Java applications at the run time.

main() in Java is the entry point for any Java program.
It is always written as public static void main(String[] args).

  1. public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
  2. static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class.
  3. void: It is the return type of the method. Void defines the method which will not return any value.
  4. main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
  5. String args[]: It is the parameter passed to the main method.

  1. Platform independence means that execution of the program does not depend on type of operating system.
    It could be any: Linux, Windows, Mac etc.
  2. Java is both compiler(javac) and interpreter(jvm) based lauguage.
  3. Your java source code is first compiled into byte code using javac compiler.
  4. This byte code can be easily converted to equivalent machine code using JVM.
  5. JVM(Java Virtual Machine) is available in all operating systems we install.
  6. Hence, byte code generated by javac is universal and can be converted to machine code on any operating system.
    This is the reason why Java is platform independent.

  1. Object-oriented Language following OOPs concepts:
    1. Inheritance
    2. Encapsulation
    3. Polymorphism
    4. Abstraction
  2. Platform independent: A single program works on different platforms without any modification.
  3. 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.
  4. Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread which is called main thread. The user can create multiple threads by extending the thread class or by implementing Runnable interface.

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.

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.

Java uses Just In Time compiler to enable high performance. JIT is used to convert the instructions into bytecodes.

A class in Java is a blueprint which includes all your data.

  1. All Java programming code is defined within a class. A Class has variables and methods.
  2. Variables are attributes which define the state of a class.
  3. Member variable, instance variable, and field are different words that mean the same thing. Field is the preferred term in Java.
  4. Methods define the behavior and are the place where the exact business logic has to be done. It contains a set of statements (or) instructions to satisfy the particular requirement.

Syntax of a class:

class Abc {
member variables // class body

Read moore about Classes 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

  1. Object is an instance of a class.
  2. An object is a real-world entity that has a state and behavior.
  3. An object has three characteristics:
    • State
    • Behavior
    • Identity
  4. An object is created using the ‘new’ keyword.
    ClassName obj = new ClassName();

    Whenever the JVM reads the “new()” keyword, it will create an instance of that class.

Read more about Objects in Java >>>

Object Cloning in Java
  1. Object cloning in Java is the process of creating an exact copy of an object.
  2. It basically means the ability to create an object with a similar state as the original object.
  3. To achieve this, Java provides a method clone() to make use of this functionality.
  4. This method creates a new instance of the class of the current object and then initializes all its fields with the exact same contents of corresponding fields.
  5. To object clone(), the marker interface java.lang.Cloneable must be implemented to avoid any runtime exceptions.
  6. One thing you must note is Object clone() is a protected method, thus you need to override it.

The technical term for a class/method/object or variable name is an identifier.

IntelliJ and Eclipse are the most popular IDE’s for Java, NetBeans was also widely used in the past and still is the IDE of choice in some companies.

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.

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

Read more about the package structure in Java >>>

  1. Constructor refers to a block of code which is used to initialize an object.
  2. When a new object is created in a program a constructor gets invoked corresponding to the class.
  3. Constructor must have the same name as the class name.
  4. Constructor has no return type and it is automatically called when an object is created.
  5. There are two types of constructors: Default Constructor and Parameterized Constructor.
    Read more about Default vs Parameterized constructors >>>
  6. Constructor can be overloaded.
    If the user created a constructor with a parameter then he should create another constructor explicitly without a parameter.

Read more about Constructors in Java >>>

Copy Constructor in Java
  1. Copy constructor is a member function that is used to initialize an object using another object of the same class.
  2. Though there is no need for copy constructor in Java since all objects are passed by reference.
  3. Moreover, Java does not even support automatic pass-by-value.

  1. Constructor chaining is the process of calling one constructor from another with respect to the current object.
  2. Constructor chaining is possible only through legacy
    where a subclass constructor is responsible for invoking the superclass’ constructor first.
  3. 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()

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.

break continue
Usage In switch and loop (for, while, do while) statements Only in loop statements
Causes the switch or loop statements to terminate the moment it is executed Doesn’t terminate the loop but causes the loop to jump to the next loop iteration
for (int i = 0; i < 5; i++) 
if (i == 3)
for (int i = 0; i < 5; i++)
if(i == 2)

  1. An infinite loop is an instruction sequence in Java
    that loops endlessly when a functional exit isn’t met.
  2. This type of loop can be the result of a programming error
    or may also be a deliberate action based on the application behavior.
  3. An infinite loop will terminate automatically once the application exits.
public class InfiniteForLoop {
public static void main(String[] arg) {
System.out.println("Welcome to the Neverending Story!");

Java Operators Interview Questions

Operator works on operands to produce a value.
Operators make the expression possible

Operand - the thing operator works on.

In expression 5 + 3,
5 and 3 are operators,
"+" is an operand.
When the expression is evaluated it will return a value of "8".

Java divides the operators into the following groups:
  1. Arithmetic operators
  2. Assignment operators
  3. Comparison operators
  4. Logical operators
  5. Bitwise operators

Expression evaluates to a value, e.g.,

String myString = new String("Hello World!")
System.out.println(string + "How are you")
//everything within () is an expression

Equals() method is defined in Object class in Java.
It is 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.
It is 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.

Java Variables and Variable Datatypes Interview Questions

  1. Local variable is defined within the method and scope of the variables is within the block.
  2. Instance variable is defined inside the class and outside the method, scope is bound to the instance of the object it is created with and is destroyed when the object is destroyed.
  3. Read more about Local vs Instance Variable 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.

In heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called String Constant Pool.

Whenever you create a string object using string literal, that object is stored in the string constant pool and whenever you create a string object using new keyword, such object is stored in the heap memory.

String pool space is allocated to an object depending upon it’s content.
There will be no two objects in the string pool having the same content.
But there can be two string objects with the same content in the heap memory.

Whenever a String object is created,
String pool first checks whether the object whether same content is already present in the pool.
If present, no new object is created, and same reference gets returned,
otherwise new object will be created in the String Pool and the respective reference will be returned.

However, when you create string objects using new keyword, a new object is created whether the content is same or not.

Once the string reference changes the old value that exists in the “constant string pool”, it cannot be erased.

E.g., String name = “book”;

Constant string pool:
constant string pool in Java

E.g., If name value has changed from “book” to “pen”,
the older value retains in the constant string pool.

Constant string pool:
changed string value in constant string pool in Java

  1. In Java, string objects are immutable in nature which simply means once the String object is created its state cannot be modified.
  2. Whenever you try to update the value of that object instead of updating the values of that particular object, Java creates a new string object.
  3. Java String objects are immutable as String objects are generally cached in the String pool.
  4. Since String literals are usually shared between multiple clients, action from one client might affect the rest.
  5. Immutability enhances security, caching, synchronization, and performance of the application.

String String Builder String Buffer
Storage Constant String Pool (Heap) Heap Heap
Mutability Immutable Mutable
(If the values are changed then the new value replaces the older value.)
(E.g., String Buffer name =”book”;
Once the name value has been changed to “pen” then the “book” is erased in the stack.)
Thread Safety Yes Yes
(synchronized which is thread-safe)
(not synchronized)
Performance Fast Slow Fast

Java Memory Management Interview Questions

In Java, all objects are dynamically allocated on Heap.

This is different from C++ where objects can be allocated memory either on Stack or on Heap.
In C++, when using "new()" keyword, the object is allocated on Heap, otherwise on Stack if not global or static.

In Java, when we only declare a variable of a class type,
only a reference is created (memory is not allocated for the object).
To allocate memory to an object, we must use new().

Stack Heap
Used only by one thread of execution. Used by all the parts of the application.
Can’t be accessed by other threads. Globally accessible.
Follows LIFO manner to free memory. Memory management is based on the generation associated with each object.
Exists until the end of execution of the thread. Lives from the start till the end of application execution.
Contains only local primitive and reference variables to objects in heap space. Whenever an object is created, it’s always stored in the Heap space.

Read more about Stack vs. Heap >>>

  1. Garbage collection in Java is a program which helps in implicit memory management.
  2. Using the new keyword, you can create objects dynamically.
    Once created, they will consume some memory.
  3. Once the job is done and there are no more references left to the object, Java using garbage collection destroys the object and relieves the memory occupied by it.

Java provides four types of Garbage Collectors:

  1. Serial Garbage Collector
  2. Parallel Garbage Collector
  3. CMS Garbage Collector
  4. G1 Garbage Collector

Java Keywords Interview Questions

Static Method Non-Static Method
Static keyword must be used before the method name No static keyword
Called as className.methodName Called like any general method
Can’t access any non-static instance variables or methods Can access any static method and any static variable without creating an instance of the class

Methods and instance variables are known as members.


Public members are visible in the same package as well as the outside package that is for other packages.
Public Access Modifier in Java
Public members in Class A are visible to Class B (Same package) as well as Class C (Different package).
Read more about Public Access Modifier in Java >>>


Private members are visible in the same class only and not for the other classes in the same package as well as classes in the outside packages.
Private Access Modifier in Java
Private members in class A is visible only in that class. It is invisible for class B as well as class C.

Read more about Private Modifier in Java >>>


Methods and variables declared in a class without any access specifiers are called default.

Default  Acccess Modifier  Java

Default members in Class A are visible to the other classes which are inside the package and invisible to the classes which are outside the package.

So Class A members are visible to the Class B and invisible to the Class C.

Read more about Default Access Modifier in Java >>>


Protected Access Modifier in Java

Protected is same as Default but if a class extends then it is visible even if it is outside the package.

Class A members are visible to Class B because it is inside the package. For Class C it is invisible but if Class C extends Class A then the members are visible to the Class C even if it is outside the package.

Read more about Protected Access Modifier in Java >>>

  1. Keyword "super" is a reference variable that is used to refer parent class objects.
  2. The keyword “super” came into the picture with the concept of Inheritance.

Keyword "super" is used to refer:

  1. Immediate parent class variable

    When a derived class and base class has same data members,
    the use of keyword "super" helps to avoid a possibility of ambiguity for the JVM.

  2. Immediate parent class method

    When parent and child classes have the same method names,
    the use of keyword "super" helps to resolve ambiguity.

  3. Immediate parent class constructor

    Keyword "super" can be used to access the parent class constructor.
    Keyword "super" can call both parametric and non-parametric constructors depending on the situation.

    Important points:

    1. Call to super() must be first statement in derived class constructor.
    2. If a constructor does not explicitly invoke a Superclass constructor,
      the Java compiler automatically inserts a call to the no-argument constructor of the Superclass.

      If the Superclass does not have a no-argument constructor, you will get a compile-time error.
      Object does have such a constructor, so if Object is the only Superclass, there is no problem.

    3. If a subclass constructor invokes a constructor of its Superclass, either explicitly or implicitly,
      the whole chain of constructors gets called, all the way back to the constructor of Object.
      This is called constructor chaining.

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

this() super()
Represents current instance of a class current instance of a parent/base class
Calls default constructor of the same class default constructor of the parent/base class
Accesses Methods of the current class Methods of the base class
Points to Current class instance Superclass instance
a block

"Final" is a special keyword in Java that is used as a non-access modifier.

Final variable Final method Final class
Creates constant variable
  • The value of a final variable can’t be changed once assigned.
  • When a final variable is a reference to an object, then this final variable is called reference final variable.
    Internal state of the object pointed by the reference variable can be changed.
    This is not re-assigning. This property of final is called non-transitivity.

    Arrays are objects in java. Arrays with final keyword are also called final arrays.
    You can add or remove elements from final array or final collection.

  • It is good practice to represent final variables in all uppercase, using underscore to separate words.
  • Final variable must be initialized, otherwise compiler will throw compile-time error.
    1. You can initialize a final variable when it is declared.
      This approach is the most common.

      When a final variable is created inside a method/constructor/block, it is called local final variable.
      It must be initialized when declared.

    2. A final variable is called blank final variable, if it is not initialized while declaration.

      It can be initialized inside instance-initializer block or inside constructor.

      If you have more than one constructor in your class then it must be initialized in all of them,
      otherwise compile time error will be thrown.

    3. A blank final static variable can be initialized inside static block.
  • Prevents Method Overriding
    A final method can’t be overridden by the subclass.

    Prevents Inheritance

    1. A final class can’t be extended by any subclass class
      but it can extend other classes.

      E.g., all Wrapper Classes like Integer, Float etc. are final classes. We can not extend them.

    2. The other use of final with classes is to create an immutable class, e.g., predefined String class.

      Immutable class means that once an object is created, its content can not be changed.
      You can not make a class immutable without making it final.

    Read more on GeeksForGeeks >>>

    Final Finally Finalize
    1. Final is used to apply restrictions on class, method, and variable.
    2. A final class can’t be inherited,
      final method can’t be overridden
      and final variable value can’t be changed.
    1. The finally keyword is used in association with a try/catch block.
      It can be used:

      1. When exceptions do not occur in the program,
        Finally guarantees that a section of code will be executed,
        even if an exception is thrown.
      2. Exception occurs and corresponding catch block matches.
        Finally executes whether exception occurs or not
        or whether corresponding catch block found or not.
      3. Exception occurs and corresponding catch block is not found
    2. The finally block will be executed after the try and catch blocks,
      but before control transfers back to its origin.
    3. Application of finally block: resource deallocation.
      All the resources opened in try block (Network Connections, Database Connections)
      need to be closed in finally block.
      This ensures that we won’t lose our resources as opened.
    1. Finalize is not a reserved keyword.
      It is a method that the Garbage Collector always calls just before the object is garbage collected to perform clean-up activity.
    2. Clean-up activity means closing the resources associated with that object
      e.g., Database Connection, Network Connection or we can say resource de-allocation.
    3. Once finalize method completes, Garbage Collector destroys that object.
    4. Finalize method belongs to the Object class, which is Superclass of all Java classes.
      Since it is available for all Java classes, Garbage Collector can call finalize method on any Java object.
    5. Syntax:
      protected void finalize throws Throwable{}

      Since Object class contains finalize method hence
      Finalize method has empty implementation and has to be overriden to define custom clean-up activities.

    6. There is no guarantee about the time when finalize is called.
      It may be called any time after the object is not being referred anywhere (cab be garbage collected).
      System.gc() is just a request to JVM to execute the Garbage Collector.
      It’s up-to JVM to call Garbage Collector or not.
      Usually JVM calls Garbage Collector when there is not enough space available in the Heap area or when the memory is low.
    7. JVM does not ignore all exceptions while executing finalize method,
      but it ignores only Unchecked exceptions.
      If the corresponding catch block is there then JVM won’t ignore
      and corresponding catch block will be executed.
    Final Finally Finalize
    class FinalVarExample {
    public static void main( String args[]){
    final int a=10;   // Final variable
    a=50;             //Error as value can't be changed
    class FinallyExample {
    public static void main(String args[]){
    try {
    int x=100;
    catch(Exception e) {
    finally {
    System.out.println("finally block is executing");}
    class FinalizeExample {
    public void finalize() {
    System.out.println("Finalize is called");
    public static void main(String args[])
    FinalizeExample f1=new FinalizeExample();
    FinalizeExample f2=new FinalizeExample();
    f1= NULL;

    In java, you will never see a class or method declared with both final and abstract keywords.

    Abstract Final
    For classes final is used to prevent inheritance abstract classes depend upon their child classes for complete implementation
    For methods final is used to prevent overriding abstract methods need to be overridden in sub-classes

    Java OOPs Interview Questions

    OOPS is an acronym that stands for

    1. Object
    2. Oriented
    3. Programming
    4. Systems

    Object-oriented programming is a programming model or approach
    where the programs are organized around objects rather than logic and functions.

    In other words, OOP mainly focuses on the objects that are required to be manipulated instead of logic.

    This approach is ideal for the program with large and complex code that needs to be actively updated or maintained.

    Four Pillars of OOPs


    1. Inheritance
    2. Encapsulation
    3. Polymorphism
    4. Abstraction

    Read more about OOPs concepts in Java >>>

    1. Polymorphism comes from the Greek roots "poly" (many) and "morphe" (form).
    2. Polymorphism can be described as “one interface, many implementations”.
    3. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts
    4. It is is the ability that allows an entity (such as a variable, a function, or an object)
      to take multiple forms.
    5. A single object can refer the super class or sub-class depending on the reference type.

      Read more about Polymorphism in Java >>>

    6. Run-time Polymorphism is applicable for overriding and Compile-time Polymorphism for overloading.

      Read more about Method Overriding in Java >>>

      Read more about Method Overloading in Java >>>

    1. Abstraction deals with (conceptual, abstract) ideas rather than (specific, concrete) events.
    2. Abstraction is the methodology of hiding the implementation details from the user and revealing only the functionality to them.

    Read more about Abstraction in Java >>>

    We can create the Abstract class by using “Abstract” keyword before the class name. An abstract class can have both “Abstract” methods and “Non-abstract” methods that are a concrete class.

    Abstract method

    The method which has only the declaration and not the implementation is called the abstract method and it has the keyword called “abstract”. Declarations are the ends with a semicolon.

    Non-abstract method

    An abstract class may have a non-abstract method also.
    The concrete Subclass which extends the Abstract class should provide the implementation for abstract methods.

    1. An interface is a template/blueprint of a class, which has only method declarations and not the method implementation.
    2. It is a collection of abstract methods and static constants.
      In an interface, each method is public and abstract but it does not contain any constructor.
      Thus, interface basically is a group of related methods with empty bodies.
    3. Multiple inheritance cannot be achieved in Java.
      However, Interface concept can be used to overcome this problem.
    public interface Animal {
      public void eat();
      public void sleep();
      public void run();

    Marker Interface

    A Marker interface can be defined as the interface having no data member and member functions.
    In simpler terms, an empty interface is called the Marker interface.
    The most common examples of Marker interface in Java are Serializable, Cloneable etc.
    The marker interface can be declared as follows.

    public interface Serializable{

    Method overriding happens if the sub class method satisfies the below conditions with the Super class method:

    1. Method name should be the same
    2. Argument should be the same
    3. Return type should be the same

    The key benefit of overriding is that the Sub class can provide some specific information about that sub class type while extending the super class.

    Read more about Method Overriding in Java >>>

    Method overloading happens for different classes or within the same class.

    For method overloading, subclass method should satisfy the below conditions with the Super class method (or) methods in the same class itself:

    1. Same method name
    2. Different argument type
    3. May have different return types

    Read more about Method Overloading in Java >>>

    Constructor Overloading in Java

    In Java, constructor overloading is a technique of adding any number of constructors to a class each having a different parameter list. The compiler uses the number of parameters and their types in the list to differentiate the overloaded constructors.

    class Demo {
    int i;
    public Demo(int a) {
    public Demo(int a, int b){

    If you create a similar Method within the Child Class
    with the same return type and same method arguments
    then it will hide the Super Class Method;
    this is known as Method Hiding.

    Read more about overriding the static Method >>>

    Similarly, you cannot override a private method in Subclass
    because it’s not accessible there.

    What you can do is create another private method with the same name in the child class:

    class Base {
    private static void display() {
    System.out.println("Static or class method from Base");
    public void print() {
    System.out.println("Non-static or instance method from Base");
    class Derived extends Base {
    private static void display() {
    System.out.println("Static or class method from Derived");
    public void print() {
    System.out.println("Non-static or instance method from Derived");
    public class test {
    public static void main(String args[])
    Base obj= new Derived();

    Java Collection Interview Questions

    1. A group of objects is known as a collection.
    2. In Java, Collection is a framework that acts as an architecture for storing and manipulating a group of objects.
    3. All the classes and interfaces for collecting are available in java.util package.
    4. Collections are used to perform the following operations:
      1. Searching
      2. Sorting
      3. Manipulation
      4. Insertion
      5. Deletion
    5. Java Collection framework includes:
      1. Interfaces
      2. Classes
      3. Methods

    1. Collection
    2. List
    3. Set
    4. Map
    5. Sorted Set
    6. Sorted Map
    7. Queue
    Lists Sets Maps Queue
    1. Array List
    2. Vector
    3. Linked List
    1. Hash set
    2. Linked Hash Set
    3. Tree Set
    1. Hash Map
    2. Hash Table
    3. Tree Map
    4. Linked Hashed Map
    Priority Queue
    Java Collection Framework Architecture Hierarchy

    Java Collection Framework Architecture Hierarchy


    It means the values that are stored in a collection is based on the values that are added to the collection. So we can iterate the values from the collection in a specific order.


    Sorting mechanism can be applied internally or externally so that the group of objects sorted in a particular collection is based on properties of the objects.

    In Java, Map is an interface of Util package.
    It maps a unique key to a specific value as a key/value pair.
    We can search a value, based on the key.

    Like Set, Map also uses “equals ( )” method to determine whether two keys are same or different.

    The Map interface is not a subset of the main Collection interface
    and thus it behaves little different from the other collection types.

    Characteristics of Map interface:

    1. Map doesn’t contain duplicate keys.
    2. Each key can map at max one value.
    Hash Map
    1. Doesn’t maintain any insertion order
    2. Unordered and unsorted map.
    3. Hashmap is a good choice when we don’t care about the order.
    4. It allows one null key and multiple null values.
    5. Duplicate keys are not allowed in Map.
    Hash Table
    1. Like vector key, methods of the class are synchronized.
    2. Thread safety and therefore slows the performance.
    3. Doesn’t allow anything that is null.
    4. Duplicate keys are not allowed.
    Linked Hash Map
    1. Maintains insertion order.
    2. Slower than Hash map.
    3. Can expect a faster iteration.
    4. Duplicate keys are not allowed.
    1. Sorted Map.
    2. Like Tree set, we can construct a sort order with the constructor.
    3. It is sorted in ascending order based on the key. Duplicate keys are not allowed.

    Array Array List
    Methods are not synchronized Key methods are synchronized
    Not thread safety Thread safety
    Iterator is used to iterate the values Enumerator is used to iterate the values
    Allows one null key and multiple null values Doesn’t allow anything that is null
    Performance is higher than of HashTable Performance is slow

    Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method is used to determine whether two objects are identical or not.

    Hash Set
    1. Unordered and unsorted.
    2. Doesn’t follow any insertion order.
    3. Uses the hash code of the object to insert the values.
    4. Duplicates are not allowed.
    5. Use this when the requirement is “no duplicates and don’t care about the order”.
    Linked Hash set
    1. An ordered version of the hash set is known as Linked Hash Set.
    2. Maintains a doubly-Linked list of all the elements.
    3. Maintains the insertion order in which they have been added to the Set.
    4. Use this when the iteration order is required.
    5. Duplicates are not allowed.
    Tree Set
    1. It is one of the two sorted collections.
    2. TreeSet sorts the elements in an ascending order.
    3. Uses “Read-Black” tree structure and guarantees that the elements will be in an ascending order.
    4. We can construct a tree set with the constructor by using comparable (or) comparator.

    HashSet TreeSet
    Inserted elements are in random order Maintains the elements in the sorted order
    Can store null objects Cannot store null objects
    Performance is fast Performance is slow

    Values added to the list is based on the index position and it is ordered by index position. Duplicates are allowed.

    Array List
    1. Fast iteration and fast Random Access.
    2. It is an ordered collection (by index) and not sorted.
    3. It implements Random Access Interface.
    4. Array List maintains the insertion order and it accepts the duplicates. But not sorted.

    It is same as Array List.

    1. Vector methods are synchronized.
    2. Thread safety.
    3. It also implements the Random Access.
    4. Thread safety usually causes a performance hit.
    5. Vector also maintains the insertion order and accepts the duplicates.
    Linked List
    1. Elements are doubly linked to one another.
    2. Performance is slow than Array list.
    3. Good choice for insertion and deletion.
    4. In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc.
    5. Maintains the insertion order and accepts the duplicates.

    Array Array List
    Size Should be given at the time of array declaration.

    String[] name = new String[2]

    Not required. It changes the size dynamically.

    ArrayList name = new ArrayList

    Index requirement while adding element Index should be specified.

    name[1] = “book”

    No index required.


    Type parameterization Array is not type parameterized ArrayList in java 5.0 are parameterized.
    ArrayLists are a type.

    Eg: a list of String.

    Data types Arrays can contain primitive data types as well as objects Arraylists can contain only objects, no primitive data types are allowed.

    Array List Vector
    not synchronized. synchronized.
    fast (as it’s non-synchronized). 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.
    does not define the increment size. defines the increment size.
    only Iterator can be used for traversing an Array List. both Enumeration and Iterator can be used for traversing Vector.

    Java Exception Interview Questions

    An Exception is a problem that can occur during the normal flow of an execution.

    A method can throw an exception when something fails at runtime.
    If that exception couldn’t be handled, then the execution gets terminated before it completes the task.

    If we handled the exception, then the normal flow gets continued.

    Exceptions are a subclass of java.lang.Exception.

    Example for handling Exception:

    //Risky codes are surrounded by this block
    }catch(Exception e){
    //Exceptions are caught in catch block

    1. The normal flow of the execution won’t be terminated if exception got handled
    2. We can identify the problem by using catch declaration

    Exception Hierarchy in Java

    Exception Hierarchy in Java
    Throwable is a parent class of all Exception classes.
    Exception is further divided into Exceptions and Errors.
    There are two types of Exceptions: Checked exceptions and UncheckedExceptions or RunTimeExceptions.
    All Errors are unchecked.

    Read more about Exceptions on Oracle website >>>

    Read more about Errors in Oracle Javadoc >>>

    See all Error Subclasses on Oracle Website >>>

    See all Exception Subclasses on Oracle Website >>>

    Error vs. Exception in Java
    Errors Exceptions
    Recoverability Impossible to recover from an Error

    Though error can be caught in the catch block
    but the execution of application will come to a halt and is not recoverable.

    Possible to recover from an Exception

    Exceptions are conditions that occur because of bad input or human error etc.
    E.g., FileNotFoundException will be thrown if the specified file does not exist.
    Or a NullPointerException will take place if you try using a null reference.

    In most of the cases it is possible to recover from an exception
    E.g., by giving the user feedback for entering proper values.

    Checked vs. Unchecked Unchecked Can be both: checked and unchecked
    When happen Run-time Can be both:compile-time and run-time
    Caused by Application running environment Application itself

    1. Throwable is the Superclass of all exceptions and errors.
    2. You can use it in a catch clause, but you should never do it!
    3. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application.
    4. Typical examples for that are the OutOfMemoryError or the StackOverflowError.

    Checked Exception
    1. These exceptions are checked by the compiler at compile-time.
    2. Classes that extend Throwable class except RuntimeException and Error are called checked Exception.
    3. Checked Exceptions must either declare the exception using throws keyword (or) surrounded by appropriate try/catch.

    E.g. ClassNotFound Exception, IOException, SQLException

    Unchecked Exception
    1. The classes that extend RuntimeException are known as unchecked exceptions.
    2. These exceptions are not checked at compile-time by the compiler.
    3. The compiler doesn’t force to handle these exceptions.

    E.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBounds Exception

    There are five keywords used to handle exceptions in Java:

    1. try
    2. catch
    3. finally
    4. throw
    5. throws

    When a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any one of the blocks is mandatory.


    This is followed by try block. Exceptions are caught here.


    This is followed either by try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are provided here.

    Using try/catch

    A risky code is surrounded by try block.
    If an exception occurs, then it is caught by the catch block which is followed by the try block.

    class Manipulation{
    public static void main(String[] args){
    Public void add(){
    }catch(Exception e){
    By declaring throws keyword

    At the end of the method, we can declare the exception using throws keyword.

    class Manipulation{
    public static void main(String[] args){
    public void add() throws Exception{

    Yes we can have multiple catch blocks under single try block but the approach should be from specific to general.

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

    throw throws
    Usage Used to explicitly throw an exception. Used to declare an exception
    Propagation Checked exceptions can not be propagated with throw only. Checked exception can be propagated with throws.
    Followed by Throw is followed by an instance. Throws is followed by class.
    Where used Within the method. With the method signature.
    Multiple exceptions You cannot throw multiple exceptions. You can declare multiple exceptions.
    E.g. public void method()throws IOException,SQLException.

    1. Finally block always executes a set of statements.
    2. It is always associated with a try block regardless of any exception that occurs or not.

    Finally will not be executed

    1. if the program exits either by calling System.exit()
    2. or by causing a fatal error that causes the process to abort.

    1. Exception and all of it’s Subclasses do not provide any specific methods.
    2. All of the methods are defined in the base class Throwable.
    Method Description
    String getMessage() This method returns the message String of Throwable about the exception.
    The message can be provided while creating the exception through it’s constructor.
    String getLocalizedMessage() This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.
    Synchronized Throwable getCause() This method returns the cause of the exception
    or null id the cause is unknown
    as represented by a Throwable object.
    String toString() This method returns the information about Throwable in String format.
    The returned String contains the name of Throwable class and localized message.
    void printStackTrace() This method prints the stack trace information to the standard error stream.
    This method is overloaded and we can pass PrintStream or PrintWriter as an argument to write the stack trace information to the file or stream.
    public StackTraceElement[] getStackTrace() This method returns an array containing each element on the stack trace.
    The element at index 0 represents the top of the call stack
    whereas the last element in the array represents the method at the bottom of the call stack.

    To create you own exception extend the Exception class or any of its subclasses.

    class New1Exception extends Exception { }               // this will create Checked Exception
    class NewException extends IOException { }             // this will create Checked exception
    class NewException extends NullPonterExcpetion { }  // this will create UnChecked exception

    Exception is first thrown from the method which is at the top of the stack. If it doesn’t catch, then it pops up the method and moves to the previous method and so on until they are got.

    This is called Exception propagation.

    public class Manipulation{
    public static void main(String[] args){
    public void add(){

    From the above example, the stack looks like as shown below:


    If an exception occurred in the addition() method is not caught, then it moves to the method add().
    Then it is moved to the main() method and then it will stop the flow of execution.
    It is called Exception Propagation.

    OutOfMemoryError is the subclass of java.lang.Error which generally occurs when our JVM runs out of memory.

    Java Threads Interview Questions

    In Java, the flow of a execution is called Thread.

    1. A thread is the smallest piece of programmed instructions which can be executed independently by a scheduler.
    2. All java programs have at least one thread known as the main thread
    3. The Main thread is created by JVM when the program starts its execution. The main thread is used to invoke the main() of the program.
    4. The user can define their own threads by extending Thread class (or) by implementing Runnable interface.
    5. Threads are executed concurrently.
    public static void main(String[] args){
       //main thread starts here

    Java Thread Lifecycle

    Thread has the following states:

    1. New
    2. Runnable
    3. Running
    4. Non-runnable (Blocked)
    5. Terminated

    In New state, Thread instance has been created but start () method is not yet invoked. Now the thread is not considered alive.


    The Thread is in runnable state after invocation of the start () method, but before the run () method is invoked. But a thread can also return to the runnable state from waiting/sleeping. In this state the thread is considered alive.


    The thread is in running state after it calls the run () method. Now the thread begins the execution.


    The thread is alive but it is not eligible to run. It is not in runnable state but also, it will return to runnable state after some time.

    E.g., wait, sleep, block.


    Once the run method is completed then it is terminated. Now the thread is not alive.

    There are two ways available to create a thread in Java:

    1. By extending the Thread class.
    2. By implementing the Runnable interface.
    Extend Thread class

    Extending a Thread class and override the run method.
    The thread is available in java.lang.thread.

    Public class Addition extends Thread {
    public void run () {

    The disadvantage of using a thread class is
    that we cannot extend any other classes
    because we have already extend the thread class.
    We can overload the run() method in our class.

    Implement Runnable interface

    Another way is implementing the runnable interface.
    For that we should provide the implementation for run() method which is defined in the interface.

    Public class Addition implements Runnable {
    public void run () {

    Process Thread
    Definition An executing instance of a program is called a process. A thread is a subset of the process.
    Communication Processes must use inter-process communication to communicate with sibling processes. Threads can directly communicate with other threads of its process.
    Control Processes can only exercise control over child processes. Threads can exercise considerable control over threads of the same process.
    Changes Any change in the parent process does not affect child processes. Any change in the main thread may affect the behavior of the other threads of the process.
    Memory Run in separate memory spaces. Run in shared memory spaces.
    Controlled by Operating system. Programmer in a program.
    Dependence Processes are independent. Threads are dependent.

    If we need our class to extend some other classes other than the thread
    then we can go with the Runnable interface
    because in java we can extend only one class.

    If we are not going to extend any class then we can extend the thread class.

    Start() method creates new thread and the code inside the run() method is executed in the new thread.

    If we directly called the run() method then a new thread is not created and the currently executing thread will continue to execute the run() method.

    Join() method is used to join one thread with the end of the currently running thread.

    public static void main (String[] args){
    Thread t = new Thread();
    1. From the above code, the main thread started the execution.
    2. When it reaches the code t.start() then ‘thread t’ starts the own stack for the execution.
    3. JVM switches between the main thread and ‘thread t’.
    4. Once it reaches the code t.join() then ‘thread t’ alone is executed and completes its task,
      then only main thread started the execution.

    Join() is a non-static method.
    Join() method has overloaded version.
    So we can mention the time duration in join() method also “.s”.

    A yield() method moves the currently running thread to a runnable state and allows the other threads for execution.
    So that equal priority threads have a chance to run.
    It is a static method.
    It doesn’t release any lock.

    Yield() method moves the thread back to the Runnable state only, and not the thread to sleep(), wait() (or) block.

    public static void main (String[] args){
    Thread t = new Thread ();
    t.start ();
    public void run(){

    notify() notifyAll()
    This method is used to send a signal to wake up a single thread in the waiting pool. This method sends the signal to wake up all the threads in a waiting spool.

    We can stop a thread by using the following thread methods.

    1. Sleeping
    2. Waiting
    3. Blocked


    Sleep() method is used to sleep the currently executing thread for the given amount of time.
    Once the thread is wake up it can move to the runnable state.
    So sleep () method is used to delay the execution for some period.

    It is a static method.

    Thread. Sleep (2000)

    So it delays the thread to sleep 2 milliseconds.
    Sleep () method throws an uninterrupted exception, hence we need to surround the block with try/catch.

    public class ExampleThread implements Runnable{
    public static void main (String[] args){
    Thread t = new Thread ();
    public void run(){
    }catch(InterruptedException e){

    Wait() method is used to make the thread to wait in the waiting pool.
    When a wait() method is executed during a thread execution then immediately the thread gives up the lock on the object and goes to the waiting pool.
    Wait() method tells the thread to wait for a given amount of time.

    Then the thread will wake up after notify() (or) notify all() method is called.

    Wait() and the other above-mentioned methods do not give the lock on the object immediately until the currently executing thread completes the synchronized code. It is mostly used in synchronization.

    public static void main (String[] args){
    Thread t = new Thread ();
    Synchronized(t) {

    Multiple threads are executed simultaneously. Each thread starts their own stack based on the flow (or) priority of the threads.

    public class MultipleThreads implements Runnable {
    public static void main (String[] args){//Main thread starts here
    Runnable r = new runnable ();
    Thread t=new thread();
    t.start ();//User thread starts here
    Addition add = new addition();
    public void run(){
    }//User thread ends here

    On the 1st line execution, JVM calls the main method and the main thread stack looks as shown below:

    Main thread

    Once the execution reaches, t.start () line then a new thread is created and the new stack for the thread is also created. Now JVM switches to the new thread and the main thread are back to the runnable state.

    The two stacks look as shown below.

    Main thread User thread
    Start() run()

    Now, the user thread executed the code inside the run() method.

    Main thread User thread
    Start() go()
    Run() run()

    Once the run() method has completed, then JVM switches back to the main thread and the User thread has completed the task and the stack was disappeared.

    JVM switches between each thread until both the threads are completed. This is called Multi-threading.

    1. Synchronization refers to multi-threading.
    2. Only one thread can access a block of code at a time =
      a synchronized block of code can be executed by only one thread at a time.
    3. As Java supports execution of multiple threads, two or more threads may access the same fields or objects.
    4. If multiple thread accesses the same block of code, there is a chance for inaccurate results at the end.
    5. To avoid this issue, we can provide synchronization for the sensitive block of codes.
      Synchronization is a process which keeps all concurrent threads in execution to be in sync.
      Synchronization avoids memory consistency errors caused due to inconsistent view of shared memory.
    6. When a method is declared as synchronized the thread holds the monitor for that method’s object.
      If another thread is executing the synchronized method the thread is blocked until that thread releases the monitor.
    7. The synchronized keyword means that a thread needs a key in order to access the synchronized code.
      Every Java object has a lock. A lock has only one key.
      A thread can access a synchronized method only if the thread can get the key to the objects lock.
    public class ExampleThread implements Runnable{
     public static void main (String[] args){
     Thread t = new Thread ();
     t.start ();
     public void run(){

    Java Multithreading and Threads Synchronization

    Synchronization is not recommended to implement all the methods.
    Because if one thread accesses the synchronized code then the next thread should have to wait.
    So it slows performance on the other end.

    Java Serialization Interview Questions

    Converting a file into a byte stream is known as Serialization. The objects in the file is converted to the bytes for security purposes. For this, we need to implement java.io.Serializable interface. It has no method to define.

    Variables that are marked as transient will not be a part of the serialization. So we can skip the serialization for the variables in the file by using a transient keyword.

    Transient variables are not part of the serialization process.
    During deserialization, the transient variables values are set to default value.
    It is not used with static variables.

    transient int numbers;

    Volatile variable values are always read from the main memory and not from thread's cache memory.
    This is used mainly during synchronization.
    It is applicable only for variables.

    volatile int number;

    ObjectOutputStream and ObjectInputStream classes are higher level java.io. package.
    We will use them with lower level classes FileOutputStream and FileInputStream.

    ObjectOutputStream.writeObject --> Serialize the object and write the serialized object to a file.

    ObjectInputStream.readObject --> Reads the file and deserializes the object.

    To be serialized, an object must implement the serializable interface.
    If superclass implements Serializable, then the subclass will automatically be serializable.

    Serialization Deserialization
    Serialization is the process which is used to convert the objects into byte stream Deserialization is the opposite process of serialization where we can get the objects back from the byte stream.
    An object is serialized by writing it an ObjectOutputStream. An object is deserialized by reading it from an ObjectInputStream.

    Whenever an object is Serialized, the object is stamped with a version ID number for the object class.
    This ID is called the SerialVersionUID.
    This is used during deserialization to verify that the sender and receiver that are compatible with the Serialization.

    JDBC Interview Questions

    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)

    Steps to Connect to a Database in Java
    1. Registering the driver class
    2. Creating connection
    3. Creating statement
    4. Executing queries
    5. Closing connection

    JDBC API components
    Interfaces Classes
    1. Connection
    2. Statement
    3. PreparedStatement
    4. ResultSet
    5. ResultSetMetaData
    6. DatabaseMetaData
    7. CallableStatement etc.
    1. DriverManager
    2. Blob
    3. Clob
    4. Types
    5. SQLException etc.

    Role of JDBC DriverManager Class
    1. The DriverManager class manages the registered drivers.
    2. It can be used to register and unregister drivers.
    3. It provides factory method that returns the instance of Connection.

    1. The Connection interface maintains a session with the database.
    2. It can be used for transaction management.
    3. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

    Java JDBC Connection Interface

    Purpose of JDBC ResultSet Interface

    The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

    JDBC ResultSetMetaData Interface

    The ResultSetMetaData interface returns the information of table
    such as total number of columns, column name, column type etc.

    JDBC DatabaseMetaData Interface

    The DatabaseMetaData interface returns the information of the database
    such as username, driver name, driver version, number of tables, number of views etc.

    Batch Processing in JDBC
    1. Batch processing helps you to group related SQL statements into a batch
      and execute them instead of executing a single query.
    2. By using batch processing technique in JDBC, you can execute multiple queries which makes the performance faster.

    Execute vs. executeQuery vs. executeUpdate

    Statement execute(String query)
    is used to execute any SQL query and it returns TRUE if the result is an ResultSet such as running Select queries. The output is FALSE when there is no ResultSet object such as running Insert or Update queries. We can use getResultSet() to get the ResultSet and getUpdateCount() method to retrieve the update count.

    Statement executeQuery(String query)
    is used to execute Select queries and returns the ResultSet. ResultSet returned is never null even if there are no records matching the query. When executing select queries we should use executeQuery method so that if someone tries to execute insert/update statement it will throw java.sql.SQLException with message “executeQuery method can not be used for update”.

    Statement executeUpdate(String query)
    is used to execute Insert/Update/Delete (DML) statements or DDL statements that returns nothing. The output is int and equals to the row count for SQL Data Manipulation Language (DML) statements. For DDL statements, the output is 0.

    You should use execute() method only when you are not sure about the type of statement else use executeQuery or executeUpdate method.

    JDBC Statements
    1. JDBC statements are used to send SQL commands to the database and retrieve data back from the database.
    2. Various methods like execute(), executeUpdate(), executeQuery, etc. are provided by JDBC to interact with the database.
    3. JDBC supports 3 types of statements:
      1. Statement: Used for general purpose access to the database and executes a static SQL query at runtime.
      2. PreparedStatement: Used to provide input parameters to the query during execution.
      3. CallableStatement: Used to access the database stored procedures and helps in accepting runtime parameters.

    Leave a Reply or Comment

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