Java Real-Life Examples

Practical applications of Java programming concepts in real-world scenarios

Practical Real-World Applications

Real-World Java Applications

Java is used in countless real-world applications from enterprise systems to Android apps. Understanding how Java concepts apply to practical problems is key to mastering the language. Below are real-life examples for each major Java concept.

Conditional Control Statements

Decision-making in real applications

Traffic Light System

Conditional statements are used in traffic control systems to manage light changes based on time, sensor input, or traffic density.

// Simplified traffic light control
public class TrafficLightSystem {
    public static void main(String[] args) {
        int trafficDensity = 75; // Percentage of road capacity
        boolean emergencyVehicle = false;
        
        if (emergencyVehicle) {
            System.out.println("All lights GREEN for emergency vehicle");
        } else if (trafficDensity > 80) {
            System.out.println("Extend GREEN time for main road");
        } else if (trafficDensity < 20) {
            System.out.println("Switch to energy-saving mode");
        } else {
            System.out.println("Normal operation sequence");
        }
    }
}
User Authentication System

Conditional statements verify user credentials and determine access levels in authentication systems.

// Simple user authentication
import java.util.Scanner;

public class UserAuthentication {
    public static void main(String[] args) {
        String username = "admin";
        String password = "secure123";
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter username: ");
        String inputUser = scanner.nextLine();
        
        System.out.print("Enter password: ");
        String inputPass = scanner.nextLine();
        
        if (inputUser.equals(username) && inputPass.equals(password)) {
            System.out.println("Access granted! Welcome admin.");
        } else if (inputUser.equals(username)) {
            System.out.println("Incorrect password. Try again.");
        } else {
            System.out.println("Invalid username.");
        }
        
        scanner.close();
    }
}

Loops

Repetitive tasks in applications

Digital Clock Simulation

Loops are essential for continuously running systems like clocks, monitoring tools, and servers.

// Simplified digital clock using loops
public class DigitalClock {
    public static void main(String[] args) throws InterruptedException {
        int hours = 0, minutes = 0, seconds = 0;
        
        // Simulate 24 hours of clock time
        for (hours = 0; hours < 24; hours++) {
            for (minutes = 0; minutes < 60; minutes++) {
                for (seconds = 0; seconds < 60; seconds++) {
                    // Clear screen
                    System.out.print("\033[H\033[2J");
                    System.out.flush();
                    
                    System.out.println("Digital Clock Simulation");
                    System.out.println("Time: " + hours + ":" + minutes + ":" + seconds);
                    
                    Thread.sleep(1000); // Wait for 1 second
                }
            }
        }
    }
}
Data Processing

Loops process large datasets, such as analyzing sensor readings or customer records.

// Processing sensor data with loops
public class SensorDataProcessor {
    public static void main(String[] args) {
        final int NUM_SENSORS = 10;
        double[] sensorReadings = {23.5, 24.1, 22.8, 25.3, 23.9, 
                                  24.8, 22.5, 23.7, 24.5, 23.2};
        double total = 0.0, average;
        
        // Calculate average temperature
        for (int i = 0; i < NUM_SENSORS; i++) {
            total += sensorReadings[i];
        }
        average = total / NUM_SENSORS;
        
        System.out.println("Average temperature: " + average + "°C");
        
        // Identify sensors with above-average readings
        System.out.print("Sensors above average: ");
        for (int i = 0; i < NUM_SENSORS; i++) {
            if (sensorReadings[i] > average) {
                System.out.print("Sensor " + (i+1) + " (" + sensorReadings[i] + "), ");
            }
        }
        System.out.println();
    }
}

Arrays

Storing and processing collections of data

Student Grade Management

Arrays store and process multiple values, such as student grades in a classroom.

