0% found this document useful (0 votes)
2 views

Java Jitters? Crack Interviews with These Hot Questions!

This document contains a compilation of the top 50 Java interview questions and answers, covering fundamental concepts such as Java's features, differences between JDK, JRE, and JVM, and the use of keywords like 'final' and 'this'. It also addresses advanced topics like multithreading, synchronization, and the Java Memory Model, providing code examples for clarity. The document serves as a comprehensive guide for individuals preparing for Java-related interviews.

Uploaded by

yashika.nigam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Jitters? Crack Interviews with These Hot Questions!

This document contains a compilation of the top 50 Java interview questions and answers, covering fundamental concepts such as Java's features, differences between JDK, JRE, and JVM, and the use of keywords like 'final' and 'this'. It also addresses advanced topics like multithreading, synchronization, and the Java Memory Model, providing code examples for clarity. The document serves as a comprehensive guide for individuals preparing for Java-related interviews.

Uploaded by

yashika.nigam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

JAVA

TOP 50

INTERVIEW Questions
1 what is java

Java is a high-level, object-oriented programming

language developed by Sun Microsystems. It is known for

its platform independence, as Java code can run on any

platform with a Java Virtual Machine (JVM).

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

What is the difference between JDK,


2
JRE, and JVM?

JDK (Java Development Kit) is used for Java application

development,

JRE (Java Runtime Environment) is used to run Java applications,

JVM (Java Virtual Machine) executes Java bytecode.

// JDK contains the tools needed for development

// JRE is used to run Java applications

