Question library

Java interview questions and answers

45 Java interview questions with answers: 10 junior, 15 mid-level and 20 senior. Junior answers are free to read.

Junior Mid Senior Updated How these answers are created

* View counts were reset on 18 October 2026, when Interviewplus moved to interviewplus.app. Votes were not affected.

Answer

Java is a high-level programming language developed by Sun Microsystems (now owned by Oracle Corporation) in the mid-1990s. It is designed to be portable, meaning that once a program is written in Java, it can be run on any platform or operating system without needing to be rewritten. Java is widely used for developing mobile applications, web applications, desktop applications, and server-side software.

One of the main differences between Java and other programming languages is its platform independence. Java programs are compiled into bytecode that can run on any machine with a Java Virtual Machine (JVM) installed, making them highly portable. This allows Java to be used for a wide range of applications, including web development, scientific computing, and enterprise software development.
Another key feature of Java is its robustness and security. Java is designed to catch errors at compile-time rather than runtime, which reduces the likelihood of program crashes or unexpected behavior. Additionally, Java's security model allows it to run untrusted code in a safe and secure way, making it ideal for use in networked environments.
Java also has a large and active developer community, which has contributed to the development of a vast array of libraries and frameworks that make it easier to develop complex applications. This has helped to make Java one of the most popular programming languages in use today.
In summary, Java is a versatile, portable, and secure programming language that is widely used for developing a variety of applications. Its platform independence, robustness, and large developer community make it an attractive choice for many programmers.

Answer

Here's an example implementation of a singly linked list in Java:

public class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class LinkedList {
    Node head;

    public LinkedList() {
        this.head = null;
    }

    public void insert(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    public void delete(int data) {
        if (head == null) {
            return;
        }
        if (head.data == data) {
            head = head.next;
            return;
        }
        Node current = head;
        while (current.next != null) {
            if (current.next.data == data) {
                current.next = current.next.next;
                return;
            }
            current = current.next;
        }
    }

    public void display() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
}

This implementation has a Node class that contains a data value and a reference to the next node in the list, and a LinkedList class that has a reference to the head node of the list. The insert method inserts a new node at the end of the list, the delete method removes the first node with a specified data value, and the display method prints out the data values of all nodes in the list.

Answer

In Java, you can declare and initialize a variable in a single statement or in two separate statements. Here's how to do it:
1. Declaring a variable: To declare a variable in Java, you need to specify its data type and give it a name. For example, to declare an integer variable named x, you would use the following syntax:

int x;

This creates a variable named x of type int. You can replace int with any other data type supported by Java, such as double, boolean, or String.
2. Initializing a variable: To initialize a variable, you need to assign it a value. You can do this in the same statement as the variable declaration or in a separate statement. For example, to initialize the variable x to the value 10, you could use the following syntax:

int x = 10;

This declares the variable x and initializes it to the value 10 in a single statement.
Alternatively, you could declare the variable first and then initialize it in a separate statement like this:

int x;  // declaration
x = 10; // initialization

This creates a variable named x and initializes it to the value 10 in two separate statements.
Note that when you declare and initialize a variable in the same statement, the data type is inferred from the value you assign to the variable. For example, if you assign a string value to a variable, Java will automatically infer that the variable is of type String. Here's an example:

String message = "Hello, world!"; // String variable
double pi = 3.14159;              // double variable
boolean isTrue = true;            // boolean variable

In summary, you can declare and initialize a variable in Java in a single statement or in two separate statements. To declare a variable, you need to specify its data type and give it a name. To initialize a variable, you need to assign it a value using the = operator.

Answer

In Java, you can write a for loop to iterate over a range of values or to iterate over elements in an array or collection. Here's the basic syntax of a for loop in Java:

for (initialization; condition; update) {
    // loop body
}

The for loop consists of three parts:
1. Initialization: In this part, you declare and initialize a variable that will be used to control the loop. This is typically a loop counter variable that keeps track of the number of iterations.
2. Condition: In this part, you specify a Boolean expression that is evaluated at the beginning of each iteration. If the expression is true, the loop body is executed; if it's false, the loop terminates.
3. Update: In this part, you specify an expression that is executed at the end of each iteration. This is typically used to update the loop counter variable.
Here's an example of a for loop that prints the numbers from 1 to 10:

for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}

