Skip to content
Kittycat.tech logo

Java Interview Q&A

Contributor:
Pretty Image
Erica Madebeykin, MBA
πŸ‡¬πŸ‡§MBA Merit
πŸ‡¬πŸ‡§MSc Comp Sci student
Creation Date:
12th of August, 2026

Mind Mapping Flow ​

  1. Define OOP
  2. Classes, Modifiers and Constructors
  3. The 4 Pillars of OOP Programming : *Encapsulation *Inheritance *Polymorphism *Abstraction
  4. Encapsulation
  5. Inheritance
  6. Polymorphism
  7. Abstraction
  8. Exception Handling
  9. IO Operations

Java OOP Interview Q & A

Q1: Keyword Definitions ​

Important Keyword definitions
Keyword / ConstructMeaning
classDefines a class, a blueprint/template that defines properties and behavior
objectInstance of a class, actual thing created from the blueprint
interfaceDefines an interface
extendsInherits a class
implementsImplements an interface
thisCurrent object
superParent class
staticBelongs to class
finalPrevents further change/inheritance/overriding
finallyExecutes after try/catch
finalize()Legacy garbage collection cleanup method; deprecated
abstractDefines incomplete abstraction
privateClass-level access
protectedPackage + subclass access
publicBroad access
newCreates an object
voidIndicates a method returns no value
mainEntry point of a Java application
ifConditional execution
elseAlternative conditional branch
switchSelects between multiple cases
breakExits a loop or switch
continueSkips to the next loop iteration
throwThrows an exception
throwsDeclares exceptions
tryStarts exception-handling/resource block
try-with-resourcesAutomatically closes resources
instanceofChecks type relationship

Q2: Four Pillars of Object Oriented Programming ​

The four pillars of OOP are:

  1. Encapsulation – controls access to an object's internal state.
  2. Inheritance – allows a class to inherit and extend another class.
  3. Polymorphism – allows the same interface/method call to have different behavior.
  4. Abstraction – hides implementation details and exposes essential behavior.
PillarCore IdeaCommon Keywords / Concepts
EncapsulationBundle data + behavior and control access to internal stateprivate, public, protected, getters, setters
InheritanceDerive a class from another classextends, parent/superclass, child/subclass, IS-A
PolymorphismSame interface/method call, different behaviorOverloading, overriding, compile-time, runtime
AbstractionHide implementation details and expose essential behaviorabstract, 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 ​

ConceptDefinition
Data / StateFields or attributes that store an object's information
BehaviorMethods that operate on the object's data
Access ModifiersControl who can access a class member
privateAccessible only within the class
protectedAccessible within the class and its subclasses/package depending on language
publicAccessible from anywhere allowed by the language
GetterMethod used to read/access a value
SetterMethod used to modify a value
Information HidingHiding internal implementation/state from outside code

Example ​

java
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 ​

java
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 ​

ConceptDefinition
Superclass / ParentThe class being inherited from
Subclass / ChildThe class that inherits from the parent
extendsUsed for class inheritance in Java
IS-ARelationship represented by inheritance
Code ReuseReusing inherited properties/behavior
Method OverridingSubclass 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:

text
Dog IS-A Animal
Car HAS-A Engine

2.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 ​

TypeAlso CalledDetermined AtMain Idea
OverloadingCompile-time polymorphismCompile timeSame method name, different parameters
OverridingRuntime polymorphismRuntimeSubclass provides a different implementation

What is Method Overloading? ​

Overloading occurs when multiple methods have the same name but different parameter lists.

java
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.

java
int add(int a, int b)
double add(int a, int b) // NOT valid overloading

What is Method Overriding? ​

Overriding occurs when a subclass provides its own implementation of a method inherited from its parent class.

java
class Animal {
    void makeSound() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark");
    }
}
java
Animal animal = new Dog();
animal.makeSound();

Output:

text
Bark