// Student grade management using arrays
public class StudentGradeManager {
    public static void main(String[] args) {
        final int NUM_STUDENTS = 5;
        String[] students = {"Alice", "Bob", "Charlie", "Diana", "Evan"};
        int[] grades = {85, 92, 78, 88, 95};
        
        // Calculate class average
        int total = 0;
        for (int i = 0; i < NUM_STUDENTS; i++) {
            total += grades[i];
        }
        double average = (double) total / NUM_STUDENTS;
        
        // Find highest and lowest grades
        int highest = grades[0], lowest = grades[0];
        String topStudent = students[0], bottomStudent = students[0];
        
        for (int i = 1; i < NUM_STUDENTS; i++) {
            if (grades[i] > highest) {
                highest = grades[i];
                topStudent = students[i];
            }
            if (grades[i] < lowest) {
                lowest = grades[i];
                bottomStudent = students[i];
            }
        }
        
        // Display results
        System.out.println("Class Grade Report");
        System.out.println("Average grade: " + average);
        System.out.println("Highest grade: " + highest + " by " + topStudent);
        System.out.println("Lowest grade: " + lowest + " by " + bottomStudent);
    }
}
Inventory Management

Arrays manage product inventories in retail systems.

// Simple inventory management system
public class InventoryManagement {
    public static void main(String[] args) {
        final int MAX_PRODUCTS = 100;
        String[] products = new String[MAX_PRODUCTS];
        int[] quantities = new int[MAX_PRODUCTS];
        int productCount = 0;
        
        // Add some sample products
        products[productCount] = "Laptop";
        quantities[productCount] = 15;
        productCount++;
        
        products[productCount] = "Mouse";
        quantities[productCount] = 42;
        productCount++;
        
        products[productCount] = "Keyboard";
        quantities[productCount] = 25;
        productCount++;
        
        // Display inventory
        System.out.println("Current Inventory:");
        for (int i = 0; i < productCount; i++) {
            System.out.println(products[i] + ": " + quantities[i] + " units");
        }
        
        // Check for low stock items
        System.out.println("\nLow Stock Alert:");
        boolean lowStockFound = false;
        for (int i = 0; i < productCount; i++) {
            if (quantities[i] < 20) {
                System.out.println("LOW: " + products[i] + " (only " + quantities[i] + " left)");
                lowStockFound = true;
            }
        }
        
        if (!lowStockFound) {
            System.out.println("No low stock items.");
        }
    }
}

Strings

Text processing in applications

Text Analysis Tool

Strings process and analyze text data, such as counting words or finding patterns.

// Simple text analysis tool
public class TextAnalysisTool {
    public static void main(String[] args) {
        String text = "Java is a powerful programming language. " +
                     "It is widely used for enterprise applications, Android development, " +
                     "and web services.";
        
        // Count words
        String[] words = text.split("\\s+");
        int wordCount = words.length;
        
        // Count sentences
        String[] sentences = text.split("[.!?]+");
        int sentenceCount = sentences.length;
        
        // Count occurrences of "Java"
        int javaCount = 0;
        String tempText = text.toLowerCase();
        int index = tempText.indexOf("java");
        
        while (index != -1) {
            javaCount++;
            index = tempText.indexOf("java", index + 1);
        }
        
        // Display analysis
        System.out.println("Text Analysis Results:");
        System.out.println("Total words: " + wordCount);
        System.out.println("Total sentences: " + sentenceCount);
        System.out.println("Occurrences of 'Java': " + javaCount);
    }
}
Username Validation

String methods validate user input like usernames and passwords.

// Username validation using string methods
public class UsernameValidator {
    public static boolean isValidUsername(String username) {
        // Check length
        if (username.length() < 5 || username.length() > 20) {
            System.out.println("Username must be between 5-20 characters.");
            return false;
        }
        
        // Check if starts with letter
        if (!Character.isLetter(username.charAt(0))) {
            System.out.println("Username must start with a letter.");
            return false;
        }
        
        // Check for invalid characters
        for (char c : username.toCharArray()) {
            if (!Character.isLetterOrDigit(c) && c != '_') {
                System.out.println("Username can only contain letters, digits, and underscores.");
                return false;
            }
        }
        
        // All checks passed
        System.out.println("Username is valid!");
        return true;
    }
    
    public static void main(String[] args) {
        String[] testUsernames = {
            "john_doe123",    // valid
            "123john",        // invalid - starts with digit
            "jane@doe",       // invalid - contains special character
            "abc",            // invalid - too short
            "very_long_username_that_exceeds_limit"  // invalid - too long
        };
        
        for (String username : testUsernames) {
            System.out.println("\nTesting: " + username);
            isValidUsername(username);
        }
    }
}

Object-Oriented Programming

Modeling real-world entities as objects

Banking System