In this example, the loop counter variable is i, which is initialized to 1 in the initialization part. The loop condition is i <= 10, which means that the loop will execute as long as i is less than or equal to 10. The update part is i++, which means that the loop counter variable i is incremented by 1 at the end of each iteration.
You can also use a for loop to iterate over elements in an array or collection. Here's an example that prints the elements of an array:

int[] numbers = {1, 2, 3, 4, 5};

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

In this example, the loop counter variable i is used to access the elements of the numbers array using the square bracket notation. The loop condition is i < numbers.length, which means that the loop will execute as long as i is less than the length of the numbers array. The update part is i++, which means that the loop counter variable i is incremented by 1 at the end of each iteration.
In summary, a for loop in Java is a control structure that allows you to iterate over a range of values or over elements in an array or collection. The loop consists of three parts: initialization, condition, and update.

Answer

In Java, you can use the if-else statement to execute different code blocks based on a Boolean condition. Here's the basic syntax of an if-else statement in Java:

if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

The if-else statement consists of two parts:
1. Condition: In this part, you specify a Boolean expression that is evaluated. If the expression is true, the code block inside the if statement is executed; if it's false, the code block inside the else statement is executed.
2. Code blocks: In the if and else blocks, you specify the code that should be executed depending on whether the condition is true or false.
Here's an example of an if-else statement that checks whether a number is positive or negative:

int num = -5;

if (num >= 0) {
    System.out.println("The number is positive");
} else {
    System.out.println("The number is negative");
}

In this example, the condition is num >= 0, which means that the code block inside the if statement will be executed if num is greater than or equal to 0, and the code block inside the else statement will be executed otherwise.
You can also use multiple else if clauses to test for multiple conditions. Here's an example that checks whether a number is positive, negative, or zero:

int num = 0;

if (num > 0) {
    System.out.println("The number is positive");
} else if (num < 0) {
    System.out.println("The number is negative");
} else {
    System.out.println("The number is zero");
}

In this example, the if statement checks whether num is greater than 0, the first else if statement checks whether num is less than 0, and the final else statement is executed if none of the previous conditions are true.
In summary, an if-else statement in Java is a control structure that allows you to execute different code blocks based on a Boolean condition. The statement consists of a condition and two code blocks: one to execute if the condition is true, and one to execute if the condition is false. You can also use multiple else if clauses to test for multiple conditions.

Answer

In Java, a method is a block of code that performs a specific task. A method is designed to be reusable, which means that you can call it from different parts of your program to perform the same task. 
Here's the basic syntax for declaring a method in Java:

access_modifier return_type method_name(parameter_list) {
    // method body
    return return_value;
}

Here's what each part of the method declaration means:
- `access_modifier: This specifies the level of access to the method. The most common access modifiers are public, private, and protected`.
- `return_type: This specifies the data type of the value returned by the method. If the method doesn't return a value, you can use the void` keyword.
- `method_name`: This is the name of the method, which you use to call it from other parts of your program.
- `parameter_list`: This is a list of parameters that are passed to the method when it's called. Each parameter is specified with a data type and a variable name.
- `method body`: This is the code that's executed when the method is called.
- `return_value`: This is the value returned by the method. If the method doesn't return a value, you can omit this part.
To call a method in Java, you use the following syntax:

return_value = method_name(argument_list);

Here's what each part of the method call means:
- `return_value`: This is the value returned by the method, which you can assign to a variable or use in an expression.
- `method_name`: This is the name of the method that you want to call.
- `argument_list`: This is a list of values that are passed to the method as arguments. Each argument must match the data type of the corresponding parameter in the method declaration.
Here's an example of a method in Java that adds two numbers and returns the result:

public int addNumbers(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
}

In this example, the method name is addNumbers, the return type is int, and there are two parameters of type int. The method body adds the two numbers and returns the result.
To call this method, you can use the following code:

int result = addNumbers(5, 10);
System.out.println(result); // output: 15

In this example, the method is called with two arguments (5 and 10), and the result is assigned to a variable named result. Finally, the result is printed to the console.
In summary, a method in Java is a block of code that performs a specific task and is designed to be reusable. To call a method, you use the method name followed by a list of arguments in parentheses. The method can return a value, which you can assign to a variable or use in an expression.

Answer

To read input from the user in Java, you can use the Scanner class, which is part of the Java standard library. Here's an example of how to use the Scanner class to read a line of text from the user:

import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter some text:");
        String userInput = scanner.nextLine();
        System.out.println("You entered: " + userInput);
    }
}

In this example, we first import the Scanner class by including the line import java.util.Scanner; at the top of the file. We then create a new Scanner object and pass System.in as the input source, which represents the standard input stream (i.e., the user's keyboard).
We then prompt the user to enter some text by printing a message to the console using System.out.println(). We then call the nextLine() method on the Scanner object, which reads a line of text from the input stream and returns it as a String. We store the user's input in a variable named userInput.
Finally, we print out the user's input to the console using System.out.println(), along with a message indicating what they entered.
If you wanted to read a different type of input, such as an integer or a floating-point number, you could use the corresponding method on the Scanner object. For example, to read an integer, you could use the nextInt() method:

int userInt = scanner.nextInt();

Or to read a floating-point number, you could use the nextDouble() method:

double userDouble = scanner.nextDouble();

Note that when reading input from the user, you should be careful to handle errors and invalid input gracefully, such as by displaying an error message and prompting the user to try again.

Answer

In Java, an exception is a problem that occurs during the execution of a program, which can cause the program to terminate abnormally if it is not handled properly. To catch and handle an exception in Java, you can use a try-catch block. Here's an example:

try {
    // code that may throw an exception
} catch (ExceptionType e) {
    // code to handle the exception
}

In this example, the try block contains the code that may throw an exception. If an exception of type ExceptionType is thrown, the code in the corresponding catch block will be executed. You can replace ExceptionType with the specific type of exception that you want to catch. For example, to catch an ArithmeticException, you would write:

try {
    int result = 1 / 0;
} catch (ArithmeticException e) {
    System.out.println("An error occurred: " + e.getMessage());
}

In this example, the code in the try block attempts to divide 1 by 0, which will throw an ArithmeticException because division by zero is undefined. The catch block then handles the exception by printing an error message to the console using System.out.println() and displaying the exception's message using e.getMessage().
You can also catch multiple types of exceptions using multiple catch blocks:

try {
    // code that may throw an exception
} catch (ExceptionType1 e) {
    // code to handle ExceptionType1
} catch (ExceptionType2 e) {
    // code to handle ExceptionType2
} catch (Exception e) {
    // code to handle any other type of exception
}

In this example, the first two catch blocks handle specific types of exceptions, while the third catch block handles any other type of exception by catching the base Exception class.
Finally, you can include a finally block after the catch block, which contains code that will be executed regardless of whether an exception was thrown or not:

try {
    // code that may throw an exception
} catch (Exception e) {
    // code to handle the exception
} finally {
    // code that will be executed regardless of whether an exception was thrown or not
}

In this example, the finally block will always be executed, even if an exception was thrown and caught by the catch block. This can be useful for releasing resources, such as closing a file or a database connection.

Answer

In Java, a class is a blueprint or template for creating objects, while an object is an instance of a class. Here are some key differences between classes and objects:
- A class defines the properties and behaviors that objects of that class will have, but does not actually create any objects. To create an object of a class, you must first define a variable of that class type and then use the new keyword to instantiate the object.
- Objects are concrete entities that exist in memory and can be manipulated by a program. Each object has its own set of properties, or instance variables, which can be read and modified by the program.
- Classes are typically used to model concepts or entities in the problem domain, such as a car, a bank account, or a customer. Objects of a class can represent specific instances of that concept, such as a particular car, bank account, or customer.
- Classes can have static members, such as static methods and static variables, which are associated with the class itself rather than with any specific object. Static members can be accessed using the class name, rather than an object reference.
- Objects can have instance methods, which operate on the object's instance variables and may interact with other objects. Instance methods can only be called on an object of the corresponding class.
Here's an example to illustrate the difference between a class and an object:

public class Car {
    private String make;
    private String model;
    private int year;
    
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }
    
    public void startEngine() {
        System.out.println("Starting the " + make + " " + model + "...");
    }
}