Even though the reference type is Animal, the actual object is Dog, so the overridden Dog implementation is executed.

Overloading vs Overriding ​

OverloadingOverriding
PurposeMultiple versions of a methodReplace/extend inherited behavior
RelationshipUsually within the same classRequires inheritance
ParametersMust be differentMust match the inherited method
Return typeCannot differ only by return typeMust be compatible
BindingCompile timeRuntime
PolymorphismCompile-timeRuntime

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 ​

java
interface Payment {
    void pay(double amount);
}

The interface tells us that a Payment can pay().

It does not expose how the payment is processed.

java
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 ClassInterface
Main purposeDefine a common base/abstractionDefine a contract/capability
Abstract methodsYesYes
Concrete methodsYesYes, e.g. default/static methods in Java
Instance state/fieldsYesNo ordinary instance fields
ConstructorYesNo
Class inheritanceA class can extend only one classA class can implement multiple interfaces
Keywordsabstract, extendsinterface, implements

Example: Abstract Class ​

java
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 ​

java
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 ClassConcrete Class
Can be instantiated?NoYes
Can contain abstract methods?YesNo
Can contain implemented methods?YesYes
Main purposeProvide a base/template for subclassesProvide 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:

text
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
    └── Interface

Common Interview Pitfalls ​

TopicKey Point
EncapsulationEncapsulation is about controlling access to internal state, not simply making fields private.
Getters/SettersGetters and setters are mechanisms for controlled access to an object's state.
InheritanceInheritance represents an IS-A relationship; code reuse is a benefit, not the only purpose.
PolymorphismPolymorphism allows the same interface/method call to have different behavior.
OverloadingSame method name + different parameter list. Changing only the return type is not enough.
OverridingA subclass provides its own implementation of an inherited method.
AbstractionAbstraction is about hiding implementation details and exposing essential behavior.
InterfaceAn interface is primarily a contract/capability. Modern Java interfaces can also contain default and static methods.
Abstract ClassAn abstract class can contain both abstract and concrete methods.
Concrete ClassA concrete class is not abstract and can be instantiated.
Inheritance vs CompositionInheritance = 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 ​

java
int result = 10 / 0;

This causes an ArithmeticException.

We can handle it with:

java
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}

Key Concepts

ConceptMeaning
ThrowAn exception is generated/raised during execution
CatchHandle the exception
PropagatePass an unhandled exception up the call stack
HandleTake appropriate action when an exception occurs
:::

3.2 Exception Hierarchy ​

text
Throwable
β”œβ”€β”€ Error
β”‚   β”œβ”€β”€ OutOfMemoryError
β”‚   └── StackOverflowError
β”‚
└── Exception
    β”œβ”€β”€ RuntimeException
    β”‚   β”œβ”€β”€ NullPointerException
    β”‚   β”œβ”€β”€ ArithmeticException
    β”‚   └── IndexOutOfBoundsException
    β”‚
    └── Other checked exceptions
        β”œβ”€β”€ IOException
        β”œβ”€β”€ SQLException
        └── ...

Key Concepts

TypeMeaning
ThrowableRoot type for things that can be thrown and caught
ExceptionRepresents conditions that applications may want to handle
RuntimeExceptionBase class for unchecked exceptions
ErrorRepresents serious problems that applications generally should not attempt to handle

Important: Throwable is the root of the hierarchy. Both Exception and Error extend Throwable.


3.3 Checked vs Unchecked Exceptions ​

What is the difference between Checked and Unchecked Exceptions?

Checked ExceptionUnchecked Exception
Checked by compiler?YesNo
Must be caught or declared?YesNo
ParentException (excluding RuntimeException and its subclasses)RuntimeException
ExamplesIOException, SQLExceptionNullPointerException, IllegalArgumentException

Checked Exception ​

The compiler requires the exception to be either:

  • handled with try-catch, or
  • declared with throws.
java
void readFile() throws IOException {
    // ...
}

Unchecked Exception ​

