Skip to content
EX-306 · Computer Programming-I (JAVA)/Quick Revision Short Notes

Computer Programming-I (JAVA) (EX-306) - Unit 5 Short Notes

5.0 Exception Handling & Robust Programming

5.1 Fundamentals of Exceptions

  • Definition: An exception is an event that disrupts the normal flow of a program. It is an object representing an error or unusual condition.

  • Error Types:

    • Compile-time (Syntax) Errors: Detected by the compiler (e.g., missing semicolon).

    • Runtime (Logical) Errors: Occur during execution; exceptions are used to handle these.

  • Exception Hierarchy:

    | Class | Description | | :--- | :--- | | Throwable | Root of all exceptions. | | Exception | Conditions a program might want to catch. | | RuntimeException | Unchecked exceptions (e.g., NullPointerException). | | Error | Serious system errors (e.g., OutOfMemoryError), not caught. |

  • Checked vs. Unchecked Exceptions:

    • Checked: Subclasses of Exception (excluding RuntimeException). Must be declared or handled (e.g., IOException).

    • Unchecked: Subclasses of RuntimeException or Error. Handling is optional (e.g., ArithmeticException).

5.2 Try-Catch Mechanism

  • Syntax:

    
    try {
    
        // Code that might throw an exception
    
    } catch (ExceptionType1 e1) {
    
        // Handler for ExceptionType1
    
    } catch (ExceptionType2 e2) {
    
        // Handler for ExceptionType2
    
    } finally {
    
        // Code that ALWAYS executes (cleanup)
    
    }
    
    
  • Multiple catch Blocks: Order matters! Place more specific exceptions before general ones (e.g., catch(FileNotFoundException) before catch(IOException)). Otherwise, the general catch will "catch" all, making specific ones unreachable → Compile Error.

  • The finally Block:

    • Executes regardless of whether an exception was thrown or caught.

    • Used for critical cleanup (e.g., closing files, releasing resources).

    • Executes even if try or catch contains a return statement.

[!TIP] Common Pitfall: A finally block will not execute if the JVM exits abruptly (e.g., System.exit(), power failure, infinite loop).

5.3 Throwing Exceptions

  • throw Statement: Used to manually throw an exception object.

    
    if (age < 0) {
    
        throw new IllegalArgumentException("Age cannot be negative");
    
    }
    
    
  • Custom Exceptions: Create by extending Exception (for checked) or RuntimeException (for unchecked).

    
    class InsufficientFundsException extends Exception {
    
        public InsufficientFundsException(String msg) {
    
            super(msg);
    
        }
    
    }
    
    

5.4 The throws Clause

  • Purpose: Declares that a method might throw a listed exception. Forces the caller to handle or declare it.

    
    public void readFile(String path) throws IOException {
    
        // Method body
    
    }
    
    
  • throw vs. throws:

    • throw: Action – throws an exception object.

    • throws: Declaration – part of method signature, lists possible exceptions.

5.5 Common Exception Classes

Exception Typical Cause
ArithmeticException Division by zero (/0).
NullPointerException Accessing method/field on a null reference.
ArrayIndexOutOfBoundsException Invalid array index.
NumberFormatException Parsing invalid number string (e.g., Integer.parseInt("abc")).
IOException General I/O failure (file not found, read error).

5.1 Fundamental Java APIs & Strings (Deep Dive)

5.1.1 The String Class Revisited

  • Immutability: Once created, a String object's value cannot be changed. Operations like concat() or replace() return new String objects.

    • Implication: Frequent modification (e.g., in loops) is inefficient → use StringBuilder.
  • Essential Methods:

    | Method | Purpose | Returns | | :--- | :--- | :--- | | length() | Number of characters. | int | | charAt(i) | Character at index i. | char | | substring(b, e) | Substring from b (inclusive) to e (exclusive). | String | | equals(obj) | Content equality (case-sensitive). | boolean | | compareTo(str) | Lexicographical comparison. | int (<0, 0, >0) | | indexOf(ch) | First index of character/substring. | int (-1 if not found) | | toLowerCase(), toUpperCase() | Case conversion. | String | | trim() | Removes leading/trailing whitespace. | String | | split(regex) | Splits string into array using regex delimiter. | String[] |

  • StringBuilder / StringBuffer:

    • Mutable sequence of characters.

    • StringBuilder (non-synchronized, faster) vs. StringBuffer (synchronized, thread-safe).

    • Key methods: append(), insert(), delete(), reverse().

5.1.2 Wrapper Classes & Autoboxing/Auto-unboxing

  • Purpose: Represent primitive types as objects (e.g., for collections which require objects).

  • Key Wrappers: Integer, Double, Character, Boolean.

  • Conversion:

    • Primitive → Object (Boxing): Integer i = 10; (Autoboxing)

    • Object → Primitive (Unboxing): int j = i; (Auto-unboxing)

    • Explicit: Integer i = Integer.valueOf(10); / int j = i.intValue();

  • Utility Methods: Integer.parseInt(String), Double.parseDouble(String), String.valueOf(primitive).


5.2 Collections Framework (Introduction)

5.2.1 Core Interfaces & Purpose

Interface Order? Duplicates? Common Implementations Key Feature
List Yes (by index) Yes ArrayList, LinkedList Random access (get(i)).
Set No No HashSet, LinkedHashSet Uniqueness. LinkedHashSet preserves insertion order.
Map N/A (key-value) Keys: No, Values: Yes HashMap, LinkedHashMap Key-based lookup. LinkedHashMap preserves insertion order.

