0% found this document useful (0 votes)
7 views24 pages

Java Interview Question & Answers Top 100

Uploaded by

freezefrozen2004
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)
7 views24 pages

Java Interview Question & Answers Top 100

Uploaded by

freezefrozen2004
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/ 24

Q1: What is Java?

A: Java is a high-level, object-oriented programming language. When compiled, Java code is


converted into bytecode, which is then interpreted and executed by the Java Virtual
Machine (JVM), making Java platform-independent. Java supports core object-oriented
principles like encapsulation, inheritance, polymorphism, and abstraction.

Q2: What are JDK, JRE, and JVM?

A:

 JDK (Java Development Kit): A software development kit that includes tools like the
compiler (javac) for developing Java programs.

 JRE (Java Runtime Environment): A part of the JDK that includes libraries and the
JVM needed to run Java programs.

 JVM (Java Virtual Machine): A virtual machine that runs Java bytecode by converting
it into machine code. It manages memory, handles threads, and executes the
program at runtime.

Q3: How is a Java program compiled and executed?

A: The Java source code (.java file) is first compiled by the Java Compiler into bytecode (.class
file). This bytecode is then executed by the JVM, which converts it into machine-specific
code using a Just-In-Time (JIT) compiler.

Q4: What is Compile Time vs Runtime in Java?

A:

 Compile Time: When the Java code is checked for syntax errors and converted into
bytecode by the compiler.

 Runtime: When the JVM executes the bytecode and converts it to native code.
Runtime errors (like NullPointerException) are detected here.

Q5: What are the main features of Java?

A:

 Platform Independent
 Object-Oriented

 Robust and Secure

 Supports Multithreading

 Rich Standard Library

Q6: How is Java platform independent?

A: Java code is compiled into bytecode, which is a platform-independent intermediate


format. This bytecode can run on any system that has a compatible JVM installed, regardless
of the underlying OS (Windows, Linux, Mac).

Q7: What is the main() method in Java? What do public, static, and void mean?

A:

 public – Allows the JVM to access the main() method from outside the class.

 static – Enables the JVM to call the method without creating an object.

 void – Indicates that the method doesn’t return any value.

 main(String[] args) – Entry point of the program; receives command-line arguments.

Q8: What is Java Bytecode?

A: Java bytecode is the intermediate representation of Java code. It is generated by the Java
compiler and is executed by the JVM. Bytecode is platform-independent and is stored in
.class files.

Q9: What are high-level and low-level languages in the context of Java?

A:

 High-Level Language: Java source code is written in a human-readable form.

 Intermediate Level: Bytecode generated by the compiler.

 Low-Level (Native) Code: Machine-specific code produced by the JVM from bytecode
for execution.

Q10: What are variables and data types in Java?


A:

 Variable: A container used to store data.

 Data Types: Define the type of data a variable holds.

o Primitive Types: int, float, char, boolean, etc.

o Reference Types: String, arrays, classes, interfaces.

Q11: What is the difference between primitive and reference data types in Java?

A:

 Primitive Data Types: Store actual values directly in memory (e.g., int, float, char,
boolean).

 Reference Data Types: Store the reference (address) to the value in memory (e.g.,
String, arrays, objects).

 Memory Usage:

o Primitives are stored in the stack memory.

o References point to objects stored in heap memory.

Q12: What are the types of operators in Java?

A:

1. Arithmetic Operators: +, -, *, /, %

2. Assignment Operators: =, +=, -=, etc.

3. Comparison (Relational) Operators: ==, !=, >, <, >=, <=

4. Logical Operators: &&, ||, !

5. Unary Operators: ++, --, +, -

6. Ternary Operator: ? :

7. instanceof Operator

Q13: What are control statements in Java?

A: Control statements manage the flow of execution in a program:

 Conditional: if, else if, else, switch

 Looping: for, while, do-while, for-each


 Branching: break, continue, return

Q14: What’s the difference between if-else, switch, and ternary operator?

A:

 if-else: Best for complex conditions and multi-line execution.

 switch: Better for cleaner comparison with multiple fixed values.

 ternary: Shortest syntax, good for simple conditions (e.g., a > b ? x : y).

Q15: What is OOP (Object-Oriented Programming)?

