Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents

Top Java Interview Questions and Answers

In 1995, James Gosling from Microsystems invented the Java programming language. Java is still one of the most widely used programming languages. Nearly 5.5 billion devices were built using Java. There is still high demand for Java developers in the IT industry. 

We filtered the most asked 26 Java interview questions and listed into three sets of questions, based on the skill level. These interview questions will help you to crack an interview with top MNCs. 

Table of Contents

A) Java Interview Questions for Freshers Level

1) What is Java? 

2) What is a functional interface in Java? 

3) What are the features of Java? 

4) Differences between Stack and Heap memory in Java? 

5) What is main() method in Java? 

6) What are JVM, JRE, and JDK? 

7) Differences between == and equals() in Java? 

8) Why Java is not a pure object-oriented language? 

9) What is the difference between the break and continue statements? 

B) Java Interview Questions for Intermediates Level 

1) What is ‘super’ keyword in Java? 

2) Why Java is a Dynamic programming language? 

3) Explain Daemon Thread in Java. 

4) What is a JDBC Driver? 

5) What is “OutOfMemoryError” in Java? 

6) Differences between HashMap and HashTable in Java? 

7) Is Java “Pass by Value“ or “Pass by Reference”? 

8) What is a ClassLoader? 

9) What are constructors in Java? 

C) Java Interview Questions for Experts Level 

1) What is Servlet Session Management?  

2) What is stream pipelining in Java? 

3) What are JCA and JPA in java? 

4) What is the lifecycle of a thread in java? 

5) Problem: Can you sort HashMap by values? 

6) Problem: Can you remove duplicates in an Array List? 

7) Problem: Can you reverse a string using Java? 

8) Problem: Can you find if a string is present in a text file? 

9) Conclusion 

Java Interview Questions for Freshers Level

1) What is java?

Java is an Object-Oriented Programming Language. It is a high-level and secure programming language. 

It was developed by “James Gosling” in 1995. Java has its own run-time environment called JRE (Java Run-time Environment). It is made for developers to “write once and run anywhere” which means that compiled Java code can run on any platform that supports Java. The latest version of Java is “Java SE 18.0.1.1”.  

“Hello world” using Java: 

public class BasicJavaSyntax { 
   public static void main(String []args) { 
      System.out.println("Hello World");  

   } 

2) What is a functional interface in Java? 

In Java, an interface contains a single abstract method called functional interface. It may include static and default methods. It is implemented using “@Functional Interface” annotation.  

Example for functional interface: 

package java.lang; 

@FunctionalInterface 

public interface Runnable { 

     public abstract void run(); 

}

3) What are the features of Java?

The amazing features of Java programming language.

1) Simple: Java’s syntax is simple and easy to learn

2) Object-Oriented: Java is Object-oriented programming language

3) Robust: It is a robust language; it has a strong memory management system

4) Portable: It is easy to port by carrying the Java bytecode to any platform

5) Secured: It is highly secure. With this feature, you can develop anti-virus software systems

6) Platform-independent: Java is platform-independent. It uses the BYTE CODE concept. A compiled program from one machine can be executed on any machine

7) Architecture Neutral: Java enables its application to compile on one hardware architecture and execute on another hardware

8) Multithreaded: Java is multithreaded. Multithread is a process of executing multiple tasks simultaneously

9) High performance: Java is a high-performance language which is facilitated with the help of a just-in-time compiler, but it is a bit slower than C++ language

10) Distributed: Java helps users create distributed applications on the internet

4) Differences between Stack and Heap memory in Java?  
 

Stack

Heap

Easy to implement

Difficult to implement

Linear data structure

Hierarchical data structure

Memory allocated in a continuous block

Memory allocated in a random fashion

The cost is less for building and maintenance of stack

Cost is high to build and maintain a heap

Excellent locality of reference

Sufficient locality of reference

If all blocks fail to be occupied, memory will be lost too

It is possible to resize in heap

Disadvantage of stack is shortage in memory due to fixed size

The disadvantage of heap is fragmentation of memory


5) What is main() method in Java? 

The main() method in Java is predefined in JVM (Java Virtual Machine). It is the starting point of Java program. Without the main() method, JVM will not execute the program. 

Syntax: 

Public static void main(String args[]) 

6) What are JVM, JRE, and JDK? 

JVM (Java Virtual Machine): JVM is a specification that provides a runtime environment. JVM is also called an interpreter because it is used to execute the line-by-line Java program.  