OOP models real-world entities like bank accounts with classes, objects, and inheritance.

// Banking system using OOP concepts
class BankAccount {
    private String accountNumber;
    private String accountHolder;
    protected double balance;
    
    public BankAccount(String accountNumber, String accountHolder, double initialDeposit) {
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
        this.balance = initialDeposit;
    }
    
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: $" + amount + ". New balance: $" + balance);
        } else {
            System.out.println("Invalid deposit amount.");
        }
    }
    
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrew: $" + amount + ". New balance: $" + balance);
        } else {
            System.out.println("Invalid withdrawal amount or insufficient funds.");
        }
    }
    
    public void displayAccountInfo() {
        System.out.println("Account Number: " + accountNumber);
        System.out.println("Account Holder: " + accountHolder);
        System.out.println("Balance: $" + balance);
    }
}

class SavingsAccount extends BankAccount {
    private double interestRate;
    
    public SavingsAccount(String accountNumber, String accountHolder, 
                        double initialDeposit, double interestRate) {
        super(accountNumber, accountHolder, initialDeposit);
        this.interestRate = interestRate;
    }
    
    public void applyInterest() {
        double interest = balance * interestRate / 100;
        deposit(interest);
        System.out.println("Interest applied: $" + interest);
    }
    
    // Override display method to show interest rate
    @Override
    public void displayAccountInfo() {
        super.displayAccountInfo();
        System.out.println("Interest Rate: " + interestRate + "%");
    }
}

public class BankingSystem {
    public static void main(String[] args) {
        // Create a savings account
        SavingsAccount myAccount = new SavingsAccount("SA001", "John Doe", 1000.0, 2.5);
        
        // Perform transactions
        myAccount.displayAccountInfo();
        System.out.println();
        
        myAccount.deposit(500.0);
        myAccount.withdraw(200.0);
        myAccount.applyInterest();
        System.out.println();
        
        myAccount.displayAccountInfo();
    }
}
E-commerce Product System

OOP models products in an e-commerce system with inheritance and polymorphism.

// E-commerce product system using OOP
abstract class Product {
    protected String name;
    protected double price;
    protected String description;
    
    public Product(String name, double price, String description) {
        this.name = name;
        this.price = price;
        this.description = description;
    }
    
    public abstract void displayDetails();
    
    public double getPrice() {
        return price;
    }
    
    public String getName() {
        return name;
    }
}

class Book extends Product {
    private String author;
    private int pageCount;
    
    public Book(String name, double price, String description, 
               String author, int pageCount) {
        super(name, price, description);
        this.author = author;
        this.pageCount = pageCount;
    }
    
    @Override
    public void displayDetails() {
        System.out.println("Book: " + name);
        System.out.println("Author: " + author);
        System.out.println("Pages: " + pageCount);
        System.out.println("Price: $" + price);
        System.out.println("Description: " + description);
    }
}

class Electronics extends Product {
    private String brand;
    private String warranty;
    
    public Electronics(String name, double price, String description, 
                     String brand, String warranty) {
        super(name, price, description);
        this.brand = brand;
        this.warranty = warranty;
    }
    
    @Override
    public void displayDetails() {
        System.out.println("Electronics: " + name);
        System.out.println("Brand: " + brand);
        System.out.println("Warranty: " + warranty);
        System.out.println("Price: $" + price);
        System.out.println("Description: " + description);
    }
}

public class EcommerceSystem {
    public static void main(String[] args) {
        Product[] products = {
            new Book("Java Programming", 45.99, 
                    "Learn Java programming from scratch", 
                    "John Smith", 350),
            new Electronics("Smartphone", 599.99, 
                         "Latest smartphone with advanced features", 
                         "TechBrand", "2 years"),
            new Book("Data Structures", 55.50, 
                    "Comprehensive guide to data structures", 
                    "Jane Doe", 420)
        };
        
        System.out.println("E-commerce Product Catalog:\n");
        
        double totalValue = 0;
        for (Product product : products) {
            product.displayDetails();
            totalValue += product.getPrice();
            System.out.println("-----------------------------");
        }
        
        System.out.println("Total inventory value: $" + totalValue);
    }
}

Collections Framework

Managing groups of objects efficiently

Employee Management System

Collections manage groups of objects like employees in a company directory.

// Employee management using Collections
import java.util.*;