A: A paradigm based on "objects" which encapsulate data and behavior.


Core Concepts:

1. Encapsulation

2. Inheritance

3. Polymorphism

4. Abstraction

5. Classes & Objects

Q16: What is a Class and an Object in Java?

A:

 Class: A blueprint or template for creating objects (e.g., Employee).

 Object: An instance of a class containing actual data and methods (e.g., Employee
emp = new Employee();).

Q17: What are the members of a class?

A:

 Fields (Variables): Hold data.

 Constructors: Special methods called when objects are created.

 Methods (Functions): Define behavior or logic.

Q18: What is the role of packages in Java?


A: Packages are used to group related classes and interfaces together, providing namespace
management and avoiding name conflicts.

Q19: What is the difference between compile-time and runtime errors?

A:

 Compile-Time Errors: Detected by the compiler (e.g., syntax errors).

 Runtime Errors: Detected during execution (e.g., NullPointerException).

Q20: What are the main control statement categories in Java?

A:

 Conditional Statements: if, else if, else, switch

 Looping Statements: for, while, do-while, for-each

 Branching Statements: break, continue, return

Q21: What are Conditional Statements in Java?

A: Conditional statements are used to make decisions in code:

 if – Executes a block if a condition is true.

 else if – Adds multiple conditions.

 else – Executes when no previous condition is true.

Q22: What is a switch statement in Java?

A: switch is a control statement that matches a variable's value against multiple case
options.
Syntax:

java

CopyEdit

switch (value) {

case 1: // code

break;

default: // code
}

Q23: What are Looping Statements in Java?

A: Used to repeat a block of code multiple times:

 for – Runs for a fixed number of iterations.

 while – Runs while a condition is true.

 do-while – Executes the loop body at least once.

Q24: What is the difference between while and do-while loops?

A:

 while: Condition is checked before executing the loop body.

 do-while: Loop body is executed at least once before checking the condition.

Q25: When to use for, while, and do-while loops?

A:

 Use for loop when number of iterations is known.

 Use while loop when condition-only logic is needed.

 Use do-while loop when code must run at least once regardless of condition.

Q26: What is the difference between for loop and for-each loop?

A:

 for loop: Gives full control using index-based iteration.

 for-each loop: Simplified version for iterating over arrays or collections without using
index.

java

CopyEdit

for (int num : numbers) {

System.out.println(num);

}
Q27: What is the use of the break statement in Java?

A: The break statement terminates the loop or switch block prematurely when a condition is
met.

Q28: What is the use of the continue statement in Java?

A: continue skips the current iteration of the loop and jumps to the next cycle.

Q29: What is the ternary (conditional) operator in Java?

A: A shorthand for if-else conditions.

java

CopyEdit

int max = (a > b) ? a : b;

It evaluates a Boolean condition and returns one of two values.

Q30: What is the instanceof operator in Java?

A: Used to check if an object is an instance of a specific class or subclass.

java

CopyEdit

if (obj instanceof String) { ... }

Q31: What are the types of memory in Java?

A:

 Stack Memory: Stores method calls and primitive/local variables.

 Heap Memory: Stores objects and reference data types.

 Method Area & MetaSpace: Stores class-level structures like metadata.

 Garbage-Collected Heap: Managed by the JVM.

Q32: What is the difference between Stack and Heap memory?


A:

 Stack: Stores primitive data types and references. Managed per thread.

 Heap: Stores actual object values and is shared across all threads.

Q33: What is Garbage Collection in Java?

A: The automatic process of deallocating memory by removing unreachable objects from the
heap. JVM handles this with no need for explicit memory management.

Q34: What are Constructors in Java?

A: Special methods used to initialize objects. They:

 Have the same name as the class.

 Do not have a return type.

 Are invoked using new.

Q35: What is Constructor Overloading in Java?

A: Defining multiple constructors in the same class with different parameters:

java

CopyEdit

Employee() { ... }

Employee(String name) { ... }

Q36: What is the this keyword in Java?

A: this refers to the current class instance. It helps:

 Distinguish between class variables and method parameters.

 Call one constructor from another (this()).

Q37: What is the difference between this and super?