public class Main {

public static void main(String[] args) {

System.out.println("JDK vs. JRE");

Curated by
3 Explain the main features of Java.

Java features include platform independence, object-

oriented, robust, secure, multithreaded, and high-

performance.

// Example of platform independence

public class PlatformIndependent {

public static void main(String[] args) {

System.out.println("Hello, World!");

From To

Success

Gautam Verma Story

Curated by
What are the differences between
4
abstract classes and interfaces?

Abstract classes can have constructors, fields, and

method implementations, while interfaces only define

method signatures. A class can extend only one abstract

class but implement multiple interfaces.

abstract class Animal {

String name;

Animal(String name) {

this.name = name;

abstract void sound();

interface Flyable {

void fly();

Tutort Provides 1:1 Mentorship from Industry experts

Curated by
How does Java achieve platform
5
independence?

Java achieves platform independence by compiling


source code into bytecode, which is then executed by the
JVM specific to the platform.

// Java source code

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

6 Explain the 'final' keyword in Java.

The 'final' keyword is used to declare variables, methods, or classes


as unchangeable. A 'final' variable cannot be reassigned, a 'final'
method cannot be overridden, and a 'final' class cannot be extended.

final class FinalClass {

final int constantValue = 42;

final void doSomething() {

// Implementation

Curated by
What is the difference between
7 'equals()' and '=='

in Java?

'==' compares object references, while 'equals()'


compares the content (values) of objects. You can
override 'equals()' to provide custom comparison logic.

String str1 = new String("Hello");

String str2 = new String("Hello");

boolean referenceComparison = (str1 == str2); // false (different


objects)

boolean contentComparison = str1.equals(str2); // true (same


content)

8 What is a constructor, and why is


it used in Java?

A constructor is a special method used to initialize objects. It is called

when an object is created and ensures that the object is in a valid


state.

class Person {

String name;

// Constructor

Person(String name) {

this.name = name;

Curated by
9 What is the 'this' keyword in Java?

'this' refers to the current object within a class. It is often


used to distinguish between instance variables and
method parameters with the same name.

class MyClass {

int value;

MyClass(int value) {

this.value = value; // 'this' refers to the

instance variable

Explain method overloading and


10
method overriding in Java.

Method overloading is when multiple methods in the same class have


the same name but different parameters. Method overriding occurs
when a subclass provides a specific implementation for a method
defined in its superclass.

class MathOperations {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

Curated by
11 What is a static method and when
is it used?

A static method belongs to the class rather than an


instance. It can be called using the class name and is often
used for utility functions that don't require instance-
specific data.

class MathUtils {

static int add(int a, int b) {

return a + b;

What is the 'super' keyword in


12
Java?

'super' is used to call a superclass's constructor or refer to a


superclass's method or variable in the context of method overriding.

class Parent {

void show() {

System.out.println("Parent class");

class Child extends Parent {

void show() {

super.show(); // Calls the parent's 'show'

method

System.out.println("Child class");

Curated by
Explain the 'try-catch-finally'
13 block in Java for

exception handling.

'try' is used to enclose code that might throw an exception, 'catch' is


used to handle exceptions, and 'finally' is used to specify code that will
always execute, whether an exception occurs or no

try {

// Code that might throw an exception

int result = 10 / 0;

} catch (ArithmeticException e) {

// Handle the exception

System.out.println("Error: " + e.getMessage());

} finally {

// Cleanup code (always executed)

System.out.println("Cleanup code");

From To
Success
Shailja Barsaiyan Story

Curated by
What is the difference between
14 checked and unchecked
exceptions?

Checked exceptions are checked at compile-time and must be either

caught or declared in the method signature using 'throws.' Unchecked

// Checked exception (must be handled or

declared)

try {

FileInputStream file = new

FileInputStream("file.txt");

} catch (FileNotFoundException e) {

System.out.println("File not found.");

// Unchecked exception (no need to declare or

catch)

int result = 10 / 0; // ArithmeticException

Curated by
15 Describe the 'NullPointerException'
and how to prevent it.

'NullPointerException' occurs when trying to access methods or fields


of a null object. To prevent it, ensure that object references are not
null before accessing them.

String name = null;

if (name != null) {

int length = name.length(); // Check for null

before accessing

Courses Offered by Tutort Academy

Data Structures and Full Stack Specialisation



Algorithms
 In Software
with System Design Development

Learn more Learn more

Curated by
16 What is the purpose of the 'finally'
block in exception handling?

The 'finally' block is used to ensure that essential cleanup code


executes, such as closing files or releasing resources, regardless of
whether an exception occurs or not.

FileInputStream file = null;

try {

file = new FileInputStream("file.txt");

// Code to read the file

} catch (IOException e) {

System.out.println("Error reading the file.");

} finally {

// Close the file, even if an exception occurs

try {

if (file != null) {

file.close();

} catch (IOException e) {

System.out.println("Error closing the file.");

Curated by
What is the Java Collections
17 Framework, and why is it
important?

The Java Collections Framework provides a set of classes and


interfaces for working with collections of objects. It's essential for
efficient data manipulation and storage in Java applications.

// Example of using ArrayList from the Collections

Framework

import java.util.ArrayList;

import java.util.List;

public class CollectionExample {

public static void main(String[] args) {

List<String> names = new ArrayList<>();

names.add("Alice");

names.add("Bob");

names.add("Charlie");

System.out.println(names);

Tutort Provides Dedicated Placement Team

Curated by
18 Explain the difference between
ArrayList and LinkedList.

ArrayList is a dynamic array that allows fast random access, while

LinkedList is a doubly-linked list that is better suited for frequent


insertions and deletions.

import java.util.ArrayList;

import java.util.LinkedList;

import java.util.List;

public class ListExample {

public static void main(String[] args) {

List<String> arrayList = new ArrayList<>();

List<String> linkedList = new LinkedList<>();

// ArrayList is good for random access

arrayList.add("A");

arrayList.add("B");

arrayList.add("C");

System.out.println(arrayList.get(1)); // Output:

// LinkedList is good for insertions and

deletions

linkedList.add("X");

linkedList.add("Y");

linkedList.add("Z");

linkedList.remove(1); // Removes "Y"

Curated by
19 What is the 'hashCode()' method
used for in Java?

'hashCode()' is used to calculate the hash code of an object,


primarily used in data structures like HashMap and HashSet for
efficient storage and retrieval.

class Student {

String name;

int id;

// Override hashCode() method

@Override

public int hashCode() {

return Objects.hash(name, id);

Curated by
How does Java handle multiple
20 threads, and what are the
potential issues with
multithreading?

Java supports multithreading through the 'Thread' class and the

'Runnable' interface. Potential issues include race conditions,


deadlocks, and thread interference, which must be managed using
synchronization.

class MyThread extends Thread {

public void run() {

// Thread's logic

class MyRunnable implements Runnable {

public void run() {

// Runnable's logic

From To
Success
Akansha Likhdari Story

Curated by
21 What is synchronization in Java,
and how is it achieved?

Synchronization is used to ensure that only one thread accesses a


block of code or a method at a time. It can be achieved using the
'synchronized' keyword or by using synchronized blocks.

class SynchronizedExample {

private int count = 0;

// Synchronized method

synchronized void increment() {

count++;

// Synchronized block

void performTask() {

synchronized (this) {

// Code that needs synchronization

Curated by
22 Explain the 'volatile' keyword in
Java.

'volatile' is used to declare a variable as "volatile," meaning its value


can be modified by multiple threads. It ensures that the variable's
value is always read from and written to the main memory, avoiding
thread caching.

class SharedResource {

volatile int value = 0;

Courses Offered by Tutort Academy

Data Structures and Full Stack Specialisation



Algorithms
 In Software
with System Design Development

Learn more Learn more

Curated by
What is the 'thread-safe' concept
23 in Java, and how can you make a
class thread-safe?

A thread-safe class ensures that its methods can be safely used by

multiple threads without causing data corruption or inconsistencies.


You can make a class thread-safe by using synchronization, locks, or

concurrent data structures.

import java.util.concurrent.atomic.AtomicInteger;

class Counter {

private AtomicInteger count = new

AtomicInteger(0);

// Thread-safe increment

void increment() {

count.incrementAndGet();

Curated by
Explain the 'wait' and 'notify'
24 methods in Java for thread
synchronization.

'wait' is used to make a thread pause execution until another thread


invokes 'notify' or 'notifyAll' on the same object, waking up the waiting
thread(s).

class SharedResource {

synchronized void produce() {

// Produce some data

notify(); // Notify waiting threads

synchronized void consume() throws

InterruptedException {

wait(); // Wait for data to be available

// Consume the data

Curated by
What is the Java Memory Model
25 (JMM), and how does it relate to
multithreading?

JMM defines how threads interact with memory and how changes to

variables are visible to other threads. It ensures that the JVM respects
the memory visibility guarantees.

class SharedResource {

private volatile int value = 0;

void increment() {

value++;

int getValue() {

return value;

1250+ Career
Transitions 350+ Hiring

Partners 2.1CR Highest

CTC

One of the best institutes for getting started with DSA and System Design.
Placed at It also assisted me in launching my technical career and in honing my
problem-solving and coding abilities. I was placed in more than 6+
product based companies because of their constant support.
Ajay Kumar

Curated by
26 What is the 'garbage collection' in
Java, and how does it work?

Answer: Garbage collection is the automatic process of identifying

and reclaiming memory occupied by objects that are no longer

referenced. Java uses different garbage collection algorithms like

generational, mark-and-sweep, and G1.

class MyClass {

// Object creation

public void createObject() {

SomeObject obj = new SomeObject();

// obj goes out of scope and becomes

eligible for garbage collection

Curated by
Explain the 'finalize()' method in
27
Java.

'finalize()' is a method called by the garbage collector before an


object is reclaimed. It allows you to perform cleanup operations on
resources like files or sockets.

class Resource {

// Clean up resources in the finalize() method

protected void finalize() {

// Close files, release resources, etc.

What is the purpose of the 'assert'


28
statement in Java ?

The 'assert' statement is used to test assumptions about program

behavior. It throws an AssertionError if the condition specified is false.

int value = 10;

assert value > 0 : "Value must be positive";

// Throws AssertionError if false

Curated by
Describe the 'enum' type in Java and
29
its advantages.

An 'enum' is a special data type that defines a set of constant values.


It provides type safety, readability, and can be used in switch
statements.

enum Day {

SUNDAY, MONDAY, TUESDAY, WEDNESDAY,

THURSDAY, FRIDAY, SATURDAY

What is the 'autoboxing' and


30
'unboxing' feature in Java?

Autoboxing is the automatic conversion of a primitive type to its

corresponding wrapper class, and unboxing is the reverse process.


For example, converting 'int' to 'Integer' and vice versa.

Integer num = 42; // Autoboxing

int value = num; // Unboxing

Curated by
What are Java annotations, and
31
how are they used?

Annotations provide metadata about the code and can be used to


add information to classes, methods, or variables. They are
commonly used for configuration, documentation, and code
generation.

@Override

public void performTask() {

// Method implementation

@Deprecated

public void oldMethod() {

// Deprecated method

Explain the 'try-with-resources'


32 statement in Java

for resource management.

'try-with-resources' is used to automatically close resources like files,

sockets, or database connections when they are no longer needed. It

simplifies resource management and prevents resource leaks.

try (FileInputStream file = new

FileInputStream("file.txt")) {

// Read and process the file

} catch (IOException e) {

// Handle exceptions

Curated by
How does Java support functional
33 programming, and what are
lambda expressions?

Java supports functional programming through lambda expressions,


which allow you to define and pass functions as arguments to
methods. They are used for writing more concise and expressive
code.

// Using a lambda expression to define a function

Function<Integer, Integer> square = (x) -> x * x;

int result = square.apply(5); // Result is 25

What is the 'Stream' API in Java, and


34 how is it used for data
manipulation?

The 'Stream' API is used for processing sequences of data in a


functional style. It provides methods for filtering, mapping, reducing,
and collecting data efficiently.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

int sum = numbers.stream()

.filter(n -> n % 2 == 0)

.mapToInt(Integer::intValue)

.sum();

Curated by
35 Explain the 'Optional' class in Java
and its purpose.

'Optional' is a container class that can contain either a non-null value


or be empty. It is used to avoid null pointer exceptions and indicate
that a value may or may not be present.

Optional<String> optionalName =

Optional.ofNullable(getName());

String result = optionalName.orElse("Default

Name");

What is the 'StringBuilder' class,


36 and how does it differ from
'String'?

'StringBuilder' is a mutable sequence of characters, while 'String' is

immutable. 'StringBuilder' is used for efficient string manipulation


without creating new objects.

StringBuilder sb = new StringBuilder();

sb.append("Hello, ");

sb.append("World!");

String result = sb.toString(); // "Hello, World!"

Curated by
37 What is a Java annotation
processor, and how does it work?

An annotation processor is a tool that reads and processes


annotations at compile-time. It can generate code, perform
validation, or enhance classes based on annotations.

@MyAnnotation

public class MyClass {

// Annotation-processed code

38 What is serialization in Java, and


how is it implemented?

Serialization is the process of converting an object into a stream of


bytes to store it or transmit it over a network. It is implemented by
making a class implement the 'Serializable' interface.

class Student implements Serializable {

String name;

int rollNumber;

// ...

Curated by
39 Explain the 'Reflection' API in Java.

The 'Reflection' API allows you to inspect and manipulate classes,


methods, fields, and objects at runtime. It is often used for dynamic
code generation and testing.

Class<?> clazz =

Class.forName("com.example.MyClass");

Field[] fields = clazz.getDeclaredFields();

// Use reflection to inspect or modify fields/

methods

40 What is the difference between an


'inner class' and a 'nested class'?

An inner class is a non-static class defined within another class, while


a nested class is any class defined within another class. Inner classes
have access to the enclosing class's members.

class Outer {

int outerValue;

class Inner {

int innerValue = outerValue;

Curated by
What is the 'Executor' framework
41 in Java, and how does it simplify
thread management?

The 'Executor' framework provides a higher-level abstraction for


managing threads. It decouples the task submission from the thread
creation and management, making it easier to control thread
execution.

Executor executor =

Executors.newFixedThreadPool(2);

executor.execute(() -> System.out.println("Task

executed."));

What are the 'Comparable' and


42 'Comparator' interfaces, and when
are they used?

'Comparable' is used to define the natural ordering of objects within a

class, while 'Comparator' allows you to define custom comparison


logic for classes not under your control.

class Student implements Comparable<Student> {

String name;

int rollNumber;

@Override

public int compareTo(Student other) {

return this.rollNumber - other.rollNumber;

Curated by
43 Explain the 'fork-join' framework
in Java for parallel processing.

The 'fork-join' framework is used for parallelism in Java, particularly


for divide-and-conquer algorithms. It uses a pool of worker threads to
execute tasks concurrently.

ForkJoinPool pool = new ForkJoinPool();

long result = pool.invoke(new MyRecursiveTask(1,

1000));

What is 'Project Loom,' and how


44 does it impact Java's concurrency
model?

Project Loom aims to simplify and improve concurrency in Java by

introducing lightweight, user-mode threads called 'Fibers.' It promises


more efficient and scalable concurrency.

import java.util.concurrent.Executors;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.ForkJoinPool;

import java.util.concurrent.Future;

public class FiberExample {

public static void main(String[] args) {

ExecutorService executor =

Executors.newVirtualThreadPerTaskExecutor();

Future<String> future = executor.submit(() ->

"Hello from a Fiber!");

Curated by
What is 'Project Valhalla,' and how
45 does it aim to enhance Java's
performance?

Project Valhalla aims to introduce value types and reified generics to


Java, improving memory efficiency and performance for certain data
structures.

value class Point {

int x;

int y;

Explain 'Project Panama' and how


46 it improves Java's interaction with
native code.

Project Panama focuses on improving the connection between Java


and native code, making it easier to interoperate with libraries written
in other languages like C and C++.

// Example of Java Native Interface (JNI) with native

C code

public class NativeExample {

native void nativeMethod();

Curated by
What is 'Project Metropolis,' and
47 how does it aim to improve Java's
memory management and
performance?

As of my last update in September 2021, Project Metropolis was not a


well- known project. Please refer to the latest Java documentation or
resources for any updates regarding this project.

What is 'Project Valhalla,' and how


48 does it aim to enhance Java's
performance?

Project Panama focuses on improving the connection between Java


and native code, making it easier to interoperate with libraries written
in other languages like C and C++.

What is 'Project Panama,' and how


48
49 does it improve Java's interaction
with native code?

Project Panama focuses on improving the connection between Java


and native code, making it easier to interoperate with libraries written
in other languages like C and C++.

Curated by
How does 'Project Metropolis' aim
50
48 to improve Java's memory
management and performance?

As of my last update in September 2021, Project Metropolis was not a


well-known project. Please refer to the latest Java documentation or
resources for any updates regarding this project.

Why Tutort Academy?

1250+ Career
Transitions 350+ Hiring

Partners 2.1CR Highest

CTC

I really want to thank Tutort Academy from bottom of my heart for helping me
brushing up system design, data structures and algorithms for the Google
Gunjan interview preparation.

Curated by
Start Your
Upskilling with us
Explore our courses

Data Structures and Full Stack Specialisation



Algorithms
 In Software
with System Design Development

www.tutort.net

Watch us on Youtube Read more on Quora

Follow us on

You might also like