Skip to content
IT-504 (C) · Java Programming/Quick Revision Short Notes

Java Programming (IT-504 (C)) - Unit 2 Short Notes

1.0 Core Java Fundamentals & Control Flow

1.1 Iteration Statements (Loops)

Used for repeated execution of a code block.

  • for loop: Best when number of iterations is known.

    
    for(initialization; condition; increment/decrement) {
    
        // body
    
    }
    
    
  • while loop: Condition checked before entry. May execute 0 times.

    
    while(condition) {
    
        // body
    
    }
    
    
  • do-while loop: Condition checked after body. Executes at least once.

    
    do {
    
        // body
    
    } while(condition);
    
    

[!TIP] Exam often asks to convert one loop type to another. Remember do-while ends with ;.

1.2 Jump Statements

Alter normal flow.

  • break: Exits the innermost loop or switch.

  • continue: Skips current iteration, proceeds to next. In for, it jumps to update; in while/do-while, to condition check.

  • return: Exits the current method, optionally returning a value.

[!CAUTION] break vs continue: break terminates loop; continue skips to next iteration.

1.3 Constructors

Special method to initialize objects. Same name as class, no return type.

  • Default Constructor: Provided by JVM if no constructor defined. Initializes with default values (0, null).

  • Parameterized Constructor: Takes arguments to initialize with specific values.

  • Copy Constructor: Takes object of same class to copy its values (Java doesn't have built-in, must define).

  • Constructor Overloading: Multiple constructors with different parameters.

Example: Area Calculation


class Circle {

    double radius;

    // Default

    Circle() { radius = 0; }

    // Parameterized

    Circle(double r) { radius = r; }

    double area() { return Math.PI * radius * radius; }

}

2.0 Object-Oriented Programming (OOP) Concepts

2.1 Core OOP Principles

Why Java is OOP:

  • Encapsulation: Bundling data (variables) and code (methods) into a single unit (class). Achieved via access modifiers.

  • Inheritance: Acquiring properties/methods from parent class (extends). Promotes code reuse.

  • Polymorphism: "Many forms". Method overloading (compile-time) and overriding (runtime).

  • Abstraction: Hiding implementation details, showing only functionality. Achieved via abstract classes and interfaces.

2.3 Access Modifiers & Access Protection

Modifier Class Package Subclass (outside pkg) World
private ✅ ❌ ❌ ❌
default ✅ ✅ ❌ ❌
protected ✅ ✅ ✅ ❌
public ✅ ✅ ✅ ✅

[!TIP] "Default" = package-private. No keyword.

2.4 Inheritance & Polymorphism

  • Inheritance: class Child extends Parent { ... }. Java supports single inheritance only for classes.

  • Method Overloading vs Overriding:

Feature Overloading Overriding
Definition Same method name, different params Same method name, same params (signature)
Purpose Compile-time polymorphism Runtime polymorphism
Access Modifier Can change Cannot reduce (can increase)
Return Type Can change Must be same or covariant
Exception Can change Cannot broaden
Static Can overload static methods Cannot override static methods
Binding Static (early) Dynamic (late)
  • Dynamic Method Dispatch (Runtime Polymorphism):

    
    class Animal { void sound() { System.out.println("Animal"); } }
    
    class Dog extends Animal { void sound() { System.out.println("Bark"); } }
    
    class Cat extends Animal { void sound() { System.out.println("Meow"); } }
    
    public class Test {
    
        public static void main(String[] args) {
    
            Animal a;
    
            a = new Dog(); a.sound(); // Output: Bark
    
            a = new Cat(); a.sound(); // Output: Meow
    
        }
    
    }
    
    

    Key: Superclass reference holding subclass object. JVM decides method call at runtime based on actual object type.

2.5 Abstract Classes and Interfaces

Feature Abstract Class Interface
Keyword abstract interface
Methods Can have abstract and concrete methods Java 8+: default, static, abstract. Pre-Java8: only abstract.
Variables Any access modifier, non-final public static final by default
Multiple Inheritance ❌ Not possible for classes ✅ A class can implement multiple interfaces
Constructor ✅ Can have ❌ Cannot have
Purpose Partial abstraction, share common code Complete abstraction, define contract
  • Implementing Multiple Inheritance:

    
    interface A { void show(); }
    
    interface B { void display(); }
    
    class C implements A, B {
    
        public void show() { ... }
    
        public void display() { ... }
    
    }
    
    
  • When to use:

    • Abstract Class: Closely related classes, share common code/state.

    • Interface: Unrelated classes, define a capability/role.

2.6 Special Keywords

  • static:

    • Variable: Single copy per class (class variable). Loaded at class loading.

    • Method: Can be called without object. Cannot use this. Can access only static members.

    • Block: Executed when class is loaded. Used for static initialization.

    
    static int count; // static variable
    
    static { count = 0; } // static block
    
    static void method() { ... } // static method
    
    
  • final:

    • Variable: Constant (value cannot change once assigned). Must be initialized.

    • Method: Cannot be overridden.

    • Class: Cannot be inherited (e.g., String, Math).

    
    final int MAX = 100;
    
    final void display() { ... }
    
    final class MyClass { ... }
    
    

3.0 Exception Handling

3.1 Fundamentals

  • Exception: Event disrupting normal flow. Recoverable (e.g., FileNotFoundException).

  • Error: Serious problem, not recoverable (e.g., OutOfMemoryError). Both are Throwable subclasses.

3.2 Keywords and Blocks


try {

    // code that may throw exception

} catch (ExceptionType e) {

    // handle exception

} finally {

    // always executes (even if return in try/catch). For cleanup (close files, DB connections).

}
  • throw: Used to throw an exception explicitly (creates exception object).

    
    if (age < 18) throw new ArithmeticException("Access denied");
    
    
  • throws: Used in method signature to declare exceptions that method might throw. Caller must handle or declare.

    
    void readFile() throws IOException { ... }
    
    
  • assert: Debugging tool. Checks boolean condition. Enabled with -ea JVM flag.

    
    assert divisor != 0 : "Divisor cannot be zero";
    
    

[!TIP] throw vs throws: throw is action (inside method), throws is declaration (in signature).

3.3 Exception Types

  • Checked: Checked at compile-time. Must be handled or declared (e.g., IOException, SQLException).

  • Unchecked: Checked at runtime. Subclasses of RuntimeException (e.g., NullPointerException, ArrayIndexOutOfBoundsException).

3.4 Custom Exceptions

Create by extending Exception (checked) or RuntimeException (unchecked).


class MyException extends Exception {

    MyException(String msg) { super(msg); }

}

4.0 Multithreading

4.1 Introduction

  • Thread: Lightweight, smallest unit of processing. Java programs are multithreaded by default (main thread).

  • Advantages: Better CPU utilization, responsiveness, resource sharing.

4.2 Thread Creation

  1. By extending Thread class:

    
    class MyThread extends Thread {
    
        public void run() { System.out.println("Thread running"); }
    
    }
    
    new MyThread().start();
    
    
  2. By implementing Runnable interface (preferred, as Java doesn't support multiple inheritance for classes):

    
    class MyRunnable implements Runnable {
    
        public void run() { System.out.println("Thread running"); }
    
    }
    
    new Thread(new MyRunnable()).start();
    
    

[!TIP] Always start thread with start(), not run(). start() creates new call stack; run() runs in current thread.

4.4 Thread Synchronization

  • Need: Prevent race condition when multiple threads access shared resource.

  • Synchronized Method: Locks entire object for the method's duration.

    
    synchronized void method() { ... }
    
    
  • Synchronized Block: Locks only a specific object, finer control.

    
    synchronized(this) { ... } // locks current object
    
    synchronized(obj) { ... }  // locks specified object
    
    

4.5 Inter-Thread Communication

Methods of Object class, must be called from synchronized context.

  • wait(): Thread releases lock and enters WAITING state.

  • notify(): Wakes up one waiting thread.

  • notifyAll(): Wakes up all waiting threads.

Example: Producer-Consumer (simplified)


synchronized void produce() {

    while (bufferFull) wait(); // wait if full

    // produce item

    notify(); // notify consumer

}
synchronized void consume() {

    while (bufferEmpty) wait(); // wait if empty

    // consume item

    notify(); // notify producer

}

5.0 Input/Output (I/O) Streams

5.1 Stream Concepts

  • Stream: Sequence of data.

  • Byte Streams (InputStream/OutputStream): Handle raw binary data (8-bit bytes). Used for images, audio, etc.

  • Character Streams (Reader/Writer): Handle text data (16-bit Unicode). Automatically handle character encoding. Preferred for text files.

5.2 Key Stream Classes

Byte Streams Character Streams
FileInputStream FileReader
FileOutputStream FileWriter
BufferedInputStream BufferedReader (has readLine())
PrintStream PrintWriter

5.3 File Operations

Copy file using character streams:


try (BufferedReader br = new BufferedReader(new FileReader("source.txt"));

     BufferedWriter bw = new BufferedWriter(new FileWriter("dest.txt"))) {

    String line;

    while ((line = br.readLine()) != null) {

        bw.write(line);

        bw.newLine();

    }

} catch (IOException e) { e.printStackTrace(); }

[!TIP] Use try-with-resources (Java 7+) to auto-close streams.


6.0 Graphical User Interface (GUI) with AWT & Swing

6.1 AWT Event Handling Model

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

  • Event Listener: Object that handles event. Must implement listener interface (e.g., ActionListener).

  • Event Class: Object carrying event info (e.g., ActionEvent).

  • Steps:

    1. Create component.

    2. Register listener: button.addActionListener(this); (if class implements ActionListener) or button.addActionListener(e -> {...}); (lambda).

    3. Implement callback method: public void actionPerformed(ActionEvent e) { ... }.

6.2 Swing Components

  • Swing vs AWT: Swing components are lightweight (pure Java, drawn by JVM), AWT are heavyweight (native OS peers). Swing provides richer set.

  • Basic Components:

    • Top-level container: JFrame, JDialog

    • Basic: JButton, JLabel, JTextField, JTextArea, JCheckBox, JRadioButton

    • Containers: JPanel, JScrollPane

  • Example: Sum of Two Numbers:


import javax.swing.*;

import java.awt.event.*;

public class SumGUI extends JFrame implements ActionListener {

    JTextField t1, t2, res;

    JButton add;

    public SumGUI() {

        t1 = new JTextField(10); t2 = new JTextField(10); res = new JTextField(10);

        add = new JButton("Add");

        add.addActionListener(this);

        add(new JLabel("Num1")); add(t1);

        add(new JLabel("Num2")); add(t2);

        add(add); add(res);

        setLayout(new FlowLayout());

        setSize(300,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);

    }

    public void actionPerformed(ActionEvent e) {

        try {

            int a = Integer.parseInt(t1.getText());

            int b = Integer.parseInt(t2.getText());

            res.setText(String.valueOf(a+b));

        } catch (Exception ex) { res.setText("Invalid"); }

    }

    public static void main(String[] args) { new SumGUI(); }

}

7.0 Applets

  • What: Small Java program embedded in HTML, runs in browser.

  • Life Cycle:

    1. init(): Called once when applet first loads. Initialize resources.

    2. start(): Called after init(), and whenever user returns to page. Start animation/threads.

    3. stop(): Called when user leaves page. Pause threads.

    4. destroy(): Called when browser closes. Final cleanup.

  • paint(Graphics g): Called to draw graphics. Override to customize.

  • HTML Tag (Deprecated in modern browsers):

    
    <applet code="MyApplet.class" width="300" height="200"></applet>
    
    <!-- or -->
    
    <object code="MyApplet.class" width="300" height="200"></object>
    
    
  • Limitations: Security restrictions (sandbox), requires Java plugin (no longer supported in modern browsers). Replaced by Java Web Start (also deprecated) and web applications.


8.0 Java Database Connectivity (JDBC)

8.2 Basic Steps for Database Access

  1. Load Driver: Class.forName("com.mysql.cj.jdbc.Driver"); (JDBC 4.0+ often auto-loads).

  2. Establish Connection:

    
    Connection con = DriverManager.getConnection(
    
        "jdbc:mysql://localhost:3306/dbname", "user", "password");
    
    
  3. Create Statement:

    • Statement stmt = con.createStatement(); (for static SQL)

    • PreparedStatement pstmt = con.prepareStatement("INSERT INTO table VALUES (?, ?)"); (for dynamic SQL, prevents SQL injection).

  4. Execute Query:

    • ResultSet rs = stmt.executeQuery("SELECT * FROM table"); (for SELECT)

    • int rows = stmt.executeUpdate("INSERT ..."); (for INSERT/UPDATE/DELETE)

  5. Process Results:

    
    while (rs.next()) {
    
        int id = rs.getInt("id");
    
        String name = rs.getString("name");
    
    }
    
    
  6. Close Connections: Close ResultSet, Statement, Connection in reverse order. Use try-with-resources.

8.3 JDBC-ODBC Bridge

  • Concept: JDBC driver that translates JDBC calls to ODBC calls. Allowed Java to connect to any ODBC-compliant DB (like MS Access).

  • Usage (Historical):

    
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    
    Connection con = DriverManager.getConnection("jdbc:odbc:DataSourceName");
    
    
  • Status: Removed in Java 8. Use native JDBC drivers now.


9.0 Networking in Java

9.2 Client-Server Communication

Server:


ServerSocket ss = new ServerSocket(1234);

Socket s = ss.accept(); // waits for client

BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

PrintWriter out = new PrintWriter(s.getOutputStream(), true);

String msg = in.readLine();

out.println("Echo: " + msg);

s.close(); ss.close();

Client:


Socket s = new Socket("localhost", 1234);

BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

PrintWriter out = new PrintWriter(s.getOutputStream(), true);

out.println("Hello Server");

String response = in.readLine();

s.close();

[!TIP] PrintWriter with true auto-flushes on println().


10.0 Java Beans & JNDI

10.1 Java Beans Characteristics

  1. No-arg constructor.

  2. Properties accessed via getter/setter methods (getXxx(), setXxx()).

  3. Implements Serializable (for persistence).

10.2 Introspection

  • What: Process of analyzing a Bean's properties, events, methods at runtime.

  • BeanInfo Interface: Provides explicit bean information. Implement getBeanDescriptor(), getPropertyDescriptors(), etc. Used by IDE tools (like NetBeans Matisse) to display properties in property sheet.

10.3 JNDI Key Methods

JNDI provides naming/directory service. Context interface is central.

  • bind(String name, Object obj): Binds object to name. Fails if name exists.

  • rebind(String name, Object obj): Binds or rebinds object to name.

  • createSubcontext(String name): Creates new subcontext (like mkdir).

  • getAttributes(String name): Returns Attributes object for named object.

  • modifyAttributes(String name, ModificationItem[] mods): Modifies attributes of named object.


11.0 Garbage Collection

  • Purpose: Automatically reclaim memory from unreachable objects.

  • How (Overview):

    1. Mark: Identify reachable objects (from GC roots: local vars, static fields, etc.).

    2. Sweep: Remove unmarked (unreachable) objects.

    • Modern GC: Generational (Young Gen: Eden, S0, S1; Old Gen). Minor GC in Young, Major/Full GC in Old.
  • finalize():

    • Called by GC once before object memory is reclaimed.

    • Unreliable: No guarantee when/if called. Avoid for critical cleanup. Use try-finally or Cleaner (Java 9+).

  • System.gc() / Runtime.gc(): Suggests JVM to run GC. Not guaranteed. Use only for debugging/memory analysis.


12.0 Packages

  • Purpose: Namespace management, access protection, grouping related classes.

  • Creating:

    
    package com.mypackage; // first statement
    
    public class MyClass { ... }
    
    

    Directory structure: com/mypackage/MyClass.java

  • Using:

    
    import com.mypackage.MyClass; // specific
    
    import com.mypackage.*;      // all classes in package
    
    
  • Accessing from another package:

    • public classes/members: accessible.

    • protected members: accessible in subclasses (even if in different package).

    • default members: accessible only within same package.

    • private: never accessible outside class.


13.0 Problem-Solving & Algorithm Implementation (Java Context)

13.1 Program to Find nth Prime Number


import java.util.Scanner;

public class NthPrime {

    static boolean isPrime(int n) {

        if (n <= 1) return false;

        for (int i = 2; i*i <= n; i++) {

            if (n % i == 0) return false;

        }

        return true;

    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt(), count = 0, num = 2;

        while (count < n) {

            if (isPrime(num)) count++;

            if (count == n) {

                System.out.println(n + "th prime: " + num);

                break;

            }

            num++;

        }

        sc.close();

    }

}

[!TIP] Optimize by checking divisibility up to $\sqrt{n}$ (i*i <= n).

13.2 Search Algorithms: DFS vs BFS

Feature Depth-First Search (DFS) Breadth-First Search (BFS)
Data Structure Stack (recursion/expl) Queue
Memory Less (stores one path) More (stores all nodes at current level)
Completeness Not complete (may get stuck in deep branch) Complete (finds shallowest solution)
Optimality Not optimal Optimal (for unweighted graphs)
Use Case Maze solving, backtracking Shortest path, web crawling

13.3 A Algorithm*

  • Concept: Best-first search using heuristic to find optimal path.

  • Evaluation Function: $$\displaystyle f(n) = g(n) + h(n) $$

    • $g(n)$: Actual cost from start to node $n$ (e.g., depth, path length).

    • $h(n)$: Heuristic estimated cost from $n$ to goal (e.g., Manhattan distance, misplaced tiles).

  • Requirement: $h(n)$ must be admissible (never overestimates true cost) for optimality.

  • 8-Puzzle Example:

    • $g(n)$ = depth of node.

    • $h(n)$ = number of misplaced tiles.

    • Expand node with lowest $f(n)$.

13.4 Hill Climbing Algorithm Problems

  • Local Maxima: Peak that is higher than neighbors but not highest (global maxima). Algorithm stops here.

  • Plateau: Flat region where all neighbors have same value. No direction to move.

  • Ridge: Sequence of local maxima with steep slopes. Difficult to ascend due to multiple directions.

  • Other Issues: Cannot backtrack, depends on initial state, may oscillate. Variants: Steepest-Ascent, First-Choice, Stochastic, Simulated Annealing (to escape local maxima).

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