1.
CORE BASICS OF JAVA – INTERVIEW ANSWERS
1. History & Features of Java
Java
Interview Answer:
Java was developed by James Gosling at Sun Microsystems in 1995. It was designed to be simple,
secure, and platform-independent.
Key Features:
• Platform Independent (WORA)
• Object-Oriented
• Secure
• Robust
• Multithreaded
2. JVM, JRE, JDK
Java Virtual Machine,
Java Runtime Environment,
Java Development Kit
Interview Answer:
JVM executes bytecode, JRE provides the runtime environment, and JDK provides development tools.
Relationship:
• JDK = JRE + Tools
• JRE = JVM + Libraries
• JVM = java interpreter + execution engine
3. Compilation & Execution Process
Interview Answer:
Java follows a two-step process:
1. Compilation → .java → .class (bytecode) using javac
2. Execution → JVM converts bytecode into machine code
This ensures platform independence.
4. Data Types
Interview Answer:
Java supports two types of data types:
Primitive:
• int, float, double, char, boolean, byte, short, long
Store actual values
Non-Primitive:
• String, Arrays, Classes, Objects
Store references
5. Variables
Interview Answer:
Variables are used to store data, and they are classified into:
• Local Variable → declared inside methods
• Instance Variable → declared inside class, belongs to object
• Static Variable → shared among all objects
Scope and lifetime differ for each type.
6. Type Casting
Interview Answer:
Type casting is the process of converting one data type into another.
Types:
• Implicit (Widening) → automatic
• Explicit (Narrowing) → manual
Example:
int a = 10;
double b = a; // widening
double x = 10.5;
int y = (int)x; // narrowing
7. Operators
Interview Answer:
Operators are symbols used to perform operations on variables.
Types:
• Arithmetic → +, -, *, /, %
• Relational → ==, !=, >, <
• Logical → &&, ||, !
• Assignment → =, +=
Used for calculations and decision-making.
1. What are Control Statements in Java?
Answer:
Control statements in Java are used to control the flow of execution of a program. They determine
which statements should be executed, when, and how many times.
They are mainly divided into:
• Decision-making statements (if, if-else, switch)
• Looping statements (for, while, do-while)
• Jump statements (break, continue)
2. if Statement
Answer:
The if statement is used to execute a block of code only when a specified condition is true.
Syntax:
if(condition) {
// code executes if condition is true
}
Key Points:
• Condition must return boolean (true or false)
• Executes only once if condition is true
3. if-else Statement
Answer:
The if-else statement is used when we want to execute one block of code if the condition is true and
another block if it is false.
Syntax:
if(condition) {
// executes if true
} else {
// executes if false
}
Key Points:
• Ensures one block always executes
• Useful for binary decisions
4. switch Statement
Answer:
The switch statement is used to select one block of code from multiple options based on a variable
value.
Syntax:
switch(expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Key Points:
• Works with int, char, String, enum
• break prevents fall-through
• default executes if no case matches
5. for Loop
Answer:
The for loop is used when the number of iterations is known beforehand.
Syntax:
for(initialization; condition; update) {
// code
}
Key Points:
• Best for fixed iterations
• All loop control in one line
6. while Loop
Answer:
The while loop executes a block of code as long as the condition is true.
Syntax:
while(condition) {
// code
}
Key Points:
• Entry-controlled loop
• May execute zero times if condition is false
7. do-while Loop
Answer:
The do-while loop executes the code at least once before checking the condition.
Syntax:
do {
// code
} while(condition);
Key Points:
• Exit-controlled loop
• Executes at least once regardless of condition
8. break Statement
Answer:
The break statement is used to immediately terminate a loop or switch statement.
Example:
for(int i=0; i<5; i++) {
if(i == 3) break;
}
Key Points:
• Exits the loop completely
• Used in loops and switch
9. continue Statement
Answer:
The continue statement skips the current iteration and moves to the next iteration of the loop.
Example:
for(int i=0; i<5; i++) {
if(i == 3) continue;
}
Key Points:
• Skips current iteration
• Does not terminate loop
3. OOP Concepts (Very Important )
1. Class & Object
Answer:
A class is a blueprint or template used to define properties (variables) and behaviors (methods),
while an object is an instance of that class which represents a real-world entity.
A class does not occupy memory until an object is created.
Example:
class Student {
String name;
int age;
void display() {
[Link](name + " " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // object creation
[Link] = "Diksha";
[Link] = 21;
[Link]();
}
}
Interview Tip:
Class = design, Object = real implementation
2. Encapsulation
Answer:
Encapsulation is the process of binding data and methods together into a single unit and restricting
direct access using access modifiers like private.
It provides data hiding and security.
Example:
class Bank {
private int balance;
public void setBalance(int balance) {
[Link] = balance;
}
public int getBalance() {
return balance;
}
}
Why Use?
• Protect sensitive data
• Control access through methods
3. Inheritance
Answer:
Inheritance allows one class (child) to inherit properties and methods from another class (parent),
promoting code reuse and hierarchy.
Example:
class Animal {
void eat() {
[Link]("Eating");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking");
}
}
Key Point:
Child class gets parent features automatically
4. Polymorphism
Answer:
Polymorphism means one method behaving in multiple ways depending on the context.
✔ Compile-Time (Method Overloading)
class Add {
int sum(int a, int b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
}
Same method name, different parameters
✔ Runtime (Method Overriding)
class Animal {
void sound() {
[Link]("Animal sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
Method decided at runtime
5. Abstraction
Answer:
Abstraction hides implementation details and shows only essential functionality to the user.
Achieved using abstract class or interface
Example:
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle {
void start() {
[Link]("Car starts with key");
}
}
Real-life Example:
ATM machine (you don’t see internal logic)
6. Constructor
Answer:
A constructor is a special method used to initialize objects. It is automatically called when an object is
created.
Types:
• Default constructor
• Parameterized constructor
Example:
class Student {
String name;
Student() {
name = "Unknown";
}
Student(String name) {
[Link] = name;
}
}
7. this Keyword
Answer:
this refers to the current object and is used to avoid confusion between instance variables and
parameters.
Example:
class Student {
String name;
Student(String name) {
[Link] = name;
}
}
8. super Keyword
Answer:
super refers to the parent class and is used to call parent class constructor or methods.
Example:
class Parent {
Parent() {
[Link]("Parent");
}
}
class Child extends Parent {
Child() {
super();
}
}
1. String vs StringBuilder vs StringBuffer
Interview Answer:
In Java, String, StringBuilder, and StringBuffer are used to handle character sequences, but they differ
in mutability and performance.
• String → Immutable (cannot be changed once created)
• StringBuilder → Mutable and not thread-safe (faster)
• StringBuffer → Mutable and thread-safe (synchronized, slower than StringBuilder)
Example:
String s = "Hello";
[Link](" World"); // creates new object
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // modifies same object
StringBuffer sbf = new StringBuffer("Hello");
[Link](" World");
Key Interview Line:
“String is immutable, while StringBuilder and StringBuffer are mutable. StringBuilder is preferred
for performance, and StringBuffer for thread safety.”
2. Immutability of String
Interview Answer:
A String in Java is immutable, meaning once an object is created, its value cannot be changed. Any
modification results in a new object.
Example:
String s = "Java";
s = s + " World";
This creates a new object, original "Java" remains unchanged.
Why Immutable? (Very Important )
• Security (used in passwords, URLs)
• Thread safety
• Enables String Pool optimization
Key Interview Line:
“String immutability ensures security, thread safety, and efficient memory usage through string
pooling.”
3. Important String Methods
equals()
Answer:
Used to compare content of strings
String a = "Java";
String b = "Java";
[Link]([Link](b)); // true
== Operator
Answer:
Compares memory reference (address)
String a = new String("Java");
String b = new String("Java");
[Link](a == b); // false
compareTo()
Answer:
Used for lexicographical comparison
[Link]("Apple".compareTo("Banana"));
Output:
• 0 → equal
• negative → smaller
• positive → greater
Other Frequently Asked Methods
Method Purpose
length() returns length
charAt() access character
substring() extract part
toUpperCase() uppercase
trim() remove spaces
Key Interview Line:
“equals() compares content, while == compares references.”
4. String Pool (Very Important )
Interview Answer:
String Pool is a special memory area in heap where string literals are stored and reused to avoid
duplicate objects and save memory.
Example:
String a = "Java";
String b = "Java";
[Link](a == b); // true
Both refer to same object in pool.
Another Example:
String a = new String("Java");
String b = "Java";
[Link](a == b); // false
Because:
• "Java" → stored in pool
• new String() → new object in heap
6. Exception Handling
try, catch, finally
Interview Answer:
Exception handling is used to handle runtime errors and maintain normal program flow.
• try → contains risky code
• catch → handles exception
• finally → always executes (cleanup code)
Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Exception handled");
} finally {
[Link]("Always executes");
}
Key Line:
“finally block executes regardless of exception occurrence.”
throw vs throws
throw
✔ Interview Answer:
throw is used to explicitly throw an exception inside a method or block.
✔ Key Points:
• Used inside method body
• Throws single exception at a time
• Used to create custom or manual exceptions
✔ Example:
class Demo {
public static void main(String[] args) {
int age = 15;
if(age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
[Link]("Eligible");
}
}
✔ Output:
Exception in thread "main" [Link]: Not eligible to vote
Interview Line:
“throw is used to explicitly create and throw an exception.”
throws
✔ Interview Answer:
throws is used to declare exceptions that a method might throw, so the caller can handle them.
✔ Key Points:
• Used in method signature
• Can declare multiple exceptions
• Mainly used with checked exceptions
✔ Example:
import [Link].*;
class Demo {
static void readFile() throws IOException {
FileReader file = new FileReader("[Link]");
}
public static void main(String[] args) {
try {
readFile();
} catch(IOException e) {
[Link]("Handled");
}
}
}
Interview Line:
“throws is used to declare exceptions so that they can be handled by the caller.”
Checked vs Unchecked Exceptions
Checked Exceptions
✔ Interview Answer:
Checked exceptions are exceptions that are checked at compile time.
The compiler ensures that these exceptions are either handled using try-catch or declared using
throws.
✔ Examples:
• IOException
• SQLException
• FileNotFoundException
✔ Example Code:
import [Link].*;
class Demo {
public static void main(String[] args) {
try {
FileReader file = new FileReader("[Link]");
} catch (IOException e) {
[Link]("File not found");
}
}
}
✔ Key Points:
• Checked at compile time
• Mandatory handling
• Represent external errors (file, database, etc.)
Interview Line:
“Checked exceptions are verified at compile time and must be handled or declared.”
Unchecked Exceptions
✔ Interview Answer:
Unchecked exceptions are exceptions that occur at runtime and are not checked by the compiler.
✔ Examples:
• ArithmeticException
• NullPointerException
• ArrayIndexOutOfBoundsException
✔ Example Code:
class Demo {
public static void main(String[] args) {
int a = 10 / 0; // runtime error
}
}
✔ Key Points:
• Occur at runtime
• Handling is optional
• Usually caused by programming mistakes
Interview Line:
“Unchecked exceptions occur at runtime and are not checked by the compiler.”
7. Java Collections Framework (Very Important )
What is Java Collections Framework?
✔ Interview Answer:
The Java Collections Framework is a set of classes and interfaces that provide dynamic data
structures to store, manipulate, and retrieve groups of objects efficiently.
✔ Key Components:
• Interfaces → List, Set, Map, Queue
• Classes → ArrayList, HashSet, HashMap, etc.
Interview Line:
“It provides reusable data structures and algorithms for efficient data handling.”
1. List (Ordered, Allows Duplicates)
ArrayList
✔ Interview Answer:
ArrayList is a dynamic array that allows duplicates and maintains insertion order.
✔ Example:
ArrayList<Integer> list = new ArrayList<>();
[Link](10);
[Link](20);
[Link](10);
[Link](list);
✔ Features:
• Fast random access
• Slow insertion/deletion (shifting required)
✔ Use Case:
When frequent access is needed
LinkedList
✔ Interview Answer:
LinkedList uses a doubly linked list structure, allowing efficient insertion and deletion.
✔ Example:
LinkedList<Integer> list = new LinkedList<>();
[Link](10);
[Link](20);
✔ Features:
• Fast insertion/deletion
• Slower access
✔ Use Case:
When frequent insert/delete operations are required
Difference: ArrayList vs LinkedList
Feature ArrayList LinkedList
Structure Array Linked List
Access Fast Slow
Insert/Delete Slow Fast
2. Set (No Duplicates)
HashSet
✔ Interview Answer:
HashSet stores unique elements and does not maintain order.
✔ Example:
HashSet<Integer> set = new HashSet<>();
[Link](1);
[Link](1); // ignored
[Link](set);
✔ Features:
• No duplicates
• Unordered
• Fast operations
✔ Use Case:
When you need unique elements only
TreeSet
✔ Interview Answer:
TreeSet stores elements in sorted order using a tree structure.
✔ Example:
TreeSet<Integer> set = new TreeSet<>();
[Link](10);
[Link](5);
[Link](set);
✔ Features:
• Sorted
• No duplicates
✔ Use Case:
When sorted unique data is required
3. Map (Key-Value Pairs)
HashMap
✔ Interview Answer:
HashMap stores data in key-value pairs and allows one null key.
✔ Example:
HashMap<Integer, String> map = new HashMap<>();
[Link](1, "Java");
[Link](2, "Python");
✔ Features:
• Fast access
• Unordered
✔ Use Case:
When fast lookup by key is required
TreeMap
✔ Interview Answer:
TreeMap stores key-value pairs in sorted order of keys.
✔ Example:
TreeMap<Integer, String> map = new TreeMap<>();
[Link](2, "B");
[Link](1, "A");
✔ Features:
• Sorted keys
• No null key
✔ Use Case:
When sorted data by keys is needed
4. Queue & PriorityQueue
Queue
✔ Interview Answer:
Queue follows FIFO (First In First Out) principle.
✔ Example:
Queue<Integer> q = new LinkedList<>();
[Link](1);
[Link](2);
[Link]([Link]()); // removes 1
✔ Use Case:
Task scheduling, buffering
PriorityQueue
✔ Interview Answer:
PriorityQueue processes elements based on priority (natural ordering).
✔ Example:
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](10);
[Link](5);
[Link]([Link]()); // 5
✔ Use Case:
When priority-based processing is required
Difference: Queue vs PriorityQueue
Feature Queue PriorityQueue
Order FIFO Priority-based
Use Simple tasks Scheduling, algorithms
Multithreading
What is Multithreading?
✔ Interview Answer:
Multithreading is the process of executing multiple threads simultaneously within a program to
improve performance and CPU utilization.
Key Line:
“Multithreading allows concurrent execution of tasks to improve efficiency.”
1. Thread Class vs Runnable Interface
Thread Class
✔ Interview Answer:
A thread can be created by extending the Thread class and overriding the run() method.
✔ Example:
class MyThread extends Thread {
public void run() {
[Link]("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link]();
}
}
Runnable Interface
✔ Interview Answer:
A thread can also be created by implementing the Runnable interface, which is preferred as it
supports multiple inheritance.
✔ Example:
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable thread");
}
}
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
[Link]();
}
}
Difference Table
Feature Thread Runnable
Approach Extend class Implement interface
Inheritance Not possible Possible
Flexibility Less More
Key Line:
“Runnable is preferred because it allows better flexibility and multiple inheritance.”
2. Lifecycle of Thread
Interview Answer:
A thread goes through different states during execution:
States:
1. New → Thread created
2. Runnable → Ready to run
3. Running → Executing
4. Blocked/Waiting → Waiting for resource
5. Terminated → Execution finished
Key Line:
“Thread lifecycle defines different states from creation to termination.”
4. Deadlock
Interview Answer:
Deadlock is a situation where two or more threads wait for each other indefinitely, and none can
proceed.
✔ Example Concept:
• Thread 1 → waiting for resource A
• Thread 2 → waiting for resource B
• Both stuck forever
Perfect — this is core Java theory + coding + interview combo. I’ll give you clear, structured,
interviewer-expected answers with examples
10. File Handling
File Class
✔ Interview Answer:
The File class is used to create, delete, and get information about files and directories.
✔ Example:
import [Link];
class Demo {
public static void main(String[] args) {
File f = new File("[Link]");
[Link]([Link]());
[Link]([Link]());
}
Key Line:
“File class is used for file metadata and operations, not for reading/writing content.”
FileReader & FileWriter
✔ Interview Answer:
• FileReader → used to read character data from file
• FileWriter → used to write character data to file
✔ Example:
import [Link].*;
class Demo {
public static void main(String[] args) throws Exception {
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello Java");
[Link]();
FileReader fr = new FileReader("[Link]");
int ch;
while((ch = [Link]()) != -1) {
[Link]((char) ch);
[Link]();
Key Line:
“FileReader and FileWriter are used for character-based file operations.”
BufferedReader
✔ Interview Answer:
BufferedReader is used to read data efficiently using buffering, especially line by line.
✔ Example:
import [Link].*;
class Demo {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
while((line = [Link]()) != null) {
[Link](line);
[Link]();
Key Line:
“BufferedReader improves performance by reducing I/O operations.”
11. Important Keywords
static
✔ Answer:
Belongs to class, not object.
static int count;
Shared among all objects
final
✔ Answer:
Used to make variable constant, method non-overridable, class non-inheritable.
final int x = 10;
abstract
✔ Answer:
Used to declare incomplete methods (no body).
abstract void display();
interface
✔ Answer:
Defines contract (only abstract methods by default).
volatile
✔ Answer:
Ensures variable value is always read from main memory (used in multithreading).
transient
✔ Answer:
Prevents variable from being serialized.
Key Line:
“These keywords control behavior like inheritance, memory, and threading.”
12. Interface vs Abstract Class
What is an Interface?
✔ Interview Answer:
An interface is a blueprint that contains only abstract methods (by default) and is used to achieve
100% abstraction and multiple inheritance.
✔ Key Features:
• Methods are public & abstract by default
• Variables are public static final (constants)
• Supports multiple inheritance
• Cannot have constructors
✔ Example:
interface Animal {
void sound(); // abstract method
}
class Dog implements Animal {
public void sound() {
[Link]("Barks");
}
}
What is an Abstract Class?
✔ Interview Answer:
An abstract class is a class that can have both abstract and concrete (normal) methods, used for
partial abstraction.
✔ Key Features:
• Can have both abstract & non-abstract methods
• Can have constructors
• Supports single inheritance
• Can have instance variables
✔ Example:
abstract class Animal {
abstract void sound(); // abstract method
void eat() { // concrete method
[Link]("Eating");
}
}
class Dog extends Animal {
void sound() {
[Link]("Barks");
}
}
Core Differences (Very Important )
Feature Interface Abstract Class
Abstraction 100% (before Java 8) Partial
Methods Only abstract (default) Abstract + concrete
Variables public static final Any type
Constructors Not allowed Allowed
Inheritance Multiple Single
Keyword implements extends
Default & Static Methods in Interface
Default Method
✔ Interview Answer:
A default method is a method in an interface that has a body (implementation) and can be inherited
by implementing classes.
✔ Key Points:
• Declared using default keyword
• Can be overridden in implementing class
• Helps in adding new methods without breaking old code
✔ Example:
interface Demo {
default void show() {
[Link]("Default method");
}
}
class Test implements Demo {
public static void main(String[] args) {
Test t = new Test();
[Link](); // calling default method
}
}
✔ Output:
Default method
Interview Line:
“Default methods allow interfaces to have implementation and support backward compatibility.”
Static Method in Interface
✔ Interview Answer:
A static method in an interface belongs to the interface itself, not to objects.
✔ Key Points:
• Declared using static keyword
• Cannot be overridden
• Called using interface name
✔ Example:
interface Demo {
static void display() {
[Link]("Static method");
}
}
class Test {
public static void main(String[] args) {
[Link](); // called using interface name
}
}
✔ Output:
Static method
Interview Line:
“Static methods in interfaces are utility methods and are called using interface name.”
14. Memory Management
Stack vs Heap
✔ Interview Answer:
Feature Stack Heap
Stores Local variables Objects
Memory Fixed Dynamic
Speed Fast Slower
Wrapper Classes
What are Wrapper Classes?
✔ Interview Answer:
Wrapper classes are used to convert primitive data types into objects.
✔ Examples:
Primitive Wrapper
int Integer
double Double
char Character
boolean Boolean
Interview Line:
“Wrapper classes allow primitives to be used as objects, especially in collections.”
Why Wrapper Classes?
✔ Reasons:
• Collections (like ArrayList) store objects only
• Needed for object-based operations
✔ Example:
import [Link].*;
class Demo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
[Link](10); // autoboxing
[Link](20);
[Link](list);
}
}
Autoboxing & Unboxing
✔ Interview Answer:
• Autoboxing → primitive → object
• Unboxing → object → primitive
✔ Example:
class Demo {
public static void main(String[] args) {
Integer obj = 10; // autoboxing
int x = obj; // unboxing
[Link](x);
}
}
Key Line:
“Stack stores method data, heap stores objects.”
Garbage Collection
✔ Interview Answer:
Garbage Collection automatically removes unused objects from memory.
✔ Example:
Demo d = new Demo();
d = null; // eligible for GC
Key Line:
“GC improves memory management by freeing unused objects.”
finalize()
✔ Interview Answer:
finalize() is called by GC before destroying an object (now deprecated).
✔ Example:
protected void finalize() {
[Link]("Object destroyed");
Important Note:
Not reliable and not recommended in modern Java