Packages, interfaces and exception handling notes — Unit 2
Free unit-wise study notes on packages, interfaces and exception handling for Java Programming, Semester 5 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.
Packages, interfaces and exception handling
Notebook — 20 pages
Page 1
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
1. Abstract Classes
An abstract class is a class that is declared with the `abstract` keyword. It represents a conceptual template that cannot be instantiated directly.
⇒1.1 Key Characteristics
You cannot create an object using `new AbstractClass()`.
It can contain both abstract methods (methods without a body) and concrete methods (normal methods with a body).
If a class contains even one abstract method, the class itself MUST be declared abstract.
Any subclass inheriting from an abstract class MUST override and provide bodies for all of its abstract methods, or else the subclass must also be declared abstract.
abstract class Shape {
abstract void draw(); // No body
void moveTo(int x, int y) { /* Normal method */ }
}
Page 2
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
2. Interfaces
An interface is a pure contract. It tells a class what to do, but not how to do it. It is declared using the `interface` keyword.
⇒2.1 Interface Rules (Pre-Java 8)
All methods are implicitly `public` and `abstract`. They cannot have bodies.
All variables are implicitly `public`, `static`, and `final` (they are constants).
A class implements an interface using the `implements` keyword.
A class can implement multiple interfaces, bypassing Java's restriction on multiple inheritance.
interface Printable {
void print(); // Implicitly public abstract
}
class Document implements Printable {
public void print() { System.out.println("Printing..."); }
}
Page 3
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
3. Modern Interfaces (Java 8+)
Historically, adding a new method to an interface would break all thousands of classes worldwide that implemented it. Java 8 introduced a massive change to solve this.
⇒3.1 Default Methods
Interfaces can now contain methods with bodies, provided they are marked with the `default` keyword. Implementing classes inherit this default behavior but can override it if desired.
⇒3.2 Static Methods
Interfaces can also contain `static` methods with bodies. These act as utility methods belonging to the interface itself.
⇒3.3 Abstract Class vs Interface
Abstract classes describe an 'is-a' relationship (Dog is an Animal) and hold state (instance variables). Interfaces describe a 'can-do' relationship (Document can be Printable) and cannot hold state.
Page 4
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
4. Packages
A package is a mechanism to encapsulate a group of classes, interfaces, and sub-packages. They are physically represented as folders in the file system.
⇒4.1 Purpose
Namespace Management: Prevents naming conflicts. You can have two classes named `Date` as long as they are in different packages (e.g., `java.util.Date` vs `java.sql.Date`).
Access Protection: Allows classes to be visible only within their own package.
⇒4.2 Creating and Importing
package com.mycompany.utils; // Must be the first line
public class MathHelper { }
To use this class elsewhere, use `import com.mycompany.utils.MathHelper;`. Note: `java.lang` is imported automatically in every file.
Page 5
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
5. Access Modifiers
Java provides four levels of access control for classes, variables, and methods to enforce encapsulation.
Modifier
Same Class
Same Package
Subclass (Diff Pkg)
World (Diff Pkg)
`private`
Yes
No
No
No
`default` (none)
Yes
Yes
No
No
`protected`
Yes
Yes
Yes
No
`public`
Yes
Yes
Yes
Yes
⇒5.1 The Protected Keyword
`protected` is specifically designed for inheritance. It hides the data from the outside world, but allows child classes (even if they live in a completely different package/folder) to inherit and use the data.
Page 6
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
6. Exception Handling Fundamentals
An Exception is an unwanted or unexpected event occurring during program execution that disrupts the normal flow of instructions. Exception handling provides a robust way to gracefully catch these events instead of crashing the program.
⇒6.1 The Exception Hierarchy
The root class is `java.lang.Throwable`, which splits into two main branches:
`Error`: Severe, unrecoverable problems caused by the JVM environment (e.g., `OutOfMemoryError`, `StackOverflowError`). You should not try to catch these.
`Exception`: Recoverable problems caused by the program logic or external resources (e.g., missing files, bad network).
Page 7
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
7. Checked vs Unchecked Exceptions
⇒7.1 Checked Exceptions
Exceptions checked at Compile-Time. The Java compiler forces the programmer to handle these, or the code will not compile. These generally represent external conditions outside the programmer's control.
`IOException`: Trying to read a file that might have been deleted.
`SQLException`: Trying to query a database that might be offline.
⇒7.2 Unchecked Exceptions (Runtime Exceptions)
Exceptions checked at Run-Time. They inherit from `RuntimeException`. The compiler does not force you to handle them. They generally represent logical programming bugs that should be fixed in the code, rather than caught.
`NullPointerException`: Calling a method on a null reference.
`ArithmeticException`: Dividing by zero.
`ArrayIndexOutOfBoundsException`: Accessing index 5 in a size 3 array.
Page 8
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
8. Try-Catch-Finally
The core mechanism for catching exceptions.
try {
// Code that might throw an exception
int data = 100 / 0;
} catch (ArithmeticException e) {
// Code to handle the specific exception
System.out.println("Cannot divide by zero!");
} catch (Exception e) {
// Fallback for any other type of exception
System.out.println(e.getMessage());
} finally {
// Code that ALWAYS executes, regardless of whether
// an exception occurred or not.
System.out.println("Cleanup code runs here.");
}
The `finally` block is crucial for closing resources (like database connections or file streams) to prevent memory leaks.
Page 9
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
9. The 'throw' and 'throws' Keywords
While `try-catch` handles exceptions, `throw` and `throws` are used to generate and declare them.
⇒9.1 `throw`
Used to explicitly throw an exception object from within a method block.
if (age < 18) {
throw new IllegalArgumentException("Must be 18+");
}
⇒9.2 `throws`
Appended to a method signature. It warns the caller: 'I might throw this Checked Exception, so you are forced to handle it.' It passes the buck up the call stack.
void readFile() throws IOException {
// If reading fails, caller must handle it
}
Page 10
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
10. Custom (User-Defined) Exceptions
Java allows you to create your own exception classes tailored to your specific application domain (e.g., `InsufficientFundsException`).
⇒10.1 Creating a Custom Exception
To create a Checked exception, extend `Exception`. To create an Unchecked exception, extend `RuntimeException`.
// Custom Checked Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message); // Pass message to parent Exception class
}
}
// Usage
void vote(int age) throws InvalidAgeException {
if(age < 18) throw new InvalidAgeException("Too young");
}
Page 11
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
11. Try-with-Resources (Java 7+)
Before Java 7, closing resources (files, network sockets) in the `finally` block was extremely verbose and prone to errors. Try-with-resources provides automatic resource management.
⇒11.1 Syntax
Resources are declared inside parentheses immediately after the `try` keyword.
try (FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr)) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
} // br and fr are automatically closed here! No finally needed.
Any object that implements the `java.lang.AutoCloseable` interface can be used in this manner.
Page 12
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
12. Strings and Immutability
In Java, `String` is not a primitive type; it is an Object. It is the most heavily used class in all of Java.
⇒12.1 Immutability
String objects are immutable. Once a String object is created in memory, its data cannot be changed. If you perform an operation like `str.concat(" world")`, the JVM does not alter the original string; it creates an entirely new String object in memory and returns its reference.
⇒12.2 The String Pool
To conserve memory, Java maintains a special area in the heap called the String Constant Pool. If you define `String s1 = "Hello";` and `String s2 = "Hello";`, the JVM only creates one object. Both `s1` and `s2` point to the exact same memory location.
Page 13
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
13. StringBuffer and StringBuilder
Because Strings are immutable, concatenating strings inside a loop creates thousands of discarded objects, severely lagging the Garbage Collector. Java provides mutable alternatives.
⇒13.1 StringBuffer
Mutable string sequences. It is Thread-Safe (synchronized), meaning multiple threads cannot access it simultaneously. Because of this lock-checking, it is slower.
⇒13.2 StringBuilder (Java 5+)
Identical to StringBuffer, but Not Thread-Safe. Without the synchronization overhead, it is significantly faster. It is the standard choice for string manipulation in single-threaded scenarios.
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies the object in-place
String finalResult = sb.toString();
Page 14
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
14. Wrapper Classes and Autoboxing
The Collections framework (like ArrayLists) strictly requires Objects; they cannot store primitive types (like `int` or `double`). Wrapper classes solve this by 'wrapping' primitives into Objects.
Since Java 5, the compiler automatically converts between primitives and wrappers.
Autoboxing: Automatic conversion of primitive to wrapper (e.g., `Integer num = 5;`).
Unboxing: Automatic conversion of wrapper to primitive (e.g., `int prim = num;`).
Page 15
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
15. Annotations
Annotations provide metadata about the program. They do not directly affect the operation of the code they annotate, but can be read by the compiler or runtime environments.
⇒15.1 Built-in Annotations
`@Override`: Instructs the compiler to verify that the method actually overrides a parent method. If you mistyped the method name, the compiler throws an error.
`@Deprecated`: Marks a method as obsolete and triggers a compiler warning if developers try to use it.
`@SuppressWarnings`: Instructs the compiler to ignore specific warnings (e.g., `@SuppressWarnings("unchecked")`).
Custom annotations can also be created and are heavily used in modern frameworks like Spring Boot (`@RestController`, `@Autowired`).
Page 16
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
16. Nested and Inner Classes
Java allows defining a class inside another class. This logically groups classes that are only used in one place and increases encapsulation.
⇒16.1 Non-static Nested Class (Inner Class)
An Inner Class has access to all members (even private) of the enclosing outer class. To instantiate it, you must first instantiate the outer class.
⇒16.2 Static Nested Class
Does not require an instance of the outer class. It can only access the static members of the outer class.
⇒16.3 Local Inner Classes
A class defined inside a method block. Its scope is restricted to that method.
Page 17
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
17. Anonymous Inner Classes
An inner class without a name. It is declared and instantiated in a single expression. It is exclusively used when you need to override methods of a class or interface for a one-time use.
⇒17.1 Syntax
// Creating an instance of an interface without creating
// a separate named class file.
Runnable runner = new Runnable() {
@Override
public void run() {
System.out.println("Running task");
}
};
Historically used heavily in GUI programming (Swing/AWT) for event listeners. Today, most anonymous classes containing a single method are replaced by Lambda Expressions.
Page 18
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
18. Lambda Expressions (Java 8+)
Lambdas introduced Functional Programming concepts to Java. They provide a clear and concise way to represent one-method interfaces (Functional Interfaces).
⇒18.1 Functional Interfaces
An interface with exactly one abstract method (often marked with `@FunctionalInterface`). Examples: `Runnable`, `Comparator`.
⇒18.2 Lambda Syntax
Format: `(parameters) -> expression` or `(parameters) -> { statements; }`
// Old Anonymous Class
MathOperation add = new MathOperation() {
public int operate(int a, int b) { return a + b; }
};
// Lambda Equivalent (Much cleaner)
MathOperation add = (a, b) -> a + b;
Page 19
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
19. Method References
Sometimes a lambda expression does nothing but call an existing method. In those cases, you can use a Method Reference for even cleaner syntax.
Types of references: Static method (`Math::max`), Instance method of specific object (`System.out::println`), Constructor (`ArrayList::new`).
Page 20
Wink Notes
B.Tech CSE — 5th Semester
Java Programming
— Unit - 2 —
20. Garbage Collection (Memory Management)
In C++, programmers must manually allocate and free memory using `malloc` and `free`. Forgetting to free memory causes Memory Leaks. Java automates this.
⇒20.1 How it Works
The JVM runs a background daemon thread called the Garbage Collector (GC). It periodically scans the Heap memory.
If an object in memory no longer has any active reference variables pointing to it (it is unreachable), it is considered 'Garbage'.
The GC destroys the object and reclaims the memory.
⇒20.2 `System.gc()` and `finalize()`
You can suggest the JVM run the garbage collector using `System.gc()`, but the JVM ignores it if it decides it isn't necessary. Before destroying an object, the GC historically called the `finalize()` method on it, but this is now deprecated as it was highly unpredictable.