class Employee {
    private int id;
    private String name;
    private String department;
    private double salary;
    
    public Employee(int id, String name, String department, double salary) {
        this.id = id;
        this.name = name;
        this.department = department;
        this.salary = salary;
    }
    
    public int getId() { return id; }
    public String getName() { return name; }
    public String getDepartment() { return department; }
    public double getSalary() { return salary; }
    
    @Override
    public String toString() {
        return "Employee [ID=" + id + ", Name=" + name + 
               ", Department=" + department + ", Salary=$" + salary + "]";
    }
}

public class EmployeeManagementSystem {
    public static void main(String[] args) {
        // Using ArrayList to store employees
        List<Employee> employees = new ArrayList<>();
        
        // Add employees
        employees.add(new Employee(101, "Alice Johnson", "Engineering", 75000));
        employees.add(new Employee(102, "Bob Smith", "Marketing", 65000));
        employees.add(new Employee(103, "Charlie Brown", "Engineering", 82000));
        employees.add(new Employee(104, "Diana Prince", "HR", 60000));
        
        // Display all employees
        System.out.println("All Employees:");
        for (Employee emp : employees) {
            System.out.println(emp);
        }
        
        // Using HashMap to group employees by department
        Map<String, List<Employee>> deptMap = new HashMap<>();
        
        for (Employee emp : employees) {
            String dept = emp.getDepartment();
            if (!deptMap.containsKey(dept)) {
                deptMap.put(dept, new ArrayList<>());
            }
            deptMap.get(dept).add(emp);
        }
        
        // Display employees by department
        System.out.println("\nEmployees by Department:");
        for (String dept : deptMap.keySet()) {
            System.out.println("\nDepartment: " + dept);
            for (Employee emp : deptMap.get(dept)) {
                System.out.println("  - " + emp.getName() + " ($" + emp.getSalary() + ")");
            }
        }
        
        // Calculate total salary using Stream API
        double totalSalary = employees.stream()
            .mapToDouble(Employee::getSalary)
            .sum();
        
        System.out.println("\nTotal monthly salary: $" + totalSalary);
    }
}
Shopping Cart

Collections manage shopping cart items in e-commerce applications.

// Shopping cart using Collections
import java.util.*;

class CartItem {
    private String productName;
    private double price;
    private int quantity;
    
    public CartItem(String productName, double price, int quantity) {
        this.productName = productName;
        this.price = price;
        this.quantity = quantity;
    }
    
    public String getProductName() { return productName; }
    public double getPrice() { return price; }
    public int getQuantity() { return quantity; }
    public void setQuantity(int quantity) { this.quantity = quantity; }
    
    public double getTotalPrice() {
        return price * quantity;
    }
    
    @Override
    public String toString() {
        return quantity + " x " + productName + " @ $" + price + " each = $" + getTotalPrice();
    }
}

public class ShoppingCart {
    private Map<String, CartItem> cartItems = new HashMap<>();
    
    public void addItem(String productName, double price, int quantity) {
        if (cartItems.containsKey(productName)) {
            // Update quantity if product already in cart
            CartItem existingItem = cartItems.get(productName);
            existingItem.setQuantity(existingItem.getQuantity() + quantity);
        } else {
            // Add new item to cart
            cartItems.put(productName, new CartItem(productName, price, quantity));
        }
        System.out.println("Added " + quantity + " of " + productName + " to cart.");
    }
    
    public void removeItem(String productName, int quantity) {
        if (cartItems.containsKey(productName)) {
            CartItem item = cartItems.get(productName);
            int newQuantity = item.getQuantity() - quantity;
            
            if (newQuantity <= 0) {
                cartItems.remove(productName);
                System.out.println("Removed " + productName + " from cart.");
            } else {
                item.setQuantity(newQuantity);
                System.out.println("Reduced quantity of " + productName + " to " + newQuantity);
            }
        } else {
            System.out.println("Product not found in cart: " + productName);
        }
    }
    
    public void displayCart() {
        if (cartItems.isEmpty()) {
            System.out.println("Your cart is empty.");
            return;
        }
        
        System.out.println("\n===== SHOPPING CART =====");
        double total = 0;
        
        for (CartItem item : cartItems.values()) {
            System.out.println(item);
            total += item.getTotalPrice();
        }
        
        System.out.println("Total: $" + total);
        System.out.println("=========================\n");
    }
    
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
        