public class Example {
    public static void main(String[] args) {
        // create an object of the Car class
        Car myCar = new Car("Toyota", "Corolla", 2022);
        
        // call the startEngine() method on the object
        myCar.startEngine();
    }
}

In this example, we define a Car class that has three instance variables (make, model, and year) and one instance method (startEngine()). We then create an object of the Car class in the main() method using the new keyword and pass in the arguments "Toyota", "Corolla", and 2022 to the constructor. We store the reference to the new object in a variable named myCar.
Finally, we call the startEngine() method on the myCar object using the dot operator (.). This causes the message "Starting the Toyota Corolla..." to be printed to the console. Note that the startEngine() method has access to the make and model instance variables of the myCar object, which were set when the object was created.

Answer

Sure, here's an example Java program that finds the largest and smallest numbers in an array of integers using the bubble sort algorithm:

import java.util.Arrays;

public class FindMinMaxInArray {
    
    public static void main(String[] args) {
        
        int[] arr = {10, 5, 25, 30, 15};
        System.out.println("Array: " + Arrays.toString(arr));
        
        int n = arr.length;
        int temp;
        boolean swapped;
        
        // Bubble sort algorithm to sort the array in ascending order
        for(int i = 0; i < n - 1; i++) {
            swapped = false;
            for(int j = 0; j < n - i - 1; j++) {
                if(arr[j] > arr[j+1]) {
                    temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    swapped = true;
                }
            }
            if(swapped == false)
                break;
        }
        
        // Print the sorted array
        System.out.println("Sorted Array: " + Arrays.toString(arr));
        
        // Find the minimum and maximum numbers in the array
        int min = arr[0];
        int max = arr[n-1];
        
        // Print the minimum and maximum numbers
        System.out.println("Minimum Number: " + min);
        System.out.println("Maximum Number: " + max);
    }
}

In this program, we first initialize an integer array arr with some values. We then sort the array using the bubble sort algorithm, which involves comparing adjacent elements of the array and swapping them if they are in the wrong order. Once the array is sorted in ascending order, we can easily find the minimum and maximum numbers in the array by looking at the first and last elements, respectively. Finally, we print out the sorted array, as well as the minimum and maximum numbers.
Note that there are more efficient algorithms than bubble sort for sorting an array, but we chose to use bubble sort for simplicity.

Answer preview

