Java Intermediate Concepts

Reference notes covering intermediate Java programming concepts for building more complex applications.

The Problem-Solving Process

Before writing any code, always follow this process:

Step-by-Step Problem Solving:

  1. 1. Understand the Problem - Read and analyze what needs to be solved
  2. 2. Get Paper and Pen - Write down the problem in your own words
  3. 3. Break It Down - Identify the main steps and sub-problems
  4. 4. Plan the Solution - Think through the logic step by step
  5. 5. Create a Flowchart - Visualize the process flow
  6. 6. Write Pseudocode - Describe the solution in plain English
  7. 7. Only Then Code - Translate your plan into Java code

Why This Matters:

Many beginners jump straight to coding without understanding the problem first. This leads to confusion, bugs, and inefficient solutions. Always solve the problem on paper first, then translate your solution to code. This is the foundation of good programming practice.

Overview

These notes cover intermediate Java programming concepts that build upon the fundamentals. The content includes practical examples and reference material for building more complex applications.

Intermediate Java Concepts

1. Object-Oriented Programming (OOP)

Advanced OOP concepts including inheritance, polymorphism, and design patterns.

  • • Classes and objects
  • • Constructors and constructor overloading
  • • Encapsulation (private, public, protected)
  • • Inheritance and polymorphism
  • • Abstract classes and interfaces
  • • Design patterns (Singleton, Factory)

2. Exception Handling

Writing robust code that handles errors gracefully.

  • • try-catch-finally blocks
  • • Checked vs unchecked exceptions
  • • Creating custom exceptions
  • • Best practices for exception handling
  • • Exception propagation

3. File I/O & Basic Applications

Building real-world applications with file operations.

  • • Reading from and writing to files
  • • Scanner and BufferedReader
  • • Building console applications
  • • Project structure and organization
  • • Working with different file formats

Advanced Login System with OOP

Building upon the basic login system, we'll create a more sophisticated version using intermediate Java concepts.

Step 1: User Class (OOP - Encapsulation)

public class User {
    private String username;
    private String password;
    private String email;
    private boolean isActive;
    
    // Constructor
    public User(String username, String password, String email) {
        this.username = username;
        this.password = password;
        this.email = email;
        this.isActive = true;
    }
    
    // Getters and Setters (Encapsulation)
    public String getUsername() {
        return username;
    }
    
    public String getEmail() {
        return email;
    }
    
    public boolean isActive() {
        return isActive;
    }
    
    public void setActive(boolean active) {
        this.isActive = active;
    }
    
    // Method to verify password
    public boolean verifyPassword(String inputPassword) {
        return this.password.equals(inputPassword);
    }
}

Step 2: LoginManager Class (OOP - Single Responsibility)

public class LoginManager {
    private List<User> users;
    private int maxAttempts;
    
    public LoginManager() {
        this.users = new ArrayList<>();
        this.maxAttempts = 3;
        initializeUsers();
    }
    
    private void initializeUsers() {
        users.add(new User("admin", "password123", "admin@example.com"));
        users.add(new User("user1", "mypass456", "user1@example.com"));
        users.add(new User("test", "testpass", "test@example.com"));
    }
    
    public User authenticateUser(String username, String password) throws LoginException {
        User user = findUser(username);
        
        if (user == null) {
            throw new LoginException("User not found");
        }
        
        if (!user.isActive()) {
            throw new LoginException("Account is deactivated");
        }
        
        if (!user.verifyPassword(password)) {
            throw new LoginException("Invalid password");
        }
        
        return user;
    }
    
    private User findUser(String username) {
        for (User user : users) {
            if (user.getUsername().equals(username)) {
                return user;
            }
        }
        return null;
    }
}

Step 3: Custom Exception (Exception Handling)

public class LoginException extends Exception {
    public LoginException(String message) {
        super(message);
    }
    
    public LoginException(String message, Throwable cause) {
        super(message, cause);
    }
}

Step 4: File Operations (File I/O)

public class UserFileManager {
    private static final String USERS_FILE = "users.txt";
    
    public void saveUserToFile(User user) {
        try (FileWriter writer = new FileWriter(USERS_FILE, true)) {
            writer.write(user.getUsername() + "," + user.getEmail() + "\n");
            System.out.println("User saved to file successfully");
        } catch (IOException e) {
            System.err.println("Error saving user: " + e.getMessage());
        }
    }
    
    public void loadUsersFromFile() {
        try (BufferedReader reader = new BufferedReader(new FileReader(USERS_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length >= 2) {
                    System.out.println("Loaded user: " + parts[0] + " (" + parts[1] + ")");
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

Step 5: Complete Application (Integration)

public class AdvancedLoginSystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        LoginManager loginManager = new LoginManager();
        UserFileManager fileManager = new UserFileManager();
        
        System.out.println("=== Advanced Login System ===");
        
        int attempts = 0;
        boolean loginSuccessful = false;
        
        while (attempts < 3 && !loginSuccessful) {
            try {
                attempts++;
                System.out.println("\nAttempt " + attempts + " of 3");
                
                System.out.print("Enter username: ");
                String username = scanner.nextLine();
                
                System.out.print("Enter password: ");
                String password = scanner.nextLine();
                
                User user = loginManager.authenticateUser(username, password);
                
                System.out.println("\nLogin successful! Welcome, " + user.getUsername() + "!");
                System.out.println("Email: " + user.getEmail());
                
                // Save login to file
                fileManager.saveUserToFile(user);
                
                loginSuccessful = true;
                
            } catch (LoginException e) {
                System.out.println("Login failed: " + e.getMessage());
                if (attempts < 3) {
                    System.out.println("Please try again...");
                }
            }
        }
        
        if (!loginSuccessful) {
            System.out.println("\nMaximum attempts reached. Access denied!");
        }
        
        scanner.close();
    }
}

Key Concepts Covered

These notes will help you understand:

  • • Design and implement complex class hierarchies
  • • Apply OOP principles effectively
  • • Handle exceptions and errors gracefully
  • • Work with files and I/O operations
  • • Build complete console applications
  • • Debug and troubleshoot Java programs
  • • Apply design patterns in real projects
  • • Prepare for advanced Java frameworks
← Back to Programming Notes
Java Intermediate Concepts