A:

 this: Refers to current class object.


 super: Refers to the immediate parent class object (used to access overridden
methods/constructors).

Q38: What is Method Overloading?

A: Defining multiple methods with the same name but different parameters in the same
class.

java

CopyEdit

void print(int a);

void print(String s);

Q39: What is Method Overriding?

A: Redefining a parent class method in a child class with the same signature.

 Used in inheritance.

 Allows runtime polymorphism.

Q40: What is the difference between Overloading and Overriding?

A:

Feature Overloading Overriding

Inheritance Not required Requires inheritance

Parameters Must differ Must be same

Runtime/Compile Compile-time Runtime

Q41: What is Inheritance in Java?

A: Inheritance is a mechanism where one class (child/subclass) acquires properties and


behaviors (fields and methods) from another class (parent/superclass).
Example:

java

CopyEdit

class Animal { void sound() {} }


class Dog extends Animal { void bark() {} }

Q42: What are the types of Inheritance in Java?

A:

1. Single Inheritance

2. Multilevel Inheritance

3. Hierarchical Inheritance
(Note: Java doesn’t support multiple inheritance with classes to avoid ambiguity;
interfaces are used instead.)

Q43: What is Polymorphism in Java?

A: The ability of an object to take many forms. Two types:

 Compile-time (Method Overloading)

 Runtime (Method Overriding)

Q44: What is Abstraction in Java?

A: Abstraction hides internal details and shows only functionality.


Achieved using:

 Abstract classes

 Interfaces

Q45: What is Encapsulation in Java?

A: Wrapping data and methods into a single unit (class).


Achieved by:

 Declaring variables private

 Providing public getters/setters

Q46: What is an Abstract Class in Java?

A: A class that cannot be instantiated and may contain abstract (unimplemented) methods
as well as concrete methods.
Used to provide a common base for subclasses.
java

CopyEdit

abstract class Animal {

abstract void makeSound();

Q47: What is an Interface in Java?

A: A contract that defines method signatures but not implementations (until Java 8).
A class implements an interface to provide concrete behavior.

java

CopyEdit

interface Flyable {

void fly();

Q48: Difference between Abstract Class and Interface?

Feature Abstract Class Interface

Methods Can have both types Only abstract (till Java 7)

Inheritance Supports single inheritance Multiple inheritance

Fields Can have instance variables Only static final variables

Q49: What is the difference between == and .equals() in Java?

A:

 == compares object references (memory location).

 .equals() compares object values (overridable method from Object class).

Q50: What is a Wrapper Class in Java?


A: Converts primitive types into objects.
Examples: int → Integer, float → Float, boolean → Boolean
Used when objects are required (e.g., in Collections like ArrayList).

Q51: What is Autoboxing and Unboxing in Java?

A:

 Autoboxing: Automatic conversion of primitive to wrapper object.


int a = 10; Integer b = a;

 Unboxing: Automatic conversion of wrapper to primitive.


Integer x = 100; int y = x;

Q52: What are Strings in Java?

A: Strings are immutable objects that represent sequences of characters. Declared using:

java

CopyEdit

String s = "Hello";

Q53: Why are Strings immutable in Java?

A: For security, synchronization, and caching:

 String constants are cached in the string pool.

 Prevents external modification when shared between threads or APIs.

Q54: What is the difference between String, StringBuilder, and StringBuffer?

Feature String StringBuilder StringBuffer

Mutability Immutable Mutable Mutable

Thread Safe No No Yes

Performance Low (slower) Fastest (no sync) Slower (sync)

Q55: How to compare two Strings in Java?

A:
 Use .equals() to compare values.

 Use == to compare memory references.

java

CopyEdit

s1.equals(s2) // true if values match

s1 == s2 // true if both refer to same object

Q56: What is the final keyword in Java?

A:

 final variable: Value cannot be changed.

 final method: Cannot be overridden.

 final class: Cannot be extended.

java

CopyEdit

final int MAX = 100;

Q57: What is the difference between final, finally, and finalize()?

A:

 final: Keyword to restrict usage (variable, method, class).

 finally: Block in exception handling that always executes.

