Java Fundamentals
***1. Why is Java platform independent?
Java is called platform independent because Java code can run on any operating system without recompilation.
How it works:
- Java source code (
.java) is compiled into bytecode (.class). - Bytecode is not machine-specific.
- The JVM (Java Virtual Machine) converts bytecode into machine code for the specific OS.
This follows the principle:
“Write Once, Run Anywhere (WORA)”
Example:
A Java program compiled on Windows can run on:
- Linux
- macOS
- Unix
as long as a JVM is installed.
Important Interview Point:
Java is platform independent because of the JVM and bytecode, not because of the compiler.
***2. What are the main features of Java?
Java provides many powerful features that make it popular.
Main Features of Java
1. Platform Independent
Runs on any OS using JVM.
2. Object-Oriented
Everything is based on classes and objects.
3. Simple
Easy syntax compared to C++.
Removes complex concepts like:
- Pointer arithmetic
- Multiple inheritance using classes
4. Secure
Java provides:
- Bytecode verification
- Security manager
- No direct memory access
5. Robust
Strong memory management and exception handling.
6. Multithreaded
Supports concurrent execution using threads.
7. High Performance
JIT compiler improves execution speed.
8. Distributed
Supports distributed applications using:
- RMI
- Web services
- Networking APIs
9. Dynamic
Classes can be loaded dynamically during runtime.
10. Automatic Garbage Collection
Unused memory is automatically cleaned.
Important Interview Point:
Interviewers often ask:
“Which feature of Java makes it secure?”
Answer:
- No pointers
- Bytecode verification
- JVM sandbox environment
***3. What is JVM?
JVM stands for Java Virtual Machine.
It is a virtual environment that executes Java bytecode.
Responsibilities of JVM
- Loads class files
- Verifies bytecode
- Executes code
- Manages memory
- Performs garbage collection
JVM Architecture Components
- Class Loader
- Method Area
- Heap Memory
- Stack Memory
- Execution Engine
- Garbage Collector
Important Interview Point:
JVM is platform dependent, while Java is platform independent.
Different OS have different JVM implementations.
***4. What is JRE?
JRE stands for Java Runtime Environment.
It provides everything required to run Java applications.
JRE Contains
- JVM
- Core libraries
- Supporting files
JRE does NOT contain:
- Java compiler (
javac)
Usage:
Used only for running Java programs.
Formula:
JRE = JVM + Libraries
***5. What is JDK?
JDK stands for Java Development Kit.
It is used to develop, compile, and run Java applications.
JDK Contains
- JRE
- JVM
- Compiler (
javac) - Debugging tools
- Development utilities
Formula:
JDK = JRE + Development Tools
Important Interview Point:
Developers install JDK because it includes both compiler and runtime environment.
***6. Difference between JVM, JRE, and JDK.
| Feature | JVM | JRE | JDK |
|---|---|---|---|
| Full Form | Java Virtual Machine | Java Runtime Environment | Java Development Kit |
| Purpose | Executes bytecode | Runs Java programs | Develops Java programs |
| Contains Compiler | No | No | Yes |
| Contains JVM | — | Yes | Yes |
| Used By | Runtime system | End users | Developers |
| Main Function | Execution | Runtime environment | Development + Execution |
Relationship
JDK = JRE + Development Tools
JRE = JVM + Libraries
Interview Shortcut:
- JVM → Executes
- JRE → Runs
- JDK → Develops
***7. What is JIT Compiler?
JIT stands for Just-In-Time Compiler.
It is part of the JVM that improves Java performance.
How JIT Works
Normally:
- Bytecode is interpreted line by line.
JIT:
- Converts frequently used bytecode into native machine code.
- Stores compiled code for reuse.
This reduces repeated interpretation.
Benefits
- Faster execution
- Improved performance
- Runtime optimization
Important Interview Point:
Without JIT, Java would be much slower because interpretation alone is slower than native execution.
**8. What is a ClassLoader?
ClassLoader is a JVM subsystem that loads .class files into memory.
Types of ClassLoaders
1. Bootstrap ClassLoader
Loads core Java classes like:
java.lang.*
2. Extension ClassLoader
Loads extension libraries.
3. Application ClassLoader
Loads application classes from classpath.
Class Loading Process
- Loading
- Linking
- Initialization
Important Interview Point:
Java uses dynamic class loading, meaning classes are loaded only when required.
***9. Explain public static void main(String args[]).
This is the entry point of a Java application.
public static void main(String args[])
Explanation of Each Keyword
public
Accessible from anywhere.
JVM must access it.
static
Can be called without creating an object.
void
Returns nothing.
main
Special method name recognized by JVM.
String args[]
Stores command-line arguments.
Example
class Test {
public static void main(String args[]) {
System.out.println("Hello Java");
}
}
Important Interview Point:
JVM starts program execution from the main() method.
***10. Why is the main method static in Java?
The main() method is static because JVM calls it directly without creating an object.
Reason
If main() were non-static:
- JVM would first need to create an object.
- Object creation itself may depend on code execution.
To avoid this dependency, Java keeps main() static.
Example
public static void main(String args[])
JVM can directly call:
ClassName.main();
Important Interview Point:
Static methods belong to the class, not objects.
**11. Can the main method be overloaded?
Yes, the main() method can be overloaded.
Example
class Test {
public static void main(String[] args) {
System.out.println("Original main");
}
public static void main(int a) {
System.out.println(a);
}
}
Important Point
JVM always calls:
public static void main(String[] args)
Other overloaded versions are called manually.
Interview Trap
Overloading is allowed.
Overriding static methods is not true runtime polymorphism.
**12. What happens if the main method is not static?
If main() is not static, the program compiles but JVM cannot execute it properly.
Example
public void main(String[] args)
Runtime Error
Error: Main method is not static
Reason
JVM calls main() without creating an object.
Non-static methods require object creation.
Important Interview Point:
main() must always be:
public static void main(String[] args)
*13. What are packages in Java?
Packages are used to organize related classes and interfaces.
They help avoid naming conflicts and improve code management.
Types of Packages
1. Built-in Packages
Provided by Java.
Examples:
java.lang
java.util
java.io
2. User-Defined Packages
Created by developers.
Example
package mypackage;
public class Test {
public void display() {
System.out.println("Hello");
}
}
Advantages
- Better organization
- Avoid class name conflicts
- Access protection
- Reusability
Important Interview Point:
java.lang package is imported automatically by Java.
*14. Advantages of Packages in Java
Packages in Java are used to organize related classes and interfaces into a structured namespace.
Advantages of Packages
1. Avoids Naming Conflicts
Two classes can have the same name if they belong to different packages.
Example
java.util.Date
java.sql.Date
2. Better Code Organization
Packages help organize large projects into modules.
Example:
com.company.service
com.company.model
com.company.controller
3. Provides Access Protection
Packages work with access modifiers like:
- protected
- default
to control visibility.
4. Improves Code Reusability
Reusable classes can be grouped into packages and imported where needed.
5. Easier Maintenance
Structured code is easier to:
- debug
- test
- maintain
6. Supports Modular Development
Different teams can work on separate packages independently.
Important Interview Point:
Java follows a hierarchical package structure using dot notation.
Example:
java.util.Scanner
Data Types & Variables
***15. Difference between primitive and non-primitive data types
Primitive Data Types
Primitive types store actual values directly.
Types
byte, short, int, long,
float, double,
char, boolean
Example
int x = 10;
Non-Primitive Data Types
Non-primitive types store references to objects.
Examples
- String
- Array
- Class
- Interface
Example
String name = "Java";
Difference Table
| Feature | Primitive | Non-Primitive |
|---|---|---|
| Stores | Actual value | Reference/address |
| Memory Size | Fixed | Variable |
| Null Allowed | No | Yes |
| Default Value | Depends on type | null |
| Object Support | No | Yes |
| Methods Available | No | Yes |
Important Interview Point:
String is non-primitive in Java even though it behaves like a basic type.
***16. Difference between instance variable, local variable, and class variable
1. Instance Variable
Declared inside class but outside methods.
Each object gets its own copy.
Example
class Test {
int x = 10;
}
Features
- Belongs to object
- Stored in heap memory
- Has default values
2. Local Variable
Declared inside methods or blocks.
Example
void show() {
int a = 5;
}
Features
- Scope limited to method/block
- No default value
- Stored in stack memory
3. Class Variable (Static Variable)
Declared using static.
Shared among all objects.
Example
class Test {
static int count = 0;
}
Features
- Single copy shared by all objects
- Memory allocated once
Difference Table
| Feature | Instance Variable | Local Variable | Class Variable |
|---|---|---|---|
| Declared | Inside class | Inside method | Inside class with static |
| Scope | Object level | Method/block | Class level |
| Memory | Heap | Stack | Method Area |
| Default Value | Yes | No | Yes |
| Shared | No | No | Yes |
Important Interview Point:
Static variables are initialized only once during class loading.
***17. What are static variables?
Static variables are class-level variables shared among all objects of a class.
They are declared using the static keyword.
Example
class Employee {
static String company = "Google";
int id;
}
All objects share the same company variable.
Features of Static Variables
- Belong to class, not object
- Memory allocated once
- Shared across all instances
- Accessed using class name
Example
Employee.company
Use Cases
- Counters
- Constants
- Shared configuration values
Important Interview Point:
Changing a static variable affects all objects.
**18. Default values of variables in Java
Java assigns default values only to:
- instance variables
- static variables
Local variables do NOT get default values.
Default Values Table
| Data Type | Default Value |
|---|---|
| byte | 0 |
| short | 0 |
| int | 0 |
| long | 0L |
| float | 0.0f |
| double | 0.0d |
| char | '\u0000' |
| boolean | false |
| Object Reference | null |
Example
class Test {
int x;
boolean flag;
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.x);
System.out.println(t.flag);
}
}
Output:
0
false
Important Interview Point:
Using an uninitialized local variable causes a compile-time error.
**19. What is type casting?
Type casting means converting one data type into another.
Types of Type Casting
1. Widening Casting (Implicit)
Small type → Large type
Automatically done by Java.
Example
int a = 10;
double b = a;
2. Narrowing Casting (Explicit)
Large type → Small type
Must be done manually.
Example
double x = 10.5;
int y = (int)x;
Important Interview Point:
Narrowing may cause:
- data loss
- precision loss
*20. Explain widening and narrowing conversion
Widening Conversion
Converting smaller data type into larger data type.
Example
int a = 100;
long b = a;
Features
- Automatic
- Safe conversion
- No data loss
Widening Order
byte → short → int → long → float → double
Narrowing Conversion
Converting larger data type into smaller data type.
Example
double x = 10.9;
int y = (int)x;
Output:
10
Features
- Manual conversion required
- Possible data loss
Difference Table
| Feature | Widening | Narrowing |
|---|---|---|
| Conversion | Small → Large | Large → Small |
| Automatic | Yes | No |
| Data Loss | No | Possible |
| Casting Required | No | Yes |
Important Interview Point:
Interviewers often ask:
“Why is narrowing unsafe?”
Because data may be truncated or overflow may occur.
*21. What are wrapper classes?
Wrapper classes convert primitive data types into objects.
Each primitive type has a corresponding wrapper class.
Primitive to Wrapper Mapping
| Primitive | Wrapper Class |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
Example
int x = 10;
Integer obj = Integer.valueOf(x);
Why Wrapper Classes Exist
Java collections work only with objects.
Example:
ArrayList<Integer>
Important Interview Point:
Wrapper classes are immutable in Java.
**22. Why do we need wrapper classes?
Wrapper classes are needed because many Java APIs and collections work only with objects, not primitive types.
Reasons for Using Wrapper Classes
1. Collections Framework Requires Objects
Example
ArrayList<Integer> list = new ArrayList<>();
Primitive types like int cannot be directly stored.
2. Utility Methods
Wrapper classes provide useful methods.
Example
Integer.parseInt("100")
3. Supports Null Values
Primitive types cannot store null.
Wrapper objects can.
4. Required in Generics
Generics work only with objects.
Example
List<Double>
5. Object-Oriented Features
Primitive types are not objects.
Wrapper classes allow:
- method calls
- object behavior
Important Interview Point:
Autoboxing automatically converts primitive types into wrapper objects.
*23. What is autoboxing and unboxing?
Autoboxing
Automatic conversion of primitive type into wrapper object.
Example
int x = 10;
Integer obj = x;
Java internally does:
Integer.valueOf(x)
Unboxing
Automatic conversion of wrapper object into primitive type.
Example
Integer obj = 20;
int x = obj;
Java internally does:
obj.intValue()
Example Program
class Test {
public static void main(String[] args) {
Integer a = 100; // Autoboxing
int b = a; // Unboxing
System.out.println(b);
}
}
Advantages
- Cleaner code
- Simplifies collection usage
- Reduces manual conversions
Important Interview Point:
Autoboxing may create extra objects and impact performance in large loops.
Operators & Control Statements
Classes & Objects
Strings in Java
***48. What is String Pool in Java?
String Pool is a special memory area inside the heap where Java stores string literals.
It is also called:
String Constant Pool (SCP)
Why String Pool Exists
To optimize memory usage by reusing string objects.
Example
String s1 = "Java";
String s2 = "Java";
Both s1 and s2 point to the same object in the String Pool.
Memory Behavior
String s1 = "Java";
String s2 = new String("Java");
Here:
-
"Java"literal goes to String Pool -
new String("Java")creates a new object in heap memory
Advantages of String Pool
- Saves memory
- Improves performance
- Avoids duplicate objects
Important Interview Point:
String literals are stored in the pool automatically, but objects created using new are stored separately in heap memory.
***49. Difference between String, StringBuffer, and StringBuilder
All three are used to handle text in Java, but they differ in mutability and thread safety.
1. String
String objects are immutable.
Any modification creates a new object.
Example
String s = "Java";
s.concat(" Programming");
Original string remains unchanged.
2. StringBuffer
StringBuffer is mutable and thread-safe.
Example
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
3. StringBuilder
StringBuilder is mutable but not thread-safe.
Faster than StringBuffer.
Example
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
Difference Table
| Feature | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread Safe | Yes | Yes | No |
| Performance | Slow | Moderate | Fast |
| Memory Usage | More | Less | Less |
| Introduced In | Java 1.0 | Java 1.0 | Java 1.5 |
When to Use
| Situation | Recommended |
|---|---|
| Constant text | String |
| Multithreaded modifications | StringBuffer |
| Single-threaded modifications | StringBuilder |
Important Interview Point:
StringBuilder is preferred in most modern applications because it is faster than StringBuffer.
***50. Why are Strings immutable in Java?
String objects cannot be changed after creation.
Example
String s = "Java";
s.concat(" World");
A new object is created instead of modifying the original string.
Reasons Why Strings are Immutable
1. Security
Strings are widely used in:
- database URLs
- file paths
- network connections
Immutability prevents accidental modification.
2. String Pool Optimization
Immutable strings can be safely shared in the String Pool.
3. Thread Safety
Immutable objects are naturally thread-safe.
4. HashCode Caching
Strings are used as keys in:
HashMap
Immutability ensures hashcode remains consistent.
Important Interview Point:
If strings were mutable, String Pool sharing would become unsafe.
**51. Difference between creating String using literal and new keyword
Using String Literal
Example
String s1 = "Java";
Behavior
- Stored in String Pool
- Reuses existing object if value already exists
Using new Keyword
Example
String s2 = new String("Java");
Behavior
- Creates new object in heap memory
- Always creates a separate object
Difference Table
| Feature | String Literal | new String() |
|---|---|---|
| Memory Location | String Pool | Heap |
| Object Reuse | Yes | No |
| Memory Efficient | Yes | Less |
| Object Creation | Only if not exists | Always |
Example
String a = "Java";
String b = "Java";
System.out.println(a == b);
Output:
true
Because both references point to same pooled object.
Important Interview Point:
Using literals is more memory efficient than using new String().
**52. Why is StringBuffer mutable?
StringBuffer is mutable to allow efficient modification of strings without creating new objects repeatedly.
Example
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
The same object gets modified.
Why Mutability is Important
If strings were modified using immutable String:
- multiple objects would be created
- memory usage would increase
- performance would decrease
Advantages of Mutable StringBuffer
- Better performance
- Lower memory consumption
- Efficient concatenation
Internal Working
StringBuffer maintains a resizable character array internally.
Important Interview Point:
StringBuffer methods are synchronized, making it thread-safe.
*53. How can you reverse a string in Java?
There are multiple ways to reverse a string.
Method 1: Using StringBuilder
Example
String str = "Java";
String reversed = new StringBuilder(str)
.reverse()
.toString();
System.out.println(reversed);
Output:
avaJ
Method 2: Using Loop
Example
String str = "Java";
String rev = "";
for(int i = str.length() - 1; i >= 0; i--) {
rev += str.charAt(i);
}
System.out.println(rev);
Method 3: Using Character Array
Example
char[] arr = str.toCharArray();
Reverse manually using swapping.
Best Approach
StringBuilder.reverse()
because it is optimized and easy to read.
Important Interview Point:
Using + inside loops is inefficient because it creates multiple String objects.
*54. Why is char array preferred for passwords over String?
char[] is preferred for passwords because it provides better security than String.
Problem with String Passwords
Strings are immutable.
Once created:
- they stay in memory until garbage collected
- cannot be modified manually
This increases security risk.
Example
String password = "admin123";
Password may remain in memory for a long time.
Advantage of char[]
Character arrays are mutable.
Password data can be cleared immediately after use.
Example
char[] password = {'a','d','m','i','n'};
After usage:
Arrays.fill(password, ' ');
Memory gets cleared.
Difference Table
| Feature | String | char[] |
|---|---|---|
| Mutable | No | Yes |
| Security | Less secure | More secure |
| Memory Cleanup | Automatic only | Manual possible |
| Stored in String Pool | Possible | No |
Important Interview Point:
Security-sensitive applications prefer char[] because passwords can be erased manually from memory.
Arrays
***55. What is an array?
An array is a collection of similar data types stored in contiguous memory locations.
Arrays are used to store multiple values using a single variable name.
Features of Arrays
- Fixed size
- Stores homogeneous data
- Fast access using index
- Index starts from
0
Syntax
datatype[] arrayName;
Example
int[] numbers = {10, 20, 30, 40};
Accessing Array Elements
System.out.println(numbers[0]);
Output:
10
Memory Representation
Index : 0 1 2 3
Value : 10 20 30 40
Important Interview Point:
Arrays in Java are objects stored in heap memory.
***56. Difference between array and ArrayList
Both arrays and ArrayList are used to store collections of data, but they differ in flexibility and functionality.
Array
An array has fixed size.
Example
int[] arr = new int[5];
ArrayList
ArrayList is a resizable collection class from:
java.util
Example
ArrayList<Integer> list = new ArrayList<>();
Difference Table
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Package | Built-in language feature | java.util |
| Data Types | Primitive + Objects | Objects only |
| Performance | Faster | Slightly slower |
| Memory Usage | Less | More |
| Methods Available | Limited | Many utility methods |
Example
list.add(10);
list.remove(0);
When to Use
| Situation | Recommended |
|---|---|
| Fixed-size data | Array |
| Dynamic data | ArrayList |
Important Interview Point:
ArrayList internally uses arrays.
**57. Why does array indexing start from 0?
Array indexing starts from 0 because of memory address calculation efficiency.
Internal Formula
Address Calculation
Address = Base Address + (Index × Size of Element)
Example
int[] arr = {10, 20, 30};
If:
- base address = 100
- size of int = 4 bytes
Then:
arr[0] = 100 + (0 × 4) = 100
arr[1] = 100 + (1 × 4) = 104
Advantages of Zero-Based Indexing
- Faster calculations
- Simpler memory access
- Efficient implementation
Important Interview Point:
Most programming languages use zero-based indexing for performance optimization.
**58. Types of arrays in Java
Java supports multiple types of arrays.
1. Single-Dimensional Array
Stores data in one row.
Example
int[] arr = {10, 20, 30};
2. Multidimensional Array
Array of arrays.
Example
int[][] matrix = {
{1, 2},
{3, 4}
};
3. Jagged Array
Rows contain different column sizes.
Example
int[][] arr = {
{1, 2},
{3, 4, 5},
{6}
};
Classification Based on Data Type
Primitive Arrays
int[] arr;
double[] marks;
Object Arrays
String[] names;
Student[] students;
Important Interview Point:
In Java, multidimensional arrays are internally implemented as arrays of arrays.
*59. What is a jagged array?
A jagged array is a multidimensional array where each row can have different lengths.
It is also called:
Ragged Array
Example
int[][] arr = new int[3][];
arr[0] = new int[2];
arr[1] = new int[4];
arr[2] = new int[1];
Memory Representation
Row 0 → 2 columns
Row 1 → 4 columns
Row 2 → 1 column
Advantages
- Efficient memory usage
- Flexible row sizes
Use Cases
- Matrix representations
- Dynamic table structures
Important Interview Point:
Java does not store multidimensional arrays as continuous memory blocks like C/C++.
*60. Difference between int[] arr and int arr[]
Both declarations are valid and create integer arrays.
Method 1
int[] arr;
Preferred Java style.
Method 2
int arr[];
Older C/C++ style syntax.
Difference
| Feature | int[] arr | int arr[] |
|---|---|---|
| Style | Java style | C-style |
| Readability | Better | Less preferred |
| Functionality | Same | Same |
Example
int[] a = new int[5];
int b[] = new int[5];
Both are equivalent.
Important Interview Point:
Most Java coding standards recommend:
int[] arr;
because it clearly associates array notation with the data type.
*61. Advantages and disadvantages of arrays
Advantages of Arrays
1. Fast Access
Elements can be accessed using index in:
O(1)
time complexity.
2. Easy Traversal
Arrays are simple to iterate using loops.
3. Memory Efficient
Stores elements in contiguous memory locations.
4. Supports Multiple Data Storage
Can store large amounts of similar data.
5. Better Performance
Faster than many dynamic collections.
Disadvantages of Arrays
1. Fixed Size
Size cannot be changed after creation.
2. Homogeneous Data Only
Stores same data type elements.
3. Insertion/Deletion is Costly
Requires shifting elements.
4. Memory Wastage
Unused allocated memory remains reserved.
5. No Built-in Methods
Unlike collections, arrays provide limited functionality.
Difference Summary
| Advantages | Disadvantages |
|---|---|
| Fast access | Fixed size |
| Memory efficient | Costly insertion/deletion |
| Simple structure | Limited functionality |
Important Interview Point:
Arrays are preferred when:
- size is fixed
- high performance is required
- direct index access is important
***62. What is exception handling?
Exception handling is a mechanism in Java used to handle runtime errors so that the normal flow of the program can continue.
What is an Exception?
An exception is an unwanted event that occurs during program execution.
Examples:
- division by zero
- file not found
- invalid array index
- null object access
Purpose of Exception Handling
- Prevent program termination
- Handle errors gracefully
- Maintain normal application flow
Keywords Used
-
try -
catch -
finally -
throw -
throws
Example
class Test {
public static void main(String[] args) {
try {
int result = 10 / 0;
}
catch(ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
System.out.println("Program continues");
}
}
Output
Cannot divide by zero
Program continues
Important Interview Point:
Exception handling improves program reliability and user experience.
***63. Difference between checked and unchecked exceptions
Exceptions in Java are divided into:
- Checked Exceptions
- Unchecked Exceptions
Checked Exceptions
Checked exceptions are checked at compile time.
The compiler forces handling using:
- try-catch
- throws
Examples
- IOException
- SQLException
- FileNotFoundException
Example
FileReader file = new FileReader("test.txt");
Compiler requires exception handling.
Unchecked Exceptions
Unchecked exceptions occur at runtime.
Compiler does not force handling.
Examples
- NullPointerException
- ArithmeticException
- ArrayIndexOutOfBoundsException
Example
int x = 10 / 0;
Difference Table
| Feature | Checked Exception | Unchecked Exception |
|---|---|---|
| Checked By | Compiler | JVM |
| Handling Mandatory | Yes | No |
| Occurs At | Compile time | Runtime |
| Parent Class | Exception | RuntimeException |
Important Interview Point:
All unchecked exceptions are subclasses of:
RuntimeException
***64. Difference between Error and Exception
Both Error and Exception are subclasses of:
Throwable
But they represent different problems.
Exception
Exceptions are conditions that applications can handle.
Examples
- IOException
- NullPointerException
Error
Errors are serious system-level problems that applications usually cannot recover from.
Examples
- OutOfMemoryError
- StackOverflowError
Difference Table
| Feature | Exception | Error |
|---|---|---|
| Recoverable | Yes | Usually No |
| Caused By | Application issues | System/JVM issues |
| Handling | Recommended | Rarely handled |
| Type | Runtime/Application problem | Critical problem |
Important Interview Point:
Errors usually indicate JVM or system failure and should not normally be caught.
***65. What is try-catch-finally?
These blocks are used for exception handling.
try Block
Contains code that may cause an exception.
catch Block
Handles the exception generated in the try block.
finally Block
Executes regardless of whether exception occurs or not.
Usually used for:
- closing files
- releasing resources
- database cleanup
Example
try {
int x = 10 / 0;
}
catch(ArithmeticException e) {
System.out.println("Exception handled");
}
finally {
System.out.println("Finally block executed");
}
Output
Exception handled
Finally block executed
Important Interview Point:
finally block is mostly used for resource cleanup.
**66. Can finally block be skipped?
Normally, the finally block always executes.
However, it may be skipped in some special situations.
Cases Where finally May Not Execute
1. JVM Shutdown
System.exit(0);
2. System Crash
- Power failure
- JVM crash
Example
try {
System.exit(0);
}
finally {
System.out.println("Finally");
}
Output:
(No output)
Important Interview Point:
Except for abnormal JVM termination, finally almost always executes.
**67. Difference between throw and throws
Both are used in exception handling but serve different purposes.
throw Keyword
Used to explicitly throw an exception.
Example
throw new ArithmeticException("Invalid");
throws Keyword
Used in method declaration to indicate possible exceptions.
Example
void readFile() throws IOException
Difference Table
| Feature | throw | throws |
|---|---|---|
| Purpose | Explicitly throws exception | Declares exception |
| Used In | Method body | Method signature |
| Followed By | Exception object | Exception class name |
| Number of Exceptions | One at a time | Multiple possible |
Important Interview Point:
throw is used by programmers, while throws informs the compiler and caller about exceptions.
**68. What is exception propagation?
Exception propagation means passing an exception from one method to another until it is handled.
Flow
If a method does not handle an exception:
- JVM passes it to the calling method
- continues until handled
Example
class Test {
void method1() {
method2();
}
void method2() {
int x = 10 / 0;
}
public static void main(String[] args) {
try {
new Test().method1();
}
catch(Exception e) {
System.out.println("Handled");
}
}
}
Output
Handled
Important Interview Point:
Unchecked exceptions propagate automatically in Java.
*69. What is NullPointerException?
NullPointerException occurs when we try to use an object reference that points to null.
Example
String s = null;
System.out.println(s.length());
Runtime Error
NullPointerException
Common Causes
- Calling method on null object
- Accessing field of null object
- Using null arrays
How to Avoid
- Null checks
- Proper object initialization
- Using
Optional(Java 8+)
Example
if(s != null) {
System.out.println(s.length());
}
Important Interview Point:
NullPointerException is one of the most common runtime exceptions in Java interviews and real projects.
*70. What happens if exception is not handled?
If an exception is not handled:
- JVM stops normal execution
- JVM creates exception object
- Stack trace is printed
- Program terminates abnormally
Example
class Test {
public static void main(String[] args) {
int x = 10 / 0;
System.out.println("Hello");
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
Hello will not print.
JVM Behavior
JVM searches for matching catch block:
- current method
- caller method
- propagation chain
If not found:
Program terminates
Important Interview Point:
Unchecked exceptions may compile successfully but can crash the application at runtime if not handled properly.
Collections Basics
Multithreading Basics
***81. What is multithreading?
Multithreading is a process of executing multiple threads simultaneously within a single program.
A thread is the smallest unit of execution.
Why Multithreading is Used
- Improves performance
- Better CPU utilization
- Executes tasks concurrently
- Reduces response time
Real-Life Example
In a web browser:
- One thread loads images
- Another handles user input
- Another plays audio/video
All tasks run simultaneously.
Example
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
Advantages
- Faster execution
- Better resource sharing
- Supports background tasks
Important Interview Point:
Java supports multithreading through:
- Thread class
- Runnable interface
- Executor Framework
***82. Difference between process and thread
Both process and thread are execution units, but they differ in memory and resource usage.
Process
A process is an independent program in execution.
Each process has:
- separate memory
- separate resources
Example
- Browser
- VS Code
- Media Player
Thread
A thread is a lightweight subpart of a process.
Threads share:
- memory
- resources
within the same process.
Example
Tabs inside browser may use multiple threads.
Difference Table
| Feature | Process | Thread |
|---|---|---|
| Definition | Independent program | Smallest execution unit |
| Memory | Separate | Shared |
| Resource Usage | Heavy | Lightweight |
| Communication | Slower | Faster |
| Creation Time | More | Less |
Important Interview Point:
Context switching between threads is faster than between processes.
***83. Two ways to create threads in Java
There are two main ways to create threads in Java.
1. Extending Thread Class
Create a class that extends:
Thread
Override:
run()
Example
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
2. Implementing Runnable Interface
Create a class implementing:
Runnable
Example
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running");
}
public static void main(String[] args) {
MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj);
t.start();
}
}
Difference Table
| Feature | Thread Class | Runnable Interface |
|---|---|---|
| Inheritance | Extends Thread | Implements Runnable |
| Multiple Inheritance | Not possible | Possible |
| Better Approach | Less preferred | Recommended |
Important Interview Point:
Implementing Runnable is preferred because Java supports single inheritance only.
**84. What is thread lifecycle?
A thread goes through multiple states during execution.
Thread Lifecycle States
1. New State
Thread object is created but not started.
Example
Thread t = new Thread();
2. Runnable State
After calling:
start()
Thread becomes ready to run.
3. Running State
Thread scheduler selects the thread for execution.
4. Blocked/Waiting State
Thread waits for:
- lock
- resource
- signal
- sleep completion
5. Terminated State
Thread finishes execution.
Lifecycle Diagram
NEW → RUNNABLE → RUNNING → WAITING/BLOCKED → TERMINATED
Important Interview Point:
Calling:
start()
creates a new thread, while:
run()
executes normally like a method call.
**85. What is daemon thread?
A daemon thread is a background thread that supports user threads.
It runs in the background and automatically terminates when all user threads finish.
Examples of Daemon Threads
- Garbage Collector
- Background monitoring
- Auto-save services
How to Create Daemon Thread
Use:
setDaemon(true)
before starting the thread.
Example
class Test extends Thread {
public void run() {
System.out.println("Daemon Thread");
}
public static void main(String[] args) {
Test t = new Test();
t.setDaemon(true);
t.start();
}
}
Features
- Low-priority background tasks
- JVM exits when only daemon threads remain
Important Interview Point:
setDaemon(true) must be called before:
start()
otherwise:
IllegalThreadStateException
occurs.
**86. Difference between sleep() and wait()
Both sleep() and wait() pause thread execution, but they work differently.
sleep()
Defined in:
Thread class
Pauses thread for a specific time.
Example
Thread.sleep(1000);
Features of sleep()
- Does NOT release lock
- Time-based pause
- Static method
wait()
Defined in:
Object class
Used for inter-thread communication.
Example
obj.wait();
Features of wait()
- Releases lock
- Must be used inside synchronized block
- Waits until notified
Difference Table
| Feature | sleep() | wait() |
|---|---|---|
| Class | Thread | Object |
| Releases Lock | No | Yes |
| Used For | Delay | Thread communication |
| Requires synchronized | No | Yes |
| Wake Up | Automatically after time | notify()/notifyAll() |
Important Interview Point:
wait() is part of Java synchronization mechanism, while sleep() is mainly used for delays or pauses.
**87. What are thread priorities?
Thread priority is a value assigned to a thread that indicates its importance to the thread scheduler.
The scheduler may use priority to decide which thread should execute first.
Priority Range
Java thread priorities range from:
1 to 10
Constants in Thread Class
| Constant | Value |
|---|---|
| MIN_PRIORITY | 1 |
| NORM_PRIORITY | 5 |
| MAX_PRIORITY | 10 |
Example
class Test extends Thread {
public void run() {
System.out.println(Thread.currentThread().getPriority());
}
public static void main(String[] args) {
Test t1 = new Test();
t1.setPriority(8);
t1.start();
}
}
Important Methods
Set Priority
setPriority(int priority)
Get Priority
getPriority()
Important Points
- Higher priority threads may get more CPU time.
- Thread scheduling behavior depends on JVM and operating system.
- Priority does NOT guarantee execution order.
Important Interview Point:
Thread priority is only a scheduling hint, not a strict rule.
Garbage Collection
***88. What is Garbage Collection?
Garbage Collection (GC) is an automatic memory management process in Java.
It removes unused objects from heap memory.
Purpose
To free memory occupied by unreachable objects.
Example
Student s = new Student();
s = null;
The object becomes eligible for garbage collection.
Who Performs Garbage Collection?
JVM Garbage Collector automatically performs cleanup.
Advantages
- Automatic memory management
- Prevents memory exhaustion
- Reduces manual memory errors
Important Interview Point:
Java developers cannot force garbage collection, they can only request it using:
System.gc();
***89. Why is Garbage Collection needed?
Garbage Collection is needed to manage memory automatically and efficiently.
Reasons for Garbage Collection
1. Prevent Memory Leaks
Unused objects are removed automatically.
2. Avoid Manual Memory Management
Unlike C/C++, Java developers do not manually free memory.
3. Improve Application Stability
Automatic cleanup prevents memory-related crashes.
4. Better Performance
Reclaims heap space for new objects.
Without Garbage Collection
Applications may suffer from:
- memory leaks
- OutOfMemoryError
- poor performance
Important Interview Point:
Garbage Collection works mainly on:
Heap Memory
**90. Difference between Heap and Stack memory
Heap and Stack are two major memory areas in Java.
Heap Memory
Used for:
- objects
- instance variables
Shared among threads.
Example
Student s = new Student();
Object stored in heap.
Stack Memory
Used for:
- method calls
- local variables
- function execution
Each thread has its own stack.
Example
int x = 10;
Local variable stored in stack.
Difference Table
| Feature | Heap Memory | Stack Memory |
|---|---|---|
| Stores | Objects | Local variables |
| Shared | Yes | No |
| Memory Management | Garbage Collector | Automatic |
| Access Speed | Slower | Faster |
| Size | Larger | Smaller |
Important Interview Point:
Objects live in heap, references may live in stack.
**91. What is memory leak?
A memory leak occurs when unused objects remain in memory and are not garbage collected.
As a result:
- memory usage keeps increasing
- application performance decreases
Common Causes
- Unclosed resources
- Static collections
- Holding unnecessary references
Example
List<Object> list = new ArrayList<>();
while(true) {
list.add(new Object());
}
Objects remain referenced and cannot be garbage collected.
Effects of Memory Leak
- High memory consumption
- Slow performance
- OutOfMemoryError
Prevention
- Remove unused references
- Close resources properly
- Use weak references when needed
Important Interview Point:
Java has garbage collection, but memory leaks can still occur if references are retained unnecessarily.
*92. What makes objects eligible for garbage collection?
An object becomes eligible for garbage collection when it is no longer reachable.
Common Cases
1. Null Reference
Student s = new Student();
s = null;
2. Reassigning Reference
Student s1 = new Student();
s1 = new Student();
Old object becomes unreachable.
3. Anonymous Objects
new Student();
No reference stored.
4. Objects Inside Method
Objects become eligible after method execution if no reference exists.
5. Island of Isolation
Objects referencing each other but unreachable externally.
Example
class Test {
Test t;
public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test();
t1.t = t2;
t2.t = t1;
t1 = null;
t2 = null;
}
}
Both objects become eligible.
Important Interview Point:
Eligibility does NOT guarantee immediate garbage collection.
Java Keywords
***93. Difference between final, finally, and finalize
These three terms are different concepts in Java.
final
Keyword used to restrict modification.
finally
Block used in exception handling.
finalize()
Method called by garbage collector before object destruction.
Difference Table
| Feature | final | finally | finalize() |
|---|---|---|---|
| Type | Keyword | Block | Method |
| Purpose | Restriction | Cleanup | GC cleanup |
| Used With | Variable/method/class | try-catch | Object class |
| Execution | Compile-time rule | Always executes | Before GC |
Important Interview Point:
finalize() is deprecated in modern Java versions because it is unreliable.
***94. Uses of final keyword in variable, method, and class
The final keyword is used to apply restrictions.
1. final Variable
Value cannot be changed.
Example
final int x = 10;
2. final Method
Cannot be overridden.
Example
final void display() {
}
3. final Class
Cannot be inherited.
Example
final class Test {
}
Real Example
String
class is final.
Summary Table
| Usage | Restriction |
|---|---|
| final variable | Value cannot change |
| final method | Cannot override |
| final class | Cannot inherit |
Important Interview Point:
Blank final variables must be initialized inside constructor.
**95. What is static keyword?
static is used for memory management in Java.
It makes members belong to the class instead of objects.
Static Members
- static variables
- static methods
- static blocks
- static nested classes
Example
class Test {
static int count = 0;
}
Features
- Shared among all objects
- Memory allocated once
- Accessed using class name
Access Example
Test.count
Important Interview Point:
Static methods cannot directly access non-static members.
**96. Can static methods be overloaded?
Yes, static methods can be overloaded.
Example
class Test {
static void show() {
System.out.println("No arguments");
}
static void show(int x) {
System.out.println(x);
}
}
Why Allowed?
Because method overloading depends on:
- method signature
- parameter list
not on runtime behavior.
Important Interview Point:
Static method overloading is resolved at compile time.
**97. Can static methods be overridden?
No, static methods cannot be truly overridden.
They can only be:
Method Hidden
Example
class Parent {
static void display() {
System.out.println("Parent");
}
}
class Child extends Parent {
static void display() {
System.out.println("Child");
}
}
Method Call
Parent p = new Child();
p.display();
Output:
Parent
Because static methods are resolved using reference type.
Important Interview Point:
Static methods belong to class, not objects, so runtime polymorphism does not apply.
98. What is transient keyword?
transient is used in serialization to skip variables during object serialization.
Purpose
Sensitive or unnecessary data should not be saved.
Example
class Student implements Serializable {
int id;
transient String password;
}
Serialization Result
-
idgets serialized -
passwordis skipped
Use Cases
- Passwords
- Security tokens
- Temporary data
Important Interview Point:
Transient variables get default values during deserialization.