In Java, access modifiers are keywords that specify the level of access that other parts of the program have to a particular class, method, or variable. There are four different access modifiers in Java: 1. `public`: This is the most permissive access modifier. A public class, method, or variable can be accessed from…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, runtime errors are commonly referred to as "exceptions". When an exception occurs during the execution of a Java program, it causes the program to terminate unless the exception is handled in some way. Here are the basic steps for handling exceptions in Java: 1. Use a try-catch block: A try-catch block is…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Here is an example of a Java-based web application that uses servlets, JSP, and JDBC to interact with a database: 1. Create a database table called "users" with the following columns: "id", "username", "password", and "email". 2. Create a Java class called "User" that represents a user object, with the following…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, an abstract class is a class that cannot be instantiated, but can be subclassed. Abstract classes are used to provide a common interface for a group of related classes, and to define abstract methods that must be implemented by the subclasses. Here are the basic steps for creating and using an abstract class…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit properties and behaviors from another class. In Java, a subclass can inherit fields, methods, and inner classes from a superclass, which is achieved through the use of the `extends` keyword. To illustrate how…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure, here is an example Java program that reads and writes data to a file using serialization and deserialization. The program creates a class called Person and writes a list of Person objects to a file using serialization. It then reads the data back from the file and prints it to the console using deserialization…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Java provides three different types of loops: `for`, `while`, and `do-while`. Each type of loop is designed for a specific purpose and can be used in different situations. Here is an overview of each type of loop: 1. **for loop:** A `for` loop is typically used when you know the number of times you want to repeat a…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, a `static` method is a method that belongs to a class rather than to an instance of the class. This means that you can call a static method directly on the class itself, without having to create an instance of the class.  Here's an example of a static method: To call this method, you can use the class name…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure! Here's an example of a Java-based calculator that can perform basic arithmetic operations: This program first prompts the user to enter two numbers and an operator. Then, it uses a switch statement to determine which operation to perform on the two numbers, and stores the result in a result variable. Finally, it…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, a `try-catch-finally` block is used to handle exceptions. Here's an example of how to implement a `try-catch-finally` block: In this example, the `try` block contains code that might throw an exception (in this case, dividing by zero). If an exception is thrown, the `catch` block will handle it by printing an…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, a constructor is a special type of method that is used to initialize objects of a class. When you create a new object using the `new` keyword, the constructor is automatically called to initialize the object's state. Here's an example of how to create a constructor in Java: In this example, the `MyClass`…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, the `this` keyword is used to refer to the current object instance within a class. It can be used in a number of ways, including: 1. To reference an instance variable:    In this example, the `this` keyword is used to disambiguate the instance variable `myNumber` from the parameter `myNumber`. 2. To invoke a…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, the `super` keyword is used to refer to the parent class of a subclass. It can be used in a number of ways, including: 1. To call a constructor in the parent class:    In this example, the `MyClass` constructor invokes the constructor in the `ParentClass` by calling `super(myNumber)`. 2. To reference a method…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Polymorphism is the ability of an object to take on multiple forms. In Java, polymorphism is achieved through method overriding and method overloading. Method overriding is when a subclass provides a specific implementation of a method that is already defined in its parent class. When a method is called on an object…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Multithreading in Java allows multiple threads to execute concurrently within a single program. Each thread runs independently and can perform different tasks simultaneously. Here is an example of implementing multithreading in Java: In this example, we create a subclass of `Thread` called `MyThread`, which takes an…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure! Here's an example of a multithreaded Java program that simulates a simple chat application: In this example, the ChatApplication class has a messageQueue field that is used to store messages sent by the sender and received by the receiver. The start() method creates two threads: one for the sender and one for…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Design patterns in Java are general, reusable solutions to commonly occurring problems in software design. They provide a way to standardize best practices and solutions that have proven to be effective in solving specific types of problems. Design patterns are typically divided into three categories: creational…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure! The singleton pattern is a design pattern that restricts the instantiation of a class to a single instance and provides a global point of access to that instance. To implement the singleton pattern in Java, you can follow these steps: 1. Create a private constructor to prevent direct instantiation of the class…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