JRE (Java Run-Time Environment): JRE is an installation package that gives an environment to run the java program on your machine. JRE is only used by the end-users of the system.  

JDK (Java Development kit): JDK provides an environment to write and execute the java program. JDK contains Development toolkit and JRE. 

7) Differences between == and equals() in Java? 
 

== 

equals() 

== is a comparison operator in Java 

It is a method in Java 

The == operator compares objects and reference values 

equals() method compares objects and reference value 

User can use == operator with objects and primitives. 

It is impossible to use equals() with primitives 

== operator cannot be overridden 

equals() method can be overridden 

The == operator cannot compare conflicting objects 

equals() can compare conflicting objects


8) Why Java is not a pure Object-Oriented language? 

Java is not a pure Object-Oriented programming language, because it supports primitive data types. Primitive data types contain Boolean, int, char, float, double, short, byte.
 

Explore our java training
 

9) What is the difference between the break and continue statements in Java? 
 

Break

Continue

The Break is a statement that is used terminate the loop

Continue is a statement that is used skip an iteration of the loop

Break statement can be used with ‘switch’

Continue statement cannot be used with ‘switch’

Break statement ends an entire loop early

Continue statement brings the next iteration early

Break statement ends the execution of loop

Continue statement does not end the execution of loop


Java Interview Questions for Intermediates Level

1) What is ‘super’ keyword in Java? 

‘Super’ keyword is a method used to call and access the superclass constructor. It refers to the parent object. The main purpose of this keyword is to avoid the confusion between superclass and subclass. 

Example

class Vehicle 

    int Speed = 120; 

class Bike extends Vehicle 

    int Speed = 180; 

    void screen() 

    { 

        System.out.println("Speed: " + super.Speed); 

    } 

}   

class Test 

    public static void main(String[] args) 

    { 

        Bikesmall = new Bike(); 

        small.screen(); 

    } 

}

2) Why Java is a Dynamic programming language? 

Java is a Dynamic programming language, because java allows run-time modification. Run-time modification is the process of changing a program during the execution. Java is made to adjust to an evolving environment, and it allows developers to pass parameters at runtime without having to define them beforehand.  

3) Explain Daemon Thread in Java. 

It is a background service thread (low priority thread) which runs in the background to perform some specific tasks. It provides services to the user thread. JVM automatically ends this thread, when all the user threads die.  

How to create a Daemon Thread:  

NewThread daemonThread = new NewThread();  

daemonThread.setDaemon(true);  

daemonThread.start(); 

4) What is JDBC Driver? 

JDBC (Java Data Base Connectivity) is an API (Application Programming Interface) for Java. It allows Java applications to connect with databases. It is used to send queries and update statements to the database,  

There are four types of JDBC drivers: 

1) JDBC-ODBC bridge driver 

2) Network Protocol driver  

3) Native-API  

4) Thin driver 

5) What is “OutofMemoryError” in Java? 

”OutOfMemoryError” in Java is a runtime error. It occurs when JVM (Java Virtual Machine) is unable to allot an object due to poor space in Java heap. Also, when the Garbage Collector is unable to free up the space, the “OutofMemoryError” issue can occur. It occurs when memory is insufficient.  

“Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at OutOfMemoryErrorExample.main(OutOfMemoryErrorExample.java:8)” 

6) Differences between HashMap and HashTable in Java? 
 

HashMap

HashTable

HashMap is non-legacy

HashTable is legacy

HashMap introduced in the Java’s 1.2 version of Java

HashTable introduced in Java’s 1.0 version

Null is permitted for both key and value

Null is not permitted for both key and value

Object is not thread safe in HashMap

Object is thread safe in HashTable

Method is not synchronized

Method is synchronized

High performance

Low performance


7) Is Java “Pass-by-Value“ or “Pass-by-Reference”? 

Java is “Pass-by-Value".

“Pass-by-Value": It means, a function (method) is called by passing a value. It makes a copy in memory of the parameter’s value.  

Example:  

public class Sample {      

      int val = 100; 

    void call(int a) {  

        val = val+100; 

    }  

    public static void main(String[] args) { 

        Sample eg = new Sample(); 

        System.out.println("Before: " + eg.val);

                eg.call(50510); 

        System.out.println("After: " + eg.val);  

    } 

Output:  

Before: 100 

After: 200 

8) What is a ClassLoader? 

