Java Interview Q&A

12th of August, 2026
Mind Mapping Flow β
- Define OOP
- Classes, Modifiers and Constructors
- The 4 Pillars of OOP Programming : *Encapsulation *Inheritance *Polymorphism *Abstraction
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
- Exception Handling
- IO Operations
Java OOP Interview Q & A
Q1: Keyword Definitions β
Important Keyword definitions
| Keyword / Construct | Meaning |
|---|---|
class | Defines a class, a blueprint/template that defines properties and behavior |
object | Instance of a class, actual thing created from the blueprint |
interface | Defines an interface |
extends | Inherits a class |
implements | Implements an interface |
this | Current object |
super | Parent class |
static | Belongs to class |
final | Prevents further change/inheritance/overriding |
finally | Executes after try/catch |
finalize() | Legacy garbage collection cleanup method; deprecated |
abstract | Defines incomplete abstraction |
private | Class-level access |
protected | Package + subclass access |
public | Broad access |
new | Creates an object |
void | Indicates a method returns no value |
main | Entry point of a Java application |
if | Conditional execution |
else | Alternative conditional branch |
switch | Selects between multiple cases |
break | Exits a loop or switch |
continue | Skips to the next loop iteration |
throw | Throws an exception |
throws | Declares exceptions |
try | Starts exception-handling/resource block |
try-with-resources | Automatically closes resources |
instanceof | Checks type relationship |
Q2: Four Pillars of Object Oriented Programming β
The four pillars of OOP are:
- Encapsulation β controls access to an object's internal state.
- Inheritance β allows a class to inherit and extend another class.
- Polymorphism β allows the same interface/method call to have different behavior.
- Abstraction β hides implementation details and exposes essential behavior.
| Pillar | Core Idea | Common Keywords / Concepts |
|---|---|---|
| Encapsulation | Bundle data + behavior and control access to internal state | private, public, protected, getters, setters |
| Inheritance | Derive a class from another class | extends, parent/superclass, child/subclass, IS-A |
| Polymorphism | Same interface/method call, different behavior | Overloading, overriding, compile-time, runtime |
| Abstraction | Hide implementation details and expose essential behavior | abstract, interface, abstract class, concrete class |
2.1 Q: What is Encapsulation β
Encapsulation is the practice of bundling an object's data and the methods that operate on that data, while controlling direct access to its internal state.
Key Concepts β
| Concept | Definition |
|---|---|
| Data / State | Fields or attributes that store an object's information |
| Behavior | Methods that operate on the object's data |
| Access Modifiers | Control who can access a class member |
private | Accessible only within the class |
protected | Accessible within the class and its subclasses/package depending on language |
public | Accessible from anywhere allowed by the language |
| Getter | Method used to read/access a value |
| Setter | Method used to modify a value |
| Information Hiding | Hiding internal implementation/state from outside code |
Example β
class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}Here, balance is private, so outside code cannot directly modify it.
Instead, the class controls how the value is accessed or changed.
Q: Why use getters and setters? β
Getters and setters provide controlled access to an object's state and allow validation or business rules to be applied.
Common Pitfall β
Encapsulation does NOT simply mean making everything
private.
private is a tool used to achieve encapsulation.
The bigger idea is controlling access to and protecting an object's internal state.
2.2 What is Inheritance? β
Inheritance allows a child/subclass to acquire and extend the properties and behavior of a parent/superclass.
It is commonly used to represent an IS-A relationship.
Example β
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}Dog IS-A Animal, so Dog inherits eat() from Animal.
Key Concepts β
| Concept | Definition |
|---|---|
| Superclass / Parent | The class being inherited from |
| Subclass / Child | The class that inherits from the parent |
extends | Used for class inheritance in Java |
| IS-A | Relationship represented by inheritance |
| Code Reuse | Reusing inherited properties/behavior |
| Method Overriding | Subclass provides its own implementation of an inherited method |
Q: When should you use inheritance? β
Use inheritance when there is a genuine IS-A relationship and the child is logically a specialized version of the parent.
Common Pitfall β
Don't use inheritance only because two classes share code.
Sometimes composition is a better design.
Inheritance = IS-AComposition = HAS-A
Example:
Dog IS-A Animal
Car HAS-A Engine2.3 What is Polymorphism? β
Polymorphism means "many forms." It allows the same interface or method call to have different behavior depending on the object or arguments involved.
Two Common Types β
| Type | Also Called | Determined At | Main Idea |
|---|---|---|---|
| Overloading | Compile-time polymorphism | Compile time | Same method name, different parameters |
| Overriding | Runtime polymorphism | Runtime | Subclass provides a different implementation |
What is Method Overloading? β
Overloading occurs when multiple methods have the same name but different parameter lists.
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}The compiler determines which add() method to use based on the arguments.
Important β
Changing only the return type does not create an overloaded method.
int add(int a, int b)
double add(int a, int b) // NOT valid overloadingWhat is Method Overriding? β
Overriding occurs when a subclass provides its own implementation of a method inherited from its parent class.
class Animal {
void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}Animal animal = new Dog();
animal.makeSound();Output:
BarkEven though the reference type is Animal, the actual object is Dog, so the overridden Dog implementation is executed.
Overloading vs Overriding β
| Overloading | Overriding | |
|---|---|---|
| Purpose | Multiple versions of a method | Replace/extend inherited behavior |
| Relationship | Usually within the same class | Requires inheritance |
| Parameters | Must be different | Must match the inherited method |
| Return type | Cannot differ only by return type | Must be compatible |
| Binding | Compile time | Runtime |
| Polymorphism | Compile-time | Runtime |
Easy Way to Remember β
Overloading = same name, different parameters.Overriding = same method, different implementation.
2.4 What is Abstraction? β
Abstraction means exposing the essential behavior of an object while hiding unnecessary implementation details.
Think:
What does it do? β Abstraction How does it do it? β Implementation
Example β
interface Payment {
void pay(double amount);
}The interface tells us that a Payment can pay().
It does not expose how the payment is processed.
class CreditCardPayment implements Payment {
public void pay(double amount) {
// Credit card implementation
}
}The user of Payment does not need to know the internal implementation.
Abstract Class vs Interface β
Both are commonly used to achieve abstraction, but they serve different purposes.
| Abstract Class | Interface | |
|---|---|---|
| Main purpose | Define a common base/abstraction | Define a contract/capability |
| Abstract methods | Yes | Yes |
| Concrete methods | Yes | Yes, e.g. default/static methods in Java |
| Instance state/fields | Yes | No ordinary instance fields |
| Constructor | Yes | No |
| Class inheritance | A class can extend only one class | A class can implement multiple interfaces |
| Keywords | abstract, extends | interface, implements |
Example: Abstract Class β
abstract class Animal {
abstract void makeSound();
void eat() {
System.out.println("Eating");
}
}The abstract class provides some common behavior but leaves makeSound() for subclasses to implement.
Example: Interface β
interface Flyable {
void fly();
}
class Bird implements Flyable {
public void fly() {
System.out.println("Flying");
}
}The interface defines a contract: any class implementing Flyable must provide fly().
Abstract Class vs Concrete Class β
| Abstract Class | Concrete Class | |
|---|---|---|
| Can be instantiated? | No | Yes |
| Can contain abstract methods? | Yes | No |
| Can contain implemented methods? | Yes | Yes |
| Main purpose | Provide a base/template for subclasses | Provide a complete implementation |
Easy Way to Remember
Abstract = incomplete / cannot be directly instantiatedConcrete = complete / can be instantiated
Where Do the Common Concepts Belong? β
This is the easiest way to organize everything for an interview:
OOP
β
βββ 1. Encapsulation
β βββ Data + methods
β βββ Access control
β βββ private / protected / public
β βββ Getters / setters
β βββ Information hiding
β
βββ 2. Inheritance
β βββ Parent / child
β βββ extends
β βββ IS-A relationship
β βββ Code reuse
β βββ Method overriding
β
βββ 3. Polymorphism
β βββ Overloading
β β βββ Compile-time
β β
β βββ Overriding
β βββ Runtime
β
βββ 4. Abstraction
βββ Hide implementation details
βββ Abstract class
βββ Concrete class
βββ InterfaceCommon Interview Pitfalls β
| Topic | Key Point |
|---|---|
| Encapsulation | Encapsulation is about controlling access to internal state, not simply making fields private. |
| Getters/Setters | Getters and setters are mechanisms for controlled access to an object's state. |
| Inheritance | Inheritance represents an IS-A relationship; code reuse is a benefit, not the only purpose. |
| Polymorphism | Polymorphism allows the same interface/method call to have different behavior. |
| Overloading | Same method name + different parameter list. Changing only the return type is not enough. |
| Overriding | A subclass provides its own implementation of an inherited method. |
| Abstraction | Abstraction is about hiding implementation details and exposing essential behavior. |
| Interface | An interface is primarily a contract/capability. Modern Java interfaces can also contain default and static methods. |
| Abstract Class | An abstract class can contain both abstract and concrete methods. |
| Concrete Class | A concrete class is not abstract and can be instantiated. |
| Inheritance vs Composition | Inheritance = IS-A; Composition = HAS-A. |
β 30-Second Interview Answer
The four pillars of OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction.
Encapsulation bundles data and behavior together and controls access to an object's internal state.
Inheritance allows a child class to inherit and extend behavior from a parent class, representing an IS-A relationship.
Polymorphism allows the same interface or method call to have different behavior, commonly through overloading and overriding.
Abstraction hides implementation details and exposes only the essential behavior, commonly using abstract classes and interfaces.
Q3: Exceptions β
3.1 What is an Exception? β
An exception is an object representing an abnormal condition that occurs during program execution and can disrupt the normal flow of a program.
Java allows exceptions to be thrown, caught, and propagated.
Example β
int result = 10 / 0;This causes an ArithmeticException.
We can handle it with:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}Key Concepts
| Concept | Meaning |
|---|---|
| Throw | An exception is generated/raised during execution |
| Catch | Handle the exception |
| Propagate | Pass an unhandled exception up the call stack |
| Handle | Take appropriate action when an exception occurs |
| ::: |
3.2 Exception Hierarchy β
Throwable
βββ Error
β βββ OutOfMemoryError
β βββ StackOverflowError
β
βββ Exception
βββ RuntimeException
β βββ NullPointerException
β βββ ArithmeticException
β βββ IndexOutOfBoundsException
β
βββ Other checked exceptions
βββ IOException
βββ SQLException
βββ ...Key Concepts
| Type | Meaning |
|---|---|
Throwable | Root type for things that can be thrown and caught |
Exception | Represents conditions that applications may want to handle |
RuntimeException | Base class for unchecked exceptions |
Error | Represents serious problems that applications generally should not attempt to handle |
Important:
Throwableis the root of the hierarchy. BothExceptionandErrorextendThrowable.
3.3 Checked vs Unchecked Exceptions β
What is the difference between Checked and Unchecked Exceptions?
| Checked Exception | Unchecked Exception | |
|---|---|---|
| Checked by compiler? | Yes | No |
| Must be caught or declared? | Yes | No |
| Parent | Exception (excluding RuntimeException and its subclasses) | RuntimeException |
| Examples | IOException, SQLException | NullPointerException, IllegalArgumentException |
Checked Exception β
The compiler requires the exception to be either:
- handled with
try-catch, or - declared with
throws.
void readFile() throws IOException {
// ...
}Unchecked Exception β
The compiler does not require you to catch or declare it.
String name = null;
System.out.println(name.length());This results in:
NullPointerExceptionInterview Answer β
Checked exceptions are checked by the compiler and must be caught or declared. Unchecked exceptions are
RuntimeExceptionand its subclasses, so the compiler does not require them to be caught or declared.
Important Pitfall β
Do not define checked exceptions as simply "recoverable" and unchecked exceptions as "programming errors."
The important technical distinction is:
Checked β compiler requires catch-or-declare.Unchecked β compiler does not require catch-or-declare.
3.4 try, catch, and finally β
Q: How do you handle exceptions? β
The basic structure is:
try β code that may throw an exception
catch β handles the exception
finally β cleanup codeExample β
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Invalid calculation");
} finally {
System.out.println("Cleanup");
}Keywords β
| Keyword | Purpose |
|---|---|
try | Contains code that may throw an exception |
catch | Handles a matching exception |
finally | Used for cleanup code |
throw | Explicitly throws an exception |
throws | Declares exceptions that a method may throw |
About finally β
finallynormally executes aftertry/catch, whether or not an exception occurs.
It is not an absolute guarantee. For example, if the JVM terminates before the finally block can execute, it may not run.
For resource cleanup, try-with-resources is generally preferred.
3.5 throw vs throws β
Q: What is the difference between throw and throws? β
throw | throws | |
|---|---|---|
| Purpose | Actually throws an exception | Declares exceptions a method may throw |
| Location | Method body | Method signature |
| Example | throw new Exception(); | method() throws Exception |
| Think | Action | Declaration |
| ::: |
throw β
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older");
}You're explicitly throwing an exception.
throws β
void readFile() throws IOException {
// ...
}You're declaring that the method may throw an IOException.
Easy Memory Trick β
throw= actually throwthrows= declare
3.6 Exception Propagation β
Q: What happens if an exception is not handled? β
If an exception is not caught in the current method, it propagates up the call stack until a matching
catchblock is found.
main()
β
methodA()
β
methodB()
β
methodC()
β
Exception occurs
β
β propagates
β
matching catchExample β
void methodC() {
int x = 10 / 0;
}
void methodB() {
methodC();
}
void methodA() {
methodB();
}If methodC() doesn't catch the exception, it can propagate through methodB() and methodA().
If it reaches the top of the thread's call stack without being caught, the thread terminates and the exception is reported.
Interview Answer β
Exception propagation means an uncaught exception moves up the call stack until a matching handler is found or the exception reaches the top of the thread's stack.
3.7 Multiple catch Blocks β
Q: Can we have multiple catch blocks? β
Yes.
try {
// code
} catch (ArithmeticException e) {
// handle arithmetic exception
} catch (NullPointerException e) {
// handle null pointer exception
} catch (Exception e) {
// handle other exceptions
}Important Rule β
More specific exceptions must come before more general exceptions.
Correct:
catch (ArithmeticException e) {
} catch (Exception e) {
}Incorrect:
catch (Exception e) {
} catch (ArithmeticException e) {
}The second catch is unreachable because Exception already catches ArithmeticException.
3.8 Try-with-Resources β
Q: What is try-with-resources? β
Try-with-resources automatically closes resources that implement
AutoCloseablewhen thetryblock finishes.
Example β
try (FileReader reader = new FileReader("file.txt")) {
// use reader
} catch (IOException e) {
// handle exception
}The reader is automatically closed.
Why use it? β
- Automatically closes resources
- Reduces cleanup code
- Helps prevent resource leaks
- Makes resource management safer and cleaner
Common examples:
FileReaderInputStream- Database resources
- Network resources
Important Detail β
If multiple resources are declared:
try (
ResourceA a = ...;
ResourceB b = ...
) {
// ...
}They are closed in reverse order of declaration:
ResourceB β ResourceA3.9 Custom Exceptions β
Q: Can we create our own exceptions? β
Yes.
Custom exceptions allow us to represent application-specific exceptional conditions.
Checked Custom Exception β
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}Unchecked Custom Exception β
class InvalidAmountException extends RuntimeException {
public InvalidAmountException(String message) {
super(message);
}
}Difference β
extends Exception
β Checked exception
extends RuntimeException
β Unchecked exception3.10 Common Exception Keywords β
| Keyword | Meaning |
|---|---|
try | Defines code that may throw an exception |
catch | Handles a matching exception |
finally | Defines cleanup code that normally executes afterward |
throw | Explicitly throws an exception |
throws | Declares exceptions a method may throw |
3.11 Common Interview Comparisons β
Checked vs Unchecked β
| Checked | Unchecked | |
|---|---|---|
| Compiler checks it? | Yes | No |
| Must catch or declare? | Yes | No |
| Base type | Exception | RuntimeException |
| Example | IOException | NullPointerException |
| Main distinction | Compile-time requirement | No compile-time requirement |
throw vs throws β
throw | throws | |
|---|---|---|
| Purpose | Actually throws an exception | Declares possible exceptions |
| Location | Method body | Method signature |
| Example | throw new Exception(); | method() throws Exception |
| Remember | Action | Declaration |
| ::: |
Exception vs Error β
| Exception | Error | |
|---|---|---|
| Parent | Throwable | Throwable |
| Meaning | Conditions applications may handle | Serious problems applications generally should not handle |
| Examples | IOException, RuntimeException | OutOfMemoryError, StackOverflowError |
| Typical handling | May be caught/handled | Generally not caught for recovery |
3.12 final vs finally vs finalize() β
| Meaning | |
|---|---|
final | Modifier used to restrict reassignment, overriding, or inheritance |
finally | Block associated with try/catch, typically used for cleanup |
finalize() | Deprecated object-finalization mechanism that should not be used |
Easy Memory Trick β
final= modifierfinally= cleanup blockfinalize()= deprecated old finalization mechanism
3.13 Common Interview Pitfalls β
| Topic | Key Point |
|---|---|
| Exception vs Error | Both extend Throwable, but Error represents serious problems that applications generally should not attempt to handle. |
Throwable | The root type of Java's throwable hierarchy. |
| Checked Exception | Must be caught or declared. |
| Unchecked Exception | RuntimeException and its subclasses; no compiler requirement to catch or declare. |
throw vs throws | throw actually throws; throws declares. |
finally | Normally executes after try/catch, but is not an absolute guarantee. |
Multiple catch | More specific exceptions must come before more general ones. |
| Exception propagation | An uncaught exception moves up the call stack until handled or it reaches the top of the thread's stack. |
| Try-with-resources | Automatically closes AutoCloseable resources. Multiple resources close in reverse declaration order. |
| Custom exceptions | Extend Exception for checked exceptions or RuntimeException for unchecked exceptions. |
Catching Exception everywhere | Can hide the actual problem; catch specific exceptions when appropriate. |
Empty catch blocks | Can silently swallow failures and make debugging difficult. |
β 30-Second Interview Answer β
An exception is an object representing an abnormal condition during program execution that can disrupt the normal flow of a program.
In Java, exceptions are part of the
Throwablehierarchy, which containsExceptionandError. Exceptions can be checked or unchecked. Checked exceptions are verified by the compiler and must be caught or declared, while unchecked exceptions extendRuntimeExceptionand don't have that requirement.We use
tryandcatchto handle exceptions,finallyfor cleanup,throwto explicitly throw an exception, andthrowsto declare exceptions a method may throw.If an exception isn't handled, it propagates up the call stack. Java also provides try-with-resources to automatically close resources.
Q4: I/O Operations β
4.1 What is I/O? β
Q: What is I/O? β
I/O (Input/Output) refers to reading data from a source and writing data to a destination.
- Input β data coming into the program
- Output β data going out of the program
Examples:
Input:
Keyboard
File
Network
Database
Output:
Console
File
Network
DatabaseIn Java, I/O is primarily handled through the java.io package, while modern file operations are commonly handled through java.nio.file.
Key Concepts β
| Concept | Meaning |
|---|---|
| Input | Data coming into the program |
| Output | Data going out of the program |
| Read | Obtain data from a source |
| Write | Send data to a destination |
4.2 Input vs Output β
| Input | Output | |
|---|---|---|
| Direction | Source β Program | Program β Destination |
| Purpose | Read data | Write data |
| Common classes | InputStream, Reader | OutputStream, Writer |
| Example | Read from a file | Write to a file |
Easy Memory Trick β
Input = readOutput = write
4.3 Byte Streams vs Character Streams β
Q: What is the difference between Byte Streams and Character Streams? β
| Byte Stream | Character Stream | |
|---|---|---|
| Handles | Raw binary data | Text/character data |
| Main classes | InputStream, OutputStream | Reader, Writer |
| Unit | Bytes | Characters |
| Best for | Images, audio, PDFs, binary files | Text files |
| Examples | FileInputStream, FileOutputStream | FileReader, FileWriter |
Byte Streams β
Used for binary data.
try (InputStream input = new FileInputStream("image.jpg")) {
int data;
while ((data = input.read()) != -1) {
// process byte
}
} catch (IOException e) {
e.printStackTrace();
}Character Streams β
Used for text data.
try (Reader reader = new FileReader("file.txt")) {
int data;
while ((data = reader.read()) != -1) {
// process character
}
} catch (IOException e) {
e.printStackTrace();
}Interview Answer β
Byte streams handle raw binary data, while character streams are designed for text data. Byte streams use
InputStreamandOutputStream, while character streams useReaderandWriter.
4.4 InputStream vs Reader β
Q: What is the difference between InputStream and Reader? β
InputStream | Reader | |
|---|---|---|
| Type of data | Bytes | Characters |
| Used for | Binary data | Text data |
| Common subclass | FileInputStream | FileReader |
| Parent abstraction | Byte stream | Character stream |
Similarly:
InputStream β reading bytes
OutputStream β writing bytes
Reader β reading characters
Writer β writing characters4.5 What is a Stream? β
Q: What is a stream in Java I/O? β
A stream represents a flow of data between a source and a destination.
For example:
File
β
InputStream
β
Java Programor:
Java Program
β
OutputStream
β
FileA stream is not necessarily a file. Streams can work with:
- Files
- Memory
- Network connections
- Other streams
4.6 Buffered I/O β
Q: What is buffering and why is it used? β
Buffering temporarily stores data in memory so that I/O operations can be performed more efficiently.
Instead of performing an expensive I/O operation for every small piece of data, a buffer allows data to be processed in larger chunks.
Common classes:
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriterExample β
try (BufferedReader reader =
new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}Why use buffering? β
- Reduces the number of direct I/O operations
- Improves performance
- Provides convenient methods such as
readLine()
Interview Answer β
Buffering improves I/O performance by temporarily storing data in memory and reducing the number of direct I/O operations.
4.7 File vs Path β
Q: What is the difference between File and Path? β
File | Path | |
|---|---|---|
| Package | java.io | java.nio.file |
| API | Older API | Modern API |
| Represents | File/directory path | File/directory path |
| Recommended for new code? | Generally no | Yes |
| Common operations | exists(), mkdir() | Used with Files |
Example with File β
File file = new File("data.txt");
if (file.exists()) {
System.out.println("File exists");
}Modern approach with Path β
Path path = Path.of("data.txt");
if (Files.exists(path)) {
System.out.println("File exists");
}For modern Java code, prefer
PathandFilesfor file-system operations.
4.8 Path and Files β
Q: What are Path and Files used for? β
Pathrepresents the location of a file or directory, whileFilesprovides utility methods for performing file-system operations.
Example:
Path path = Path.of("data.txt");
Files.writeString(path, "Hello World");
String content = Files.readString(path);
System.out.println(content);Common operations:
| Method | Purpose |
|---|---|
Files.exists() | Checks whether a path exists |
Files.createFile() | Creates a file |
Files.createDirectory() | Creates a directory |
Files.delete() | Deletes a file or directory |
Files.readString() | Reads a file as a String |
Files.writeString() | Writes a String to a file |
Files.copy() | Copies a file |
Files.move() | Moves or renames a file |
4.9 Reading and Writing Files β
Q: How can you read a text file in Java? β
For modern Java, a simple approach is:
Path path = Path.of("data.txt");
try {
String content = Files.readString(path);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}For larger files, reading line-by-line can be more appropriate:
try (BufferedReader reader = Files.newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}Q: How can you write to a text file? β
Path path = Path.of("data.txt");
try {
Files.writeString(path, "Hello World");
} catch (IOException e) {
e.printStackTrace();
}4.10 IOException β
Q: What is IOException? β
IOExceptionis a checked exception that indicates an I/O operation has failed or been interrupted.
Examples include problems involving:
- File access
- Reading/writing streams
- Network I/O
- Other I/O operations
Example:
try {
String content = Files.readString(Path.of("data.txt"));
} catch (IOException e) {
System.out.println("Could not read file");
}Because IOException is checked, it must be caught or declared.
void readFile() throws IOException {
String content = Files.readString(Path.of("data.txt"));
}4.11 Try-with-Resources and I/O β
Q: Why is try-with-resources important in I/O? β
I/O resources should be closed after use. Try-with-resources automatically closes resources that implement
AutoCloseable.
Example:
try (BufferedReader reader =
new BufferedReader(new FileReader("data.txt"))) {
String line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}The reader is automatically closed when the try block finishes.
Important β
Do not rely on
finallyto manually close resources when try-with-resources can be used.
Try-with-resources is safer and reduces the chance of resource leaks.
4.12 File vs Stream β
Q: What is the difference between a File and a Stream? β
| File | Stream | |
|---|---|---|
| Represents | Stored data/location | Flow of data |
| Purpose | Represents a file or directory | Reads or writes data |
| Example | Path, File | InputStream, OutputStream, Reader, Writer |
| Think | Where the data is | How data moves |
Easy Memory Trick β
File/Path = whereStream = how data flows
4.13 Common I/O Classes β
| Class | Purpose |
|---|---|
InputStream | Base class for byte input |
OutputStream | Base class for byte output |
Reader | Base class for character input |
Writer | Base class for character output |
FileInputStream | Reads bytes from a file |
FileOutputStream | Writes bytes to a file |
FileReader | Reads characters from a file |
FileWriter | Writes characters to a file |
BufferedReader | Buffered character input |
BufferedWriter | Buffered character output |
Path | Represents a file-system path |
Files | Provides file-system operations |
4.14 Common Interview Comparisons β
Byte Stream vs Character Stream β
| Byte Stream | Character Stream | |
|---|---|---|
| Data | Binary/raw data | Text/characters |
| Classes | InputStream, OutputStream | Reader, Writer |
| Best for | Images, audio, PDFs | Text files |
File vs Path β
File | Path | |
|---|---|---|
| API | Older | Modern |
| Package | java.io | java.nio.file |
| File operations | Methods on File | Usually through Files |
| New code | Generally prefer Path | Recommended |
InputStream vs Reader β
InputStream | Reader | |
|---|---|---|
| Reads | Bytes | Characters |
| Data | Binary/raw | Text |
| Example | FileInputStream | FileReader |
4.15 Common Interview Pitfalls β
| Topic | Key Point |
|---|---|
| Input vs Output | Input reads data into the program; output writes data from the program. |
| Byte vs Character streams | Byte streams are for raw/binary data; character streams are for text. |
InputStream vs Reader | InputStream reads bytes; Reader reads characters. |
OutputStream vs Writer | OutputStream writes bytes; Writer writes characters. |
| Buffering | Improves I/O performance by reducing direct I/O operations. |
File vs Path | File is the older API; Path with Files is generally preferred for modern code. |
Path vs Files | Path represents a location; Files performs file-system operations. |
IOException | A checked exception commonly associated with I/O failures. |
| Resource closing | Use try-with-resources for AutoCloseable resources. |
| Streams | A Java I/O stream is a flow of data, not necessarily a file. |
finally for closing resources | Possible, but try-with-resources is generally preferred. |
| Reading entire files | Convenient methods like readString() are useful for small files; large files may be better processed incrementally. |
β 30-Second Interview Answer β
I/O stands for Input/Output and refers to reading and writing data between a program and an external source or destination.
In Java, byte streams such as
InputStreamandOutputStreamhandle raw or binary data, while character streams such asReaderandWriterhandle text.For file operations, modern Java commonly uses
PathandFilesfromjava.nio.file. I/O operations can throw checked exceptions such asIOException, which must be caught or declared.For resources such as files and streams, try-with-resources should generally be used because it automatically closes the resources and helps prevent resource leaks.
Bonus: What is Software Development Life Cycle? β
SDLC Table from HWU
| Phase | Main Purpose | Key Activities | Relevant Roles | Java/OOP Connection |
|---|---|---|---|---|
| 1. Planning | Define what needs to be built and why. | Set objectives, scope, budget, feasibility, and timeline. | Project Manager, Business Analyst | Understand project goals before designing classes and features. |
| 2. Requirements Analysis | Identify what the system must do. | Gather functional and non-functional requirements; create the SRS. | Requirements Analyst, System Analyst | Convert requirements into use cases and system behavior. |
| 3. Design | Create the technical blueprint. | Design architecture, modules, databases, interfaces, and data flow. | Software Architect, UI/UX Designer, Database Designer | Apply encapsulation, inheritance, abstraction, polymorphism, interfaces, and design patterns. |
| 4. Development | Implement the software using code. | Write Java code, create classes and methods, perform unit testing, and integrate modules. | Java Developer, Backend Developer, Frontend Developer | Build reusable, maintainable, and loosely coupled object-oriented components. |
| 5. Testing | Verify quality and find defects. | Perform functional, integration, system, performance, security, and regression testing. | QA Engineer, Automation Tester, Performance Tester | Use JUnit/TestNG to test classes, methods, and object behavior. |
| 6. Deployment | Release the application to users. | Deploy to production, monitor the release, and provide documentation or training. | DevOps Engineer, System Administrator, IT Support | Package and deploy Java applications using tools such as Maven, Docker, or CI/CD pipelines. |
| 7. Maintenance | Keep the software reliable and up to date. | Fix bugs, apply updates, improve performance, and adapt to new requirements. | Support Engineer, Maintenance Engineer, System Analyst | Refactor code, fix defects, improve scalability, and maintain backward compatibility. |
Interview Flow
Planning β Requirements β Design β Development β Testing β Deployment β Maintenance
Short interview answer: βSDLC is the Software Development Life Cycle. It consists of seven phases: planning, requirements analysis, design, development, testing, deployment, and maintenance. In Java OOP projects, object-oriented principles are mainly applied during the design and development phases to create reusable, maintainable, and scalable software.β