 finalize(): Method called by garbage collector before destroying object (deprecated


in recent versions).

Q58: What are Arrays in Java?

A: Arrays are containers that hold fixed-size sequential elements of the same type.

java

CopyEdit

int[] nums = {1, 2, 3};


Q59: How to declare and initialize arrays in Java?

A:

java

CopyEdit

int[] arr1 = new int[5]; // default 0s

int[] arr2 = {1, 2, 3, 4, 5}; // initialized

String[] names = new String[3];

Q60: What is an enhanced for-each loop?

A: Simplifies iterating through arrays and collections.

java

CopyEdit

for (int num : arr2) {

System.out.println(num);

Q61: What is a 2D array in Java?

A: A 2D array is an array of arrays, often used to represent matrices or tables.

java

CopyEdit

int[][] matrix = {

{1, 2, 3},

{4, 5, 6}

};

Q62: What are Java Collections?

A: Collections are a framework that provides classes and interfaces for storing and
manipulating groups of data:

 List
 Set

 Queue

 Map

Q63: What is the difference between Array and ArrayList?

Feature Array ArrayList

Size Fixed Dynamic

Data Type Primitive & Object Only Objects

Performance Faster Slower (overhead for features)

Q64: What is the List Interface in Java?

A: List is an ordered collection that allows duplicates. Implementations include:

 ArrayList

 LinkedList

 Vector

Q65: How to iterate over a List in Java?

A:

java

CopyEdit

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

for (String name : names) {

System.out.println(name);

Other ways: using for loop, iterator, or forEach() with lambda.

Q66: What is a Set in Java?

A: Set is a collection that doesn’t allow duplicate elements.


Main implementations:
 HashSet (unordered)

 LinkedHashSet (ordered)

 TreeSet (sorted)

Q67: What is the difference between List and Set?

Feature List Set

Order Maintains insertion order No guarantee (except TreeSet/LinkedHashSet)

Duplicates Allowed Not allowed

Q68: What is a Map in Java?

A: Map is a collection that stores key-value pairs.


Each key is unique, and a key maps to one value.

Common implementations:

 HashMap

 TreeMap

 LinkedHashMap

Q69: How to iterate over a Map in Java?

A:

java

CopyEdit

Map<String, Integer> map = new HashMap<>();

for (Map.Entry<String, Integer> entry : map.entrySet()) {

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

Q70: What is the difference between HashMap and TreeMap?


Feature HashMap TreeMap

Order Unordered Sorted by keys

Null keys Allows one Does not allow null key

Performance Faster Slower (sorted)

Q71: What is Exception Handling in Java?

A: It’s the mechanism to handle runtime errors gracefully using:

 try

 catch

 finally

 throw

 throws

This prevents program crashes and ensures proper error flow.

Q72: What is the difference between Checked and Unchecked Exceptions?

A:

 Checked: Checked at compile-time (IOException, SQLException)

 Unchecked: Occur at runtime (NullPointerException, ArithmeticException)

Q73: What is the use of try-catch-finally block?

A:

 try: Wraps code that might throw an exception.

 catch: Handles specific exceptions.

 finally: Executes regardless of exception, usually for cleanup.

Q74: What is the throw and throws keyword in Java?

A:

 throw: Used to explicitly throw an exception.


java

CopyEdit

throw new ArithmeticException("Divide by zero");

 throws: Declares exceptions a method might throw.

java

CopyEdit

void read() throws IOException { ... }

Q75: What are Custom Exceptions in Java?

A: You can create your own exception class by extending Exception or RuntimeException.

java

CopyEdit

class MyException extends Exception {

MyException(String msg) {

super(msg);

Q76: What is Multithreading in Java?

A: Multithreading allows concurrent execution of two or more threads. It improves CPU


utilization and application performance by executing tasks in parallel.

Q77: How to create threads in Java?

A:

1. By extending the Thread class

java

CopyEdit

class MyThread extends Thread {

public void run() { ... }


}

2. By implementing the Runnable interface

java

CopyEdit

class MyTask implements Runnable {

public void run() { ... }

Q78: What is the difference between Thread and Runnable?

Feature Thread Class Runnable Interface

Inheritance Uses a class (limits inheritance) Implements an interface (flexible)

Design Less preferred More preferred (decoupled logic)

Q79: What are Daemon threads in Java?

A: Background threads that provide services to user threads.


Example: Garbage collection. They terminate when all user threads finish.

java

CopyEdit

thread.setDaemon(true);

Q80: What is the synchronized keyword in Java?

A: Ensures that only one thread can access a block/method at a time, preventing thread
interference and memory consistency errors.

java

CopyEdit

synchronized void printData() { ... }

Q81: What is Inter-thread communication in Java?

A: It allows synchronized threads to communicate using:


 wait()

 notify()

 notifyAll()

These methods help coordinate thread execution inside synchronized blocks.

Q82: What is Deadlock in Java?

A: Deadlock occurs when two or more threads wait indefinitely for each other’s resources,
preventing program execution from continuing.

Q83: What is the volatile keyword in Java?

A: It tells the JVM that a variable’s value may be changed by multiple threads, and it should
always read from main memory rather than cache.

Q84: What is Serialization in Java?

A: It is the process of converting an object into a byte stream to save or transmit it.
Used with ObjectOutputStream and Serializable interface.

Q85: How do you deserialize an object in Java?

A: Deserialization is the reverse of serialization—converting a byte stream back into an


object using ObjectInputStream.

java

CopyEdit

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.ser"));

MyClass obj = (MyClass) in.readObject();

Q86: What is the transient keyword in Java?

A: transient is used to skip certain fields during serialization. When an object is serialized,
transient fields are ignored.

java

CopyEdit
transient int tempData;

Q87: What is the difference between transient and static in Java?

A:

 transient: Excluded from serialization.

 static: Belongs to the class, not to instances, hence not serialized either.

Q88: What are Lambda Expressions in Java?

A: Introduced in Java 8, lambdas provide a concise way to represent functional interfaces.

java

CopyEdit

(a, b) -> a + b

Q89: What is a Functional Interface?

A: An interface with a single abstract method. Common examples:

 Runnable

 Callable

 Custom: @FunctionalInterface

Q90: What is the Stream API in Java?

A: Stream API helps perform functional-style operations on collections (map, filter, reduce)
efficiently and declaratively.

java

CopyEdit

list.stream().filter(x -> x > 5).forEach(System.out::println);

Q91: What is Optional in Java?

A: Optional is a container object to represent the presence or absence of a value. It helps


avoid NullPointerException.

java
CopyEdit

Optional<String> name = Optional.of("Kiran");

name.ifPresent(System.out::println);

Q92: What are default and static methods in interfaces (Java 8+)?

A:

 default method: Has a body inside the interface.

 static method: Belongs to the interface, not instances.

java

CopyEdit

default void log() { ... }

static void print() { ... }

Q93: What is the difference between Comparable and Comparator?

Feature Comparable Comparator

Defined in Class being compared Separate class

Method compareTo() compare()

Sorting logic Single natural ordering Multiple custom orderings

Q94: What is Reflection in Java?

A: Reflection allows inspection and modification of classes, methods, and fields at runtime.
Useful for frameworks, tools, and IDEs.

java

CopyEdit

Class<?> cls = Class.forName("MyClass");

Method[] methods = cls.getDeclaredMethods();

Q95: What are annotations in Java?


A: Metadata added to code elements (classes, methods, fields) to instruct
compilers/tools/frameworks.

Examples: @Override, @Deprecated, @FunctionalInterface

Q96: What is the Java Memory Model (JMM)?

A: JMM defines how variables are read/written in concurrent programs and how threads
interact through memory. It ensures visibility, atomicity, and ordering.

Q97: What is the use of assert in Java?

A: Used for debugging. Throws AssertionError if the condition fails.

java

CopyEdit

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

Q98: What is the difference between JAR and WAR files?

File Type Description

JAR Java Archive – packages Java classes

WAR Web Archive – packages web apps (servlets, JSP, HTML, etc.)

Q99: What is the Java Platform Module System (JPMS)?

A: Introduced in Java 9, it allows modular programming by splitting code into named, self-
contained modules with clear dependencies.

Q100: What are some new features introduced in Java 8–17?

A:

 Java 8: Lambda, Stream API, Optional, default methods

 Java 9: JPMS (modules), JShell

 Java 10–17: var, Records, Text Blocks, Sealed Classes, Pattern Matching

You might also like