        // Add items to cart
        cart.addItem("Java Programming Book", 45.99, 2);
        cart.addItem("Wireless Mouse", 25.50, 1);
        cart.addItem("USB Cable", 12.99, 3);
        
        // Display cart
        cart.displayCart();
        
        // Update quantities
        cart.removeItem("USB Cable", 2);
        cart.addItem("Java Programming Book", 45.99, 1);
        
        // Display updated cart
        cart.displayCart();
    }
}

Exception Handling

Gracefully handling errors in applications

File Reader with Error Handling

Exception handling manages file operations where errors might occur.

// File reader with exception handling
import java.io.*;
import java.util.Scanner;

public class FileReaderWithExceptionHandling {
    
    // Method to read file with exception handling
    public static void readFile(String filename) {
        File file = new File(filename);
        Scanner scanner = null;
        
        try {
            scanner = new Scanner(file);
            System.out.println("File content:");
            System.out.println("-------------");
            
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            
        } catch (FileNotFoundException e) {
            System.err.println("Error: The file '" + filename + "' was not found.");
            System.err.println("Please check the file path and try again.");
            
        } catch (SecurityException e) {
            System.err.println("Error: Permission denied to read the file '" + filename + "'.");
            
        } finally {
            // Ensure scanner is closed even if an exception occurs
            if (scanner != null) {
                scanner.close();
                System.out.println("Scanner closed successfully.");
            }
        }
    }
    
    // Method to demonstrate custom exception
    public static void processNumber(String numberStr) throws InvalidNumberException {
        try {
            int number = Integer.parseInt(numberStr);
            
            if (number < 0) {
                throw new InvalidNumberException("Number cannot be negative: " + number);
            }
            
            System.out.println("Processed number: " + number);
            
        } catch (NumberFormatException e) {
            throw new InvalidNumberException("Invalid number format: '" + numberStr + "' is not a valid integer.");
        }
    }
    
    // Custom exception class
    static class InvalidNumberException extends Exception {
        public InvalidNumberException(String message) {
            super(message);
        }
    }
    
    public static void main(String[] args) {
        System.out.println("=== File Reading Example ===");
        readFile("sample.txt");  // This file might not exist
        
        System.out.println("\n=== Number Processing Example ===");
        String[] testNumbers = {"42", "-5", "abc"};
        
        for (String num : testNumbers) {
            try {
                processNumber(num);
            } catch (InvalidNumberException e) {
                System.err.println("Error: " + e.getMessage());
            }
        }
        
        System.out.println("\nProgram completed successfully.");
    }
}
Bank Transaction with Exception Handling

Exception handling ensures banking transactions complete safely even when errors occur.

// Bank transaction with exception handling
class InsufficientFundsException extends Exception {
    private double currentBalance;
    private double withdrawalAmount;
    
    public InsufficientFundsException(double currentBalance, double withdrawalAmount) {
        super("Insufficient funds: Attempted to withdraw $" + withdrawalAmount + 
              " but account only has $" + currentBalance);
        this.currentBalance = currentBalance;
        this.withdrawalAmount = withdrawalAmount;
    }
    
    public double getCurrentBalance() { return currentBalance; }
    public double getWithdrawalAmount() { return withdrawalAmount; }
}

class BankAccountEx {
    private double balance;
    private String accountNumber;
    
    public BankAccountEx(String accountNumber, double initialBalance) {
        this.accountNumber = accountNumber;
        this.balance = initialBalance;
    }
    
    public void deposit(double amount) throws IllegalArgumentException {
        if (amount <= 0) {
            throw new IllegalArgumentException("Deposit amount must be positive: $" + amount);
        }
        balance += amount;
        System.out.println("Deposited $" + amount + ". New balance: $" + balance);
    }
    
    public void withdraw(double amount) throws InsufficientFundsException, IllegalArgumentException {
        if (amount <= 0) {
            throw new IllegalArgumentException("Withdrawal amount must be positive: $" + amount);
        }
        
        if (amount > balance) {
            throw new InsufficientFundsException(balance, amount);
        }
        
        balance -= amount;
        System.out.println("Withdrew $" + amount + ". New balance: $" + balance);
    }
    