The compiler does not require you to catch or declare it.

java
String name = null;

System.out.println(name.length());

This results in:

text
NullPointerException

Interview Answer ​

Checked exceptions are checked by the compiler and must be caught or declared. Unchecked exceptions are RuntimeException and 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:

text
try     β†’ code that may throw an exception
catch   β†’ handles the exception
finally β†’ cleanup code

Example ​

java
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Invalid calculation");
} finally {
    System.out.println("Cleanup");
}

Keywords ​

KeywordPurpose
tryContains code that may throw an exception
catchHandles a matching exception
finallyUsed for cleanup code
throwExplicitly throws an exception
throwsDeclares exceptions that a method may throw

About finally ​

finally normally executes after try/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? ​

throwthrows
PurposeActually throws an exceptionDeclares exceptions a method may throw
LocationMethod bodyMethod signature
Examplethrow new Exception();method() throws Exception
ThinkActionDeclaration
:::

throw ​

java
if (age < 18) {
    throw new IllegalArgumentException("Age must be 18 or older");
}

You're explicitly throwing an exception.

throws ​

java
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 catch block is found.

text
main()
  ↓
methodA()
  ↓
methodB()
  ↓
methodC()
  ↓
Exception occurs
  ↑
  β”‚ propagates
  β”‚
matching catch

Example ​

java
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.

java
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:

java
catch (ArithmeticException e) {

} catch (Exception e) {

}

Incorrect:

java
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 AutoCloseable when the try block finishes.

Example ​

java
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:

  • FileReader
  • InputStream
  • Database resources
  • Network resources

Important Detail ​

If multiple resources are declared:

java
try (
    ResourceA a = ...;
    ResourceB b = ...
) {
    // ...
}

They are closed in reverse order of declaration:

text
ResourceB β†’ ResourceA

3.9 Custom Exceptions ​

Q: Can we create our own exceptions? ​

Yes.

Custom exceptions allow us to represent application-specific exceptional conditions.

Checked Custom Exception ​

java
class InsufficientBalanceException extends Exception {

    public InsufficientBalanceException(String message) {
        super(message);
    }
}

Unchecked Custom Exception ​

java
class InvalidAmountException extends RuntimeException {

    public InvalidAmountException(String message) {
        super(message);
    }
}

Difference ​

text
extends Exception
    β†’ Checked exception

extends RuntimeException
    β†’ Unchecked exception

3.10 Common Exception Keywords ​

KeywordMeaning
tryDefines code that may throw an exception
catchHandles a matching exception
finallyDefines cleanup code that normally executes afterward
throwExplicitly throws an exception
throwsDeclares exceptions a method may throw

3.11 Common Interview Comparisons ​

Checked vs Unchecked ​

CheckedUnchecked
Compiler checks it?YesNo
Must catch or declare?YesNo
Base typeExceptionRuntimeException
ExampleIOExceptionNullPointerException
Main distinctionCompile-time requirementNo compile-time requirement

throw vs throws ​

throwthrows
PurposeActually throws an exceptionDeclares possible exceptions
LocationMethod bodyMethod signature
Examplethrow new Exception();method() throws Exception
RememberActionDeclaration
:::

Exception vs Error ​

ExceptionError
ParentThrowableThrowable
MeaningConditions applications may handleSerious problems applications generally should not handle
ExamplesIOException, RuntimeExceptionOutOfMemoryError, StackOverflowError
Typical handlingMay be caught/handledGenerally not caught for recovery

3.12 final vs finally vs finalize() ​

Meaning
finalModifier used to restrict reassignment, overriding, or inheritance
finallyBlock 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 ​

