Java Interview Preparation - Complete
Theory & Detailed Notes
1. Introduction to Java
Java is a high-level, class-based, object-oriented programming language that is designed to
have as few implementation dependencies as possible.
Developed by James Gosling in 1995 at Sun Microsystems (later acquired by Oracle).
It is platform-independent because Java programs are compiled into bytecode, which runs
on any system that has the Java Virtual Machine (JVM).
Key Principles:
- Simple: Syntax similar to C++, but without complexities like operator overloading and
multiple inheritance (handled via interfaces).
- Secure: No explicit pointer use, runs in a sandboxed environment, and has a bytecode
verifier.
- Portable: Bytecode can run anywhere.
- Robust: Strong memory management and exception handling.
- Multithreaded: Built-in support for multithreaded programming.
- High Performance: Just-In-Time (JIT) compiler for faster execution.
- Distributed: Supports Remote Method Invocation (RMI) and other distributed computing.
Java Editions:
- Java SE (Standard Edition): Core Java features.
- Java EE (Enterprise Edition): APIs for web and enterprise apps.
- Java ME (Micro Edition): For mobile and embedded devices.
2. JVM, JRE, JDK
JVM (Java Virtual Machine):
- Abstract machine that provides runtime environment to execute Java bytecode.
- Responsibilities: Loads code, verifies code, executes code, manages memory.
- Components: Class Loader, Runtime Data Areas, Execution Engine, Garbage Collector.
JRE (Java Runtime Environment):
- Contains JVM + Libraries required to run Java applications.
- Does not include development tools.
JDK (Java Development Kit):
- JRE + Development tools (compiler javac, debugger, etc.).
- Needed for Java application development.
3. Java Syntax Basics
A Java program consists of classes and methods.
Example:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
Identifiers: Names for classes, variables, methods. Rules: Cannot start with digit, no special
chars except _, $, case-sensitive.
Keywords: Reserved words like public, static, class, return, etc.
Variables: Local (inside methods), Instance (inside class, non-static), Static (class-level).
Data Types:
- Primitive: byte, short, int, long, float, double, char, boolean.
- Non-Primitive: String, Arrays, Classes, Interfaces.
Type Casting:
- Widening: Automatic conversion to larger type (int to double).
- Narrowing: Explicit conversion to smaller type (double to int).
4. OOP Concepts
Encapsulation: Binding data and methods together. Achieved via private fields + public
getters/setters.
Inheritance: Mechanism to acquire properties/methods from another class using 'extends'.
Supports single, multilevel, hierarchical inheritance. Multiple inheritance via interfaces.
Polymorphism: Ability to perform actions in different ways.
- Compile-time: Method Overloading.
- Runtime: Method Overriding.
Abstraction: Hiding implementation details using abstract classes and interfaces.
Access Modifiers: public, private, protected, default.
5. Strings in Detail
String is a sequence of characters stored as an object in Java.
Immutable: Once created, cannot be modified. Any modification creates a new String.
String Pool: Stores string literals for memory efficiency.
Important Methods: length(), charAt(), substring(), equals(), compareTo(), trim(), replace(),
toLowerCase(), toUpperCase().
StringBuilder (mutable, faster) and StringBuffer (mutable, thread-safe).
6. Arrays
Fixed-size collection of elements of the same type.
Syntax: int[] arr = new int[5];
Multidimensional arrays: int[][] matrix = {{1,2},{3,4}};
Utility Methods: Arrays.sort(), Arrays.equals(), Arrays.binarySearch().
7. Collections Framework
Set of classes and interfaces for storing groups of data.
Hierarchy: Iterable -> Collection -> List/Set/Queue.
List: ArrayList, LinkedList, Vector.
Set: HashSet, LinkedHashSet, TreeSet.
Queue: PriorityQueue, ArrayDeque.
Map: HashMap, LinkedHashMap, TreeMap.
Utility: Collections.sort(), Collections.reverse(), Collections.max().
8. Exception Handling
Mechanism to handle runtime errors.
Types:
- Checked: Compile-time check (IOException).
- Unchecked: Runtime exceptions (NullPointerException).
- Errors: Serious issues (OutOfMemoryError).
Keywords: try, catch, finally, throw, throws.
Custom Exceptions can be created by extending Exception class.
9. Multithreading
Ability to run multiple threads concurrently.
Thread creation:
- Extending Thread class.
- Implementing Runnable interface.
Thread states: New, Runnable, Running, Waiting, Terminated.
Synchronization ensures thread safety.
Concurrent Collections: ConcurrentHashMap, CopyOnWriteArrayList.
10. Java Memory Management
Stack: Stores method calls and local variables.
Heap: Stores objects.
Garbage Collector: Removes unused objects automatically.
Reference Types: Strong, Weak, Soft, Phantom.
11. Java 8+ Features
Lambdas: (parameters) -> expression.
Streams API: filter(), map(), reduce().
Default methods in interfaces.
Optional class to handle nulls.
Method references: ClassName::methodName.
12. File Handling
File class for file metadata.
Reading: FileReader, BufferedReader, Scanner.
Writing: FileWriter, BufferedWriter.
Serialization: ObjectOutputStream, ObjectInputStream.
13. Java Keywords Detailed
static: Belongs to the class, not instance.
final: Constant variable, non-overridable method, non-inheritable class.
this: Refers to current object.
super: Refers to parent class.
volatile: Ensures visibility in multithreading.
synchronized: Thread-safe method/block.
14. Design Patterns
Singleton: One instance per application.
Factory: Creates objects without exposing creation logic.
Builder: Builds complex objects step-by-step.
Observer: Publisher-Subscriber model.
Strategy: Select algorithm at runtime.
15. Common Programs
Palindrome check, Fibonacci, Prime number, Factorial.
Sorting: Bubble, Merge, Quick sort.
String reversal, Anagram check.