    public double getBalance() {
        return balance;
    }
}

public class BankTransactionSystem {
    public static void main(String[] args) {
        BankAccountEx account = new BankAccountEx("ACC123456", 1000.0);
        
        // Test various transactions with exception handling
        try {
            account.deposit(500.0);
            account.withdraw(200.0);
            account.withdraw(1500.0);  // This should throw InsufficientFundsException
        } catch (InsufficientFundsException e) {
            System.err.println("Transaction failed: " + e.getMessage());
            System.err.println("Please try a smaller amount.");
        } catch (IllegalArgumentException e) {
            System.err.println("Invalid transaction: " + e.getMessage());
        }
        
        // Test invalid deposit
        try {
            account.deposit(-100.0);  // This should throw IllegalArgumentException
        } catch (IllegalArgumentException e) {
            System.err.println("Deposit failed: " + e.getMessage());
        }
        
        // Final balance
        System.out.println("Final account balance: $" + account.getBalance());
    }
}

File Handling

Reading from and writing to files

Student Gradebook File System

File handling stores and retrieves student grade data from files.

// Student gradebook with file handling
import java.io.*;
import java.util.*;

class StudentGrade implements Serializable {
    private String studentName;
    private int studentId;
    private Map<String, Double> grades;
    
    public StudentGrade(String studentName, int studentId) {
        this.studentName = studentName;
        this.studentId = studentId;
        this.grades = new HashMap<>();
    }
    
    public void addGrade(String subject, double grade) {
        grades.put(subject, grade);
    }
    
    public double getGrade(String subject) {
        return grades.getOrDefault(subject, -1.0);
    }
    
    public double calculateAverage() {
        if (grades.isEmpty()) {
            return 0.0;
        }
        
        double sum = 0.0;
        for (double grade : grades.values()) {
            sum += grade;
        }
        return sum / grades.size();
    }
    
    @Override
    public String toString() {
        return "StudentGrade [Name=" + studentName + ", ID=" + studentId + 
               ", Grades=" + grades + ", Average=" + calculateAverage() + "]";
    }
}

public class GradebookFileSystem {
    private Map<Integer, StudentGrade> students = new HashMap<>();
    private String dataFile = "gradebook.dat";
    
    // Save gradebook to file
    public void saveGradebook() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFile))) {
            oos.writeObject(students);
            System.out.println("Gradebook saved successfully to " + dataFile);
        } catch (IOException e) {
            System.err.println("Error saving gradebook: " + e.getMessage());
        }
    }
    
    // Load gradebook from file
    public void loadGradebook() {
        File file = new File(dataFile);
        if (!file.exists()) {
            System.out.println("No existing gradebook file found. Starting with empty gradebook.");
            return;
        }
        
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFile))) {
            students = (Map<Integer, StudentGrade>) ois.readObject();
            System.out.println("Gradebook loaded successfully from " + dataFile);
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("Error loading gradebook: " + e.getMessage());
        }
    }
    
    // Add a student to the gradebook
    public void addStudent(StudentGrade student) {
        students.put(student.studentId, student);
        System.out.println("Added student: " + student.studentName);
    }
    
    // Display all students and their grades
    public void displayGradebook() {
        if (students.isEmpty()) {
            System.out.println("Gradebook is empty.");
            return;
        }
        
        System.out.println("\n===== GRADEBOOK =====");
        for (StudentGrade student : students.values()) {
            System.out.println(student);
        }
        System.out.println("=====================\n");
    }
    
    public static void main(String[] args) {
        GradebookFileSystem gradebook = new GradebookFileSystem();
        
        // Load existing data
        gradebook.loadGradebook();
        
        // Add some sample students and grades
        StudentGrade student1 = new StudentGrade("Alice Johnson", 1001);
        student1.addGrade("Math", 92.5);
        student1.addGrade("Science", 88.0);
        student1.addGrade("English", 95.5);
        
        StudentGrade student2 = new StudentGrade("Bob Smith", 1002);
        student2.addGrade("Math", 78.5);
        student2.addGrade("Science", 85.0);
        student2.addGrade("History", 91.0);
        
        gradebook.addStudent(student1);
        gradebook.addStudent(student2);
        
        // Display the gradebook
        gradebook.displayGradebook();
        
        // Save the gradebook to file
        gradebook.saveGradebook();
        
        // Demonstrate loading by creating a new instance
        System.out.println("\nCreating new gradebook instance and loading data...");
        GradebookFileSystem newGradebook = new GradebookFileSystem();
        newGradebook.loadGradebook();
        newGradebook.displayGradebook();
    }
}
Configuration File Reader