TopicKey Point
Exception vs ErrorBoth extend Throwable, but Error represents serious problems that applications generally should not attempt to handle.
ThrowableThe root type of Java's throwable hierarchy.
Checked ExceptionMust be caught or declared.
Unchecked ExceptionRuntimeException and its subclasses; no compiler requirement to catch or declare.
throw vs throwsthrow actually throws; throws declares.
finallyNormally executes after try/catch, but is not an absolute guarantee.
Multiple catchMore specific exceptions must come before more general ones.
Exception propagationAn uncaught exception moves up the call stack until handled or it reaches the top of the thread's stack.
Try-with-resourcesAutomatically closes AutoCloseable resources. Multiple resources close in reverse declaration order.
Custom exceptionsExtend Exception for checked exceptions or RuntimeException for unchecked exceptions.
Catching Exception everywhereCan hide the actual problem; catch specific exceptions when appropriate.
Empty catch blocksCan 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 Throwable hierarchy, which contains Exception and Error. Exceptions can be checked or unchecked. Checked exceptions are verified by the compiler and must be caught or declared, while unchecked exceptions extend RuntimeException and don't have that requirement.

We use try and catch to handle exceptions, finally for cleanup, throw to explicitly throw an exception, and throws to 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:

text
Input:
Keyboard
File
Network
Database

Output:
Console
File
Network
Database

In Java, I/O is primarily handled through the java.io package, while modern file operations are commonly handled through java.nio.file.

Key Concepts ​

ConceptMeaning
InputData coming into the program
OutputData going out of the program
ReadObtain data from a source
WriteSend data to a destination

4.2 Input vs Output ​

InputOutput
DirectionSource β†’ ProgramProgram β†’ Destination
PurposeRead dataWrite data
Common classesInputStream, ReaderOutputStream, Writer
ExampleRead from a fileWrite 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 StreamCharacter Stream
HandlesRaw binary dataText/character data
Main classesInputStream, OutputStreamReader, Writer
UnitBytesCharacters
Best forImages, audio, PDFs, binary filesText files
ExamplesFileInputStream, FileOutputStreamFileReader, FileWriter

Byte Streams ​

Used for binary data.

java
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.

java
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 InputStream and OutputStream, while character streams use Reader and Writer.


4.4 InputStream vs Reader ​

Q: What is the difference between InputStream and Reader? ​

InputStreamReader
Type of dataBytesCharacters
Used forBinary dataText data
Common subclassFileInputStreamFileReader
Parent abstractionByte streamCharacter stream

Similarly:

text
InputStream  β†’ reading bytes
OutputStream β†’ writing bytes

Reader       β†’ reading characters
Writer       β†’ writing characters

4.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:

text
File
  ↓
InputStream
  ↓
Java Program

or:

text
Java Program
  ↓
OutputStream
  ↓
File

A 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:

text
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter

Example ​

java
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? ​

FilePath
Packagejava.iojava.nio.file
APIOlder APIModern API
RepresentsFile/directory pathFile/directory path
Recommended for new code?Generally noYes
Common operationsexists(), mkdir()Used with Files

Example with File ​

java
File file = new File("data.txt");

if (file.exists()) {
    System.out.println("File exists");
}

Modern approach with Path ​

java
Path path = Path.of("data.txt");

if (Files.exists(path)) {
    System.out.println("File exists");
}

For modern Java code, prefer Path and Files for file-system operations.


4.8 Path and Files ​

Q: What are Path and Files used for? ​

Path represents the location of a file or directory, while Files provides utility methods for performing file-system operations.

Example:

java
Path path = Path.of("data.txt");

Files.writeString(path, "Hello World");

String content = Files.readString(path);

System.out.println(content);

Common operations:

MethodPurpose
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:

java
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:

java
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? ​

java
Path path = Path.of("data.txt");

try {
    Files.writeString(path, "Hello World");
} catch (IOException e) {
    e.printStackTrace();
}

4.10 IOException ​

Q: What is IOException? ​

IOException is 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:

java
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.

java
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:

java
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 finally to 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? ​

FileStream
RepresentsStored data/locationFlow of data
PurposeRepresents a file or directoryReads or writes data
ExamplePath, FileInputStream, OutputStream, Reader, Writer
ThinkWhere the data isHow data moves