5.2.2 Common Operations

  • Adding: list.add(obj), map.put(key, value)

  • Accessing: list.get(index), map.get(key)

  • Removing: list.remove(index) or list.remove(obj), map.remove(key)

  • Iteration:

    
    // Enhanced for-loop
    
    for (String s : list) { ... }
    
    // Iterator
    
    Iterator<String> it = list.iterator();
    
    while (it.hasNext()) { String s = it.next(); }
    
    
  • Collections Utility Class:

    • Collections.sort(list)

    • Collections.shuffle(list)

    • Collections.binarySearch(list, key) (requires sorted list)

5.2.3 Generics (Introduction)

  • Purpose: Provide type safety at compile time. Eliminates need for casting and prevents ClassCastException at runtime.

  • Syntax: List<String> names = new ArrayList<>();

  • Raw Types vs. Parameterized Types:

    • Raw: List list = new ArrayList(); // Unsafe, generates warning.

    • Parameterized: List<String> list = new ArrayList<String>(); // Safe.

  • Generic Class/Method: class Box<T> { private T item; }


5.3 File I/O (Basic)

5.3.1 Streams, Readers, and Writers

  • Byte Streams (InputStream/OutputStream): For raw binary data (images, audio).

  • Character Streams (Reader/Writer): For text data (handles character encoding). Preferred for text files.

  • File Class: Represents file/directory path names. Does not create/file data.

    
    File f = new File("test.txt");
    
    boolean exists = f.exists();
    
    

5.3.2 Reading & Writing Text Files

Class Purpose Buffering?
FileReader / FileWriter Basic character stream. No (inefficient for many small reads/writes).
BufferedReader / BufferedWriter Wraps another reader/writer for efficiency (buffers data). Yes
PrintWriter Convenient print()/println() methods. Can wrap BufferedWriter. Optional
  • Try-with-resources (Java 7+): Automatically closes resources (AutoCloseable).

    
    try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    
        String line;
    
        while ((line = br.readLine()) != null) {
    
            System.out.println(line);
    
        }
    
    } catch (IOException e) {
    
        e.printStackTrace();
    
    }
    
    // br is automatically closed here.
    
    

    \boxed{\text{try (ResourceType res = new Resource()) { } catch (Exception e) { }}}


5.4 Introduction to Multithreading (Basic Concepts)

5.4.1 What is a Thread?

  • A thread is a lightweight sub-process, the smallest unit of execution.

  • Creating Threads:

    1. Extend Thread class: Override run().

      
      class MyThread extends Thread {
      
          public void run() { /* task */ }
      
      }
      
      new MyThread().start();
      
      
    2. Implement Runnable interface: Pass Runnable to Thread constructor. Preferred (Java doesn't support multiple inheritance).

      
      class MyRunnable implements Runnable {
      
          public void run() { /* task */ }
      
      }
      
      new Thread(new MyRunnable()).start();
      
      

5.4.2 Thread Lifecycle & States

  1. NEW: Thread object created, start() not called.

  2. RUNNABLE: Thread is executing or ready to execute (in runnable pool).

  3. BLOCKED: Waiting to acquire a monitor lock (for synchronized block/method).

  4. WAITING: Waiting indefinitely (Object.wait(), Thread.join()).

  5. TIMED_WAITING: Waiting for specified time (Thread.sleep(ms)).

  6. TERMINATED: run() completed or died.

5.4.3 Basic Thread Control

  • start():** *Starts* the thread and calls run()**in a new call stack**. **Never callrun()` directly (executes in current thread).

  • `run(): Contains the code to be executed in the new thread.

  • **Thread.sleep(ms):** Pauses current thread for msmilliseconds. ThrowsInterruptedException`.

  • synchronized: Keyword to prevent thread interference and memory consistency errors.

    • Synchronized method: public synchronized void method() { ... }

    • Synchronized block: synchronized(obj) { ... }

[!TIP] Exam Focus: Understand the difference between start() (creates new thread) and run() (ordinary method call). Know why synchronized is needed (shared mutable data).


5.5 Introduction to GUI Programming (Swing)

5.5.1 AWT vs. Swing

  • AWT: Heavyweight components (native OS peers). java.awt package.

  • Swing: Lightweight components (pure Java, more flexible). javax.swing package.

    • Pluggable Look-and-Feel (PLAF): Can change appearance at runtime.

    • All Swing components start with J (e.g., JFrame, JButton).

5.5.2 Core Swing Components

Component Purpose
JFrame Top-level window (main application window).
JDialog Pop-up window dependent on a frame.
JLabel Display read-only text or image.
JButton Clickable button.
JTextField Single-line text input.
JTextArea Multi-line text input.
JCheckBox On/off toggle (multiple selections allowed).
JRadioButton Mutually exclusive selection (used with ButtonGroup).
  • Layout Managers: Control component arrangement.

    • FlowLayout (default for JPanel): Left-to-right, wraps.

    • BorderLayout (default for JFrame content pane): North, South, East, West, Center.

    • GridLayout (rows, cols): Uniform grid.

5.5.3 Event Handling

  • Event Delegation Model:

    1. Event Source: Component that generates event (e.g., JButton).

    2. Event Object: Encapsulates event info (e.g., ActionEvent).

    3. Listener Interface: Defines callback method (e.g., ActionListener with actionPerformed(ActionEvent e)).

    4. Listener Object: Class that implements listener interface and is registered with source.

  • Registering Listener: button.addActionListener(listenerObject);

  • Anonymous Inner Class (Common Pattern):

    
    JButton btn = new JButton("Click");
    
    btn.addActionListener(new ActionListener() {
    
        public void actionPerformed(ActionEvent e) {
    
            // Code to execute on click
    
        }
    
    });
    
    

    Java 8+ Lambda: btn.addActionListener(e -> { /* code */ }); (since ActionListener is a Functional Interface).

Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in