File handling reads configuration settings from files for applications.

// Configuration file reader
import java.io.*;
import java.util.*;

public class ConfigFileReader {
    private Map<String, String> config = new HashMap<>();
    private String configFile;
    
    public ConfigFileReader(String configFile) {
        this.configFile = configFile;
    }
    
    public void loadConfig() {
        try (BufferedReader reader = new BufferedReader(new FileReader(configFile))) {
            String line;
            int lineNumber = 0;
            
            while ((line = reader.readLine()) != null) {
                lineNumber++;
                line = line.trim();
                
                // Skip empty lines and comments
                if (line.isEmpty() || line.startsWith("#")) {
                    continue;
                }
                
                // Parse key=value pairs
                int equalsIndex = line.indexOf('=');
                if (equalsIndex == -1) {
                    System.err.println("Warning: Invalid format at line " + lineNumber + ": '" + line + "'");
                    continue;
                }
                
                String key = line.substring(0, equalsIndex).trim();
                String value = line.substring(equalsIndex + 1).trim();
                
                config.put(key, value);
            }
            
            System.out.println("Configuration loaded from " + configFile);
            
        } catch (FileNotFoundException e) {
            System.err.println("Config file not found: " + configFile);
            System.err.println("Using default configuration.");
        } catch (IOException e) {
            System.err.println("Error reading config file: " + e.getMessage());
        }
    }
    
    public String getConfigValue(String key, String defaultValue) {
        return config.getOrDefault(key, defaultValue);
    }
    
    public int getConfigValueInt(String key, int defaultValue) {
        String value = config.get(key);
        if (value != null) {
            try {
                return Integer.parseInt(value);
            } catch (NumberFormatException e) {
                System.err.println("Warning: Invalid integer value for key '" + key + "': '" + value + "'");
            }
        }
        return defaultValue;
    }
    
    public boolean getConfigValueBool(String key, boolean defaultValue) {
        String value = config.get(key);
        if (value != null) {
            return value.equalsIgnoreCase("true") || value.equals("1");
        }
        return defaultValue;
    }
    
    public void displayConfig() {
        if (config.isEmpty()) {
            System.out.println("No configuration settings loaded.");
            return;
        }
        
        System.out.println("\n===== CONFIGURATION SETTINGS =====");
        for (Map.Entry<String, String> entry : config.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
        System.out.println("=================================\n");
    }
    
    public static void main(String[] args) {
        // Create a sample config file
        String configFileName = "app.config";
        
        try (PrintWriter writer = new PrintWriter(new FileWriter(configFileName))) {
            writer.println("# Application Configuration");
            writer.println("app.name=MyJavaApp");
            writer.println("app.version=1.0");
            writer.println();
            writer.println("# Database Settings");
            writer.println("db.host=localhost");
            writer.println("db.port=3306");
            writer.println("db.name=mydatabase");
            writer.println();
            writer.println("# Feature Flags");
            writer.println("feature.logging=true");
            writer.println("feature.debug=false");
            
            System.out.println("Sample config file created: " + configFileName);
        } catch (IOException e) {
            System.err.println("Error creating config file: " + e.getMessage());
        }
        
        // Load and use the config file
        ConfigFileReader configReader = new ConfigFileReader(configFileName);
        configReader.loadConfig();
        configReader.displayConfig();
        
        // Access specific configuration values
        String appName = configReader.getConfigValue("app.name", "DefaultApp");
        int dbPort = configReader.getConfigValueInt("db.port", 5432);
        boolean loggingEnabled = configReader.getConfigValueBool("feature.logging", false);
        
        System.out.println("Application: " + appName);
        System.out.println("Database Port: " + dbPort);
        System.out.println("Logging Enabled: " + loggingEnabled);
        
        // Try accessing a non-existent config value
        String timeout = configReader.getConfigValue("request.timeout", "30s");
        System.out.println("Request Timeout: " + timeout);
    }
}