To build a RESTful API in Java that interacts with a database and provides CRUD operations, you can follow these general steps: 1. Choose a web framework to build the API. Some popular options include Spring Boot, Spark, and Play Framework. 2. Set up the database connection. You can use a JDBC driver to connect to a…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, a stack and a queue are both data structures used to store collections of elements. However, they differ in the order in which elements are added and removed from the collection. A stack is a last-in, first-out (LIFO) data structure. This means that the last element added to the stack is the first element to…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Generics in Java are a powerful feature that allow you to write code that can work with different data types, without sacrificing type safety. Generics allow you to parameterize classes, interfaces, and methods with one or more type parameters. These type parameters can then be used throughout the code to specify the…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, both `StringBuilder` and `StringBuffer` are used to represent mutable sequences of characters. However, there are some key differences between the two: 1. Thread-safety: `StringBuffer` is thread-safe, which means that multiple threads can access and modify the same object without any problems. On the other…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure! Here's an example Java program that performs some basic string manipulations: This program initializes a sample string and performs several manipulations on it, such as converting it to uppercase, checking if it contains a specific character, replacing a character, splitting it into an array of substrings…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure! Here's an example implementation of a binary search algorithm in Java: This implementation takes an array of integers `arr` and a search key `key` as parameters. It returns the index of the search key in the array if it is present, or -1 if it is not. The algorithm starts by setting the left and right indices to…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, both HashMap and TreeMap are used to store data as key-value pairs. However, they differ in their implementation and performance characteristics. HashMap uses hashing to store the key-value pairs, which makes it faster for adding, removing, and accessing elements on average. It does not guarantee any order of…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure! Here's an example implementation of a singly linked list in Java: In this example, the `Node` class represents a single node in the linked list, which contains a data value and a reference to the next node in the list. The `LinkedList` class contains a reference to the head node of the list and provides methods…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Annotations in Java provide a way to associate metadata with various parts of a Java program, such as classes, methods, variables, and parameters. Annotations can be used to provide additional information that can be used by the compiler, runtime environment, or other tools. Annotations are defined using the @ symbol…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Memory leaks in Java occur when objects that are no longer needed are not properly removed from memory, leading to a buildup of unused objects and eventual exhaustion of available memory. Here are some ways to handle memory leaks in Java: 1. Use garbage collection: The Java virtual machine includes a garbage collector…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, a set is a collection that contains only unique elements, whereas a list is a collection that can contain duplicate elements. The main difference between the two is that a set enforces uniqueness, whereas a list does not. Here are some scenarios where you might choose to use a set over a list: - When you want…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

To develop a Java-based GUI application, we can use the Swing framework, which is a set of Java classes that provide a toolkit for creating graphical user interfaces. Here is an example of a simple Swing application that includes a button, a label, and an action listener: In this example, we extend the JFrame class to…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure, here's an example of how to implement a binary tree in Java: In this example, we have defined a `Node` class with an integer `key` value and left and right child `Node`s. We then define a `BinaryTree` class with a `root` `Node` and methods for inserting a new `Node` into the tree, performing an inorder…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Java, both the `Comparable` and `Comparator` interfaces are used for sorting objects, but they differ in how they sort. The `Comparable` interface is used to define the natural order of an object. When a class implements the `Comparable` interface, it is saying that the objects of that class can be compared to each…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Serialization is the process of converting an object into a stream of bytes so that it can be stored in a file, a database, or sent over a network. The reverse process of converting a stream of bytes back into an object is called deserialization. In Java, the Serializable interface is used to indicate that a class can…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Concurrency refers to the ability of a program to execute multiple threads simultaneously. In Java, concurrency can lead to issues such as race conditions and deadlock if not handled properly. Here are some ways to handle concurrency issues in Java: 1. Synchronization: Synchronization is a mechanism provided by Java…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Here's an example of implementing a stack data structure in Java: This implementation of a stack data structure in Java includes the basic operations of push, pop, peek, isEmpty, and size. It uses a generic type parameter to allow the stack to hold any type of data. The stack is implemented using a linked list with a…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

More practice

Go further with Java

Java code challenges

10 challenges with answers

Behavioral Questions

10 questions with answers

Cultural Fit Questions

10 questions with answers

Competency-Based Questions

10 questions with answers

Motivational Questions

10 questions with answers

Communication Skills Questions

10 questions with answers

Scenario-Based Questions

10 questions with answers

Problem-Solving and Analytical Questions

10 questions with answers

Ethical and Integrity Questions

10 questions with answers

Industry-Specific Questions

10 questions with answers

Leadership and Management Questions

10 questions with answers

Personal Questions

10 questions with answers

About this topic

Java interview questions and answers

This page lists 45 Java interview questions with answers, ordered from junior to senior level. Commonly asked questions include "What is Java and how is it different from other programming languages?", "Implement a linked list in Java, including features such as node insertion, deletion, and traversal." and "How do you declare and initialize a variable in Java?".

Other frequently asked questions include "How do you write a conditional statement (if-else) in Java?", "What is a method in Java and how do you call one?" and "What are the different access modifiers in Java and how do they differ?". Review each answer and consider how you would adapt it to your own experience.

Practise Java in a mock interview

Answer questions one at a time and receive a score with written feedback on each answer.

Start a mock interview

Reviews and comments