ClassLoader is an abstract class in Java. It is a sub system of JVM (Java Virtual Machine). It is used to load class files when a program is executing. ClassLoader performs the first process in loading the executable file. It belongs to java.lang package. ClassLoader works based on three principles: Delegation, Visibility, and Uniqueness. 

There are three types of ClassLoader: 

A) Bootstrap ClassLoader 

B) Extensions Class Loader 

C) System Class Loader 

9) What is constructor in Java? 

Constructor is a block of code same as like methods. A constructor used to start an object. It is automatically invoked when a new object is created.

Two types of Constructors:  

1) Default: By default, java compiler creates the default constructor. Java requires no constructor when we create a class.

2) Parameterized: Parameterized constructor is used to start instance variables when it accepts a particular parameters.  

Java Interview Questions for Experts Level

1) What is Servlet Session Management in Java? 

Servlet Session Management is used to store session data in a Web container. In this mechanism, user’s data is managed by the session tracking method. Some other methods used to manage sessions in Java, are Cookies, HTTP Session API, URL writing, Hidden Fields, etc.  

2) What is stream pipelining in Java? 

A stream is a series of objects that support different methods that can be pipelined to produce the desired result. Stream pipelining is the concept of changing operations together. It is an API used to process the set of objects.

1) Stream and data structure are not same, but the process of stream is same as data structure. Stream takes data from collections, Array and input and output channels 

2) Stream provides the result based on the pipelined methods 

3) Every intermediate operation is slowly executed and returns a stream as a result

3) What are JCA and JPA in java? 

JCA: Java EE Connector Architecture and J2EE Connector Architecture. It is used to connect application servers by connecting an enterprise’s data system.  

JPA: Java Persistence API. It is the standard API for persistence and object/relational mapping for the Java EE platform. It is crucial to Java developers for data binding purposes.  

4) What is the lifecycle of a thread in java?  

In Java, a thread passes through different stages in its lifecycle. A thread is always present in one of these following stages: 

A) New: A new-born thread enters its lifecycle in the new state but start() method has not started the execution yet. 

B) Runnable: In this state, it is ready for execution, and is waiting for resources allocation. 

C) Blocked: When a thread is suspended or sleeping or in the waiting to satisfy some condition, it is considered as blocked state.  

D) Waiting: In this stage, the thread waits for the other thread to perform a specific task with no time limit   

E) Timed_Waiting: In this stage, thread waits for other threads to perform a specified task for a certain time limit 

F) Terminated: In this final stage, the thread automatically moves to dead state when execution is completed.  

5) Problem: Can you sort HashMap by keys and values? 

import java.text.ParseException;  

import java.util.ArrayList;  

import java.util.Collections;  

import java.util.Comparator;  

import java.util.HashMap;  

import java.util.LinkedHashMap;  

import java.util.List;  

import java.util.Map.Entry;  

import java.util.Set;  

import java.util.TreeMap

public class HashMapSorting {  

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

                   HashMap codenames = new HashMap(); 

                   codenames.put("JDK 1.1.4", "Sparkler"); 

                   codenames.put("J2SE 1.2", "Playground"); 

                   codenames.put("J2SE 1.3", "Kestrel"); 

                   codenames.put("J2SE 1.4", "Merlin"); 

                   codenames.put("J2SE 5.0", "Tiger"); 

                   codenames.put("Java SE 6", "Mustang"); 

                   codenames.put("Java SE 7", "Dolphin"); 

                    System.out.println("HashMap before sorting, random order ");  

                   Set> entries = codenames.entrySet();      

                             for(Entry entry : entries){  

                     System.out.println(entry.getKey() + " ==> " + entry.getValue());  

                     TreeMap sorted = new TreeMap<>(codenames); 

                   Set> mappings = sorted.entrySet(); 
               

         System.out.println("HashMap after sorting by keys in ascending order ");  

         for(Entry mapping : mappings){  

                System.out.println(mapping.getKey() + " ==> " + mapping.getValue()); 

      Comparator> valueComparator  

                 = new Comparator>() {  

             @Override  

            public int compare(Entry e1, Entry e2) {  

                  String v1 = e1.getValue();  

                  String v2 = e2.getValue();  

                  return v1.compareTo(v2); 
   } 
        }; 

  List> listOfEntries  
           = new ArrayList>(entries); 

     Collections.sort(listOfEntries, valueComparator);  

     LinkedHashMap sortedByValue 

                           = new LinkedHashMap(listOfEntries.size()); 

     for(Entry entry : listOfEntries){  

           sortedByValue.put(entry.getKey(), entry.getValue());  


    

     System.out.println("HashMap after sorting entries by values ");  

     Set> entrySetSortedByValue = sortedByValue.entrySet();  

     for(Entry mapping : entrySetSortedByValue){  

            System.out.println(mapping.getKey() + " ==> " + mapping.getValue());  

            }  

       }  



Output:  

HashMap before sorting, random order  

Java SE 7 ==> Dolphin  

J2SE 1.2 ==> Playground  

Java SE 6 ==> Mustang  

J2SE 5.0 ==> Tiger  

J2SE 1.3 ==> Kestrel  

J2SE 1.4 ==> Merlin  

JDK 1.1.4 ==> Sparkler  

HashMap after sorting by keys in ascending order  

J2SE 1.2 ==> Playground  

J2SE 1.3 ==> Kestrel  

J2SE 1.4 ==> Merlin  

J2SE 5.0 ==> Tiger  

JDK 1.1.4 ==> Sparkler  

Java SE 6 ==> Mustang  

Java SE 7 ==> Dolphin  

HashMap after sorting entries by values  

Java SE 7 ==> Dolphin  

J2SE 1.3 ==> Kestrel  

J2SE 1.4 ==> Merlin  

Java SE 6 ==> Mustang  

J2SE 1.2 ==> Playground 

 JDK 1.1.4 ==> Sparkler  

J2SE 5.0 ==> Tiger 
                                               
 6) Problem: Can you remove duplicates in an Array List? 

Removing duplicates in an Array List using LinkedHashSet 

ArrayListExample.java 

import java.util.ArrayList; 

import java.util.Arrays; 

import java.util.LinkedHashSet; 

  public class ArrayListExample  

    public static void main(String[] args)  

    { 

        // ArrayList with duplicate elements 

        ArrayList numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8)); 

                  System.out.println(numbersList); 

          LinkedHashSet hashSet = new LinkedHashSet<>(numbersList); 

              ArrayList listWithoutDuplicates = new ArrayList<>(hashSet); 

                System.out.println(listWithoutDuplicates); 

    } 

Output: 

Console 

[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8] 

[1, 2, 3, 4, 5, 6, 7, 8] 

7) Problem: Can you reverse a string using Java? 

Reversing a string using a loop in Java 

public class ReverseStringByFavTutor 
 

 
   public static void main(String[] args) { 
  
       String stringExample  =  "FavTutor"; 
 
       System.out.println("Original string: "+stringExample); 
 
        StringBuilder reverseString = new StringBuilder(stringExample); 
 
        reverseString.reverse();   
   
       String result = reverseString.toString(); 
 
        System.out.println("Reversed string: "+result); 
  
   } 
 

Output:

Original string: FavTutor 
 
Reversed string: rotuTvaF 

8) Problem: Can you find if a string is present in a text file? 

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
  
public class StringFinder { 
 
public static void main(String[] args) 

    double count = 0,countBuffer=0,countLine=0; 
    String lineNumber = ""; 
    String filePath = "C:UsersvikiDesktopTestText.txt"; 
    BufferedReader br; 
    String inputSearch = "are"; 
    String line = ""; 
 
    try { 
        br = new BufferedReader(new FileReader(filePath)); 
        try { 
            while((line = br.readLine()) != null) 
            { 
                countLine++; 
                //System.out.println(line); 
                String[] words = line.split(" "); 
 
                for (String word : words) { 
                  if (word.equals(inputSearch)) { 
                    count++; 
                    countBuffer++; 
                  } 
                } 
 
                if(countBuffer > 0) 
                { 
                    countBuffer = 0; 
                    lineNumber += countLine + ","; 
                } 
 
            } 
            br.close(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
    } catch (FileNotFoundException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
    } 
 
    System.out.println("Times found at--"+count); 
    System.out.println("Word found at--"+lineNumber); 

Conclusion 

Java is still a highly demanded programming language in IT industry. Start preparing this top interview to crack your java interview.  

If you are looking to make a career in Java, check out this advanced Java training program offered by Knowledge Academy. In this training you will learn the core to advanced concept of Java with projects. Get Certified now!  

Frequently Asked Questions

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

OUR BIGGEST SPRING SALE!

Special Discounts

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.