Easy Memory Trick ​

File/Path = whereStream = how data flows


4.13 Common I/O Classes ​

ClassPurpose
InputStreamBase class for byte input
OutputStreamBase class for byte output
ReaderBase class for character input
WriterBase class for character output
FileInputStreamReads bytes from a file
FileOutputStreamWrites bytes to a file
FileReaderReads characters from a file
FileWriterWrites characters to a file
BufferedReaderBuffered character input
BufferedWriterBuffered character output
PathRepresents a file-system path
FilesProvides file-system operations

4.14 Common Interview Comparisons ​

Byte Stream vs Character Stream ​

Byte StreamCharacter Stream
DataBinary/raw dataText/characters
ClassesInputStream, OutputStreamReader, Writer
Best forImages, audio, PDFsText files

File vs Path ​

FilePath
APIOlderModern
Packagejava.iojava.nio.file
File operationsMethods on FileUsually through Files
New codeGenerally prefer PathRecommended

InputStream vs Reader ​

InputStreamReader
ReadsBytesCharacters
DataBinary/rawText
ExampleFileInputStreamFileReader

4.15 Common Interview Pitfalls ​

TopicKey Point
Input vs OutputInput reads data into the program; output writes data from the program.
Byte vs Character streamsByte streams are for raw/binary data; character streams are for text.
InputStream vs ReaderInputStream reads bytes; Reader reads characters.
OutputStream vs WriterOutputStream writes bytes; Writer writes characters.
BufferingImproves I/O performance by reducing direct I/O operations.
File vs PathFile is the older API; Path with Files is generally preferred for modern code.
Path vs FilesPath represents a location; Files performs file-system operations.
IOExceptionA checked exception commonly associated with I/O failures.
Resource closingUse try-with-resources for AutoCloseable resources.
StreamsA Java I/O stream is a flow of data, not necessarily a file.
finally for closing resourcesPossible, but try-with-resources is generally preferred.
Reading entire filesConvenient 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 InputStream and OutputStream handle raw or binary data, while character streams such as Reader and Writer handle text.

For file operations, modern Java commonly uses Path and Files from java.nio.file. I/O operations can throw checked exceptions such as IOException, 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
PhaseMain PurposeKey ActivitiesRelevant RolesJava/OOP Connection
1. PlanningDefine what needs to be built and why.Set objectives, scope, budget, feasibility, and timeline.Project Manager, Business AnalystUnderstand project goals before designing classes and features.
2. Requirements AnalysisIdentify what the system must do.Gather functional and non-functional requirements; create the SRS.Requirements Analyst, System AnalystConvert requirements into use cases and system behavior.
3. DesignCreate the technical blueprint.Design architecture, modules, databases, interfaces, and data flow.Software Architect, UI/UX Designer, Database DesignerApply encapsulation, inheritance, abstraction, polymorphism, interfaces, and design patterns.
4. DevelopmentImplement the software using code.Write Java code, create classes and methods, perform unit testing, and integrate modules.Java Developer, Backend Developer, Frontend DeveloperBuild reusable, maintainable, and loosely coupled object-oriented components.
5. TestingVerify quality and find defects.Perform functional, integration, system, performance, security, and regression testing.QA Engineer, Automation Tester, Performance TesterUse JUnit/TestNG to test classes, methods, and object behavior.
6. DeploymentRelease the application to users.Deploy to production, monitor the release, and provide documentation or training.DevOps Engineer, System Administrator, IT SupportPackage and deploy Java applications using tools such as Maven, Docker, or CI/CD pipelines.
7. MaintenanceKeep the software reliable and up to date.Fix bugs, apply updates, improve performance, and adapt to new requirements.Support Engineer, Maintenance Engineer, System AnalystRefactor 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.”

βœ…Summarized reviews based on Kittycat's insights from the best online courses at top universities