1.
Exception Handling (Error Management in Java)
Definition:
An exception is an error that occurs during runtime. Exception handling allows for
managing these errors gracefully.
Key Components:
o try: Block to test code for errors.
o catch: Handles exceptions thrown in the try block.
o finally: Executes cleanup code, regardless of whether an exception occurred.
o throw: Used to explicitly throw an exception.
o throws: Declares exceptions a method might throw.
Code Examples:
// Simple try-catch example
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero.");
}
java
CopyEdit
// Using finally
try {
int[] arr = {1, 2, 3};
[Link](arr[5]); // ArrayIndexOutOfBounds
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Index is out of bounds.");
} finally {
[Link]("Cleanup actions here.");
}
2. Serialization (Object Persistence)
Definition:
Serialization is the process of converting an object into a byte stream to save it to a file or
transmit it over a network. Deserialization recreates the object from this stream.
Steps to Serialize and Deserialize:
o Implement the Serializable interface in the class.
o Use ObjectOutputStream to write the object.
o Use ObjectInputStream to read the object.
Code Examples:
import [Link].*;
// Serializable class
public class Student implements Serializable {
int id;
String name;
public Student(int id, String name) {
[Link] = id;
[Link] = name;
}
}
// Serialization
Student student = new Student(1, "John");
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("[Link]"));
[Link](student);
[Link]();
// Deserialization
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("[Link]"));
Student s = (Student) [Link]();
[Link]();
[Link]([Link] + " " + [Link]);
3. Generics (Type Safety in Java)
Definition:
Generics enable types (classes and methods) to operate on objects of various types while
providing compile-time type safety.
Benefits:
o Compile-time type checking.
o No need for type casting.
Generic Classes and Methods:
// Generic Class
public class Box<T> {
private T value;
public void set(T value) { [Link] = value; }
public T get() { return value; }
}
Box<String> stringBox = new Box<>();
[Link]("Hello");
[Link]([Link]());
java
CopyEdit
// Generic Method
public static <T> void printArray(T[] array) {
for (T element : array) {
[Link](element + " ");
}
[Link]();
}
Integer[] intArray = {1, 2, 3};
printArray(intArray);
Wildcard Examples:
public static void printList(List<?> list) {
for (Object elem : list) {
[Link](elem);
}
}
1. Exception Handling (Error Management in Java)
Simple Try-Catch Example:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero.");
}
}
}
Finally Block Example:
public class Main {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
[Link](arr[5]); // ArrayIndexOutOfBounds
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Index out of bounds.");
} finally {
[Link]("Cleanup actions here.");
}
}
}
Custom Exception Example:
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class Main {
public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above.");
}
}
public static void main(String[] args) {
try {
validateAge(16);
} catch (InvalidAgeException e) {
[Link]([Link]());
}
}
}
2. Serialization (Object Persistence)
Serialization Example:
import [Link].*;
public class Main {
public static void main(String[] args) throws IOException {
Student student = new Student(1, "John");
// Serialization
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("[Link]"));
[Link](student);
[Link]();
[Link]("Serialization done.");
}
}
class Student implements Serializable {
int id;
String name;
public Student(int id, String name) {
[Link] = id;
[Link] = name;
}
}
Deserialization Example:
import [Link].*;
public class Main {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
// Deserialization
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("[Link]"));
Student student = (Student) [Link]();
[Link]();
[Link]("Deserialization done.");
[Link]("ID: " + [Link] + ", Name: " +
[Link]);
}
}
class Student implements Serializable {
int id;
String name;
public Student(int id, String name) {
[Link] = id;
[Link] = name;
}
}
3. Generics (Type Safety in Java)
Generic Class Example:
public class Box<T> {
private T value;
public void set(T value) {
[Link] = value;
}
public T get() {
return value;
}
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
[Link]("Hello Generics");
[Link]([Link]());
}
}
Generic Method Example:
java
CopyEdit
public class Main {
public static <T> void printArray(T[] array) {
for (T element : array) {
[Link](element + " ");
}
[Link]();
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4};
String[] strArray = {"Java", "Generics"};
printArray(intArray);
printArray(strArray);
}
}
Wildcard Example:
java
CopyEdit
import [Link];
import [Link];
public class Main {
public static void printList(List<?> list) {
for (Object elem : list) {
[Link](elem);
}
}
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
[Link]("Java");
[Link]("OOP");
printList(strings);
}
}
Practice question
1. Relationships Between Objects
Definition:
Relationships between objects define how objects interact and
relate to each other.
o Association: A "uses-a" relationship (e.g., a student uses a
library).
o Aggregation: A "has-a" relationship (e.g., a department has
professors).
o Composition: A "part-of" relationship (e.g., a car has an
engine).
class Engine {
void start() {
[Link]("Engine started.");
}
}
class Car {
private Engine engine = new Engine(); // Composition
void drive() {
[Link]();
[Link]("Car is driving.");
}
}
public class Main { public static void main(String[] args) {Car car = new
Car();
[Link]();
}
}
Practice Question:
Implement a class Library that contains multiple Books using aggregation.
Here are short notes, code examples, and practice questions for each topic, simplified for
easier understanding:
1. Relationships Between Objects
Definition:
Relationships between objects define how objects interact and relate to each other.
o Association: A "uses-a" relationship (e.g., a student uses a library).
o Aggregation: A "has-a" relationship (e.g., a department has professors).
o Composition: A "part-of" relationship (e.g., a car has an engine).
Code Example:
java
CopyEdit
class Engine {
void start() {
[Link]("Engine started.");
}
}
class Car {
private Engine engine = new Engine(); // Composition
void drive() {
[Link]();
[Link]("Car is driving.");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
[Link]();
}
}
Practice Question:
Implement a class Library that contains multiple Books using aggregation.
2. Abstract and Final Classes
Abstract Class:
o Cannot be instantiated.
o Used as a base class to provide common functionality for
derived classes.
o Contains abstract methods (no body).
Final Class:
o Cannot be extended.
o Used to prevent inheritance.
Practice Question:
Create an abstract class Shape with a method calculateArea().
Extend it to Circle and Rectangle.
Code: abstract class Animal {
abstract void sound(); // Abstract method
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks.");
final class Cat {
void sound() {
[Link]("Cat meows.");
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
[Link]();
Cat cat = new Cat();
[Link]();
}
}
3. Introduction to GUI (Graphical User Interface)
Definition:
GUI allows users to interact with the application using graphical
elements like buttons, text fields, etc.
Practice Question:
Create a GUI with a text field and a button. When clicked, the
button should display the entered text in a label.
import [Link].*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Simple GUI");
JButton button = new JButton("Click Me!");
[Link](100, 100, 120, 50);
[Link](button);
[Link](400, 400);
[Link](null);
[Link](true);
}
}
4. Inheritance
Definition:
Inheritance allows a class to inherit properties and methods from
another class.
Practice Question:
Create a class Person with properties name and age. Extend it to
Student with additional property grade.
Code Example:
class Parent {
void display() {
[Link]("I am a parent class.");
}
}
class Child extends Parent {
void show() {
[Link]("I am a child class.");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
[Link]();
[Link]();
}
}
5. Data Encapsulation and Hiding
Definition:
Encapsulation hides the internal state of an object and allows
controlled access through getters and setters.
Practice Question:
Create a class Car with private properties speed and fuel. Use
methods to access and modify them.
Code Example:
class BankAccount {
private double balance;
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
[Link](500);
[Link]("Balance: " +
[Link]());
}
}
6. Method Overloading
Definition:
Method overloading allows multiple methods with the same name
but different parameter lists.
Practice Question:
Create a class Shape with an overloaded method calculateArea()
for circle and rectangle.
Code Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](2, 3));
[Link]([Link](2.5, 3.5));
}
}