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

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

UNIT 5: Java Programming - Exam-Focused Short Notes

I. Core Java Fundamentals

Iteration Statements (Loops)

Loop Type Execution Flow Use Case
for Initialization → Condition check → Body → Increment/Decrement Known iterations
while Condition check → Body Unknown iterations, condition checked before entry
do-while Body → Condition check Must execute at least once

Example:


for(int i=1; i<=5; i++) { /* executes 5 times */ }

while(condition) { /* may execute 0 times */ }

do { /* executes at least once */ } while(condition);

[!TIP] In do-while, the semicolon after while(condition) is mandatory.

Jump Statements

  • break: Terminates the nearest enclosing loop or switch.

  • continue: Skips current iteration, proceeds to next iteration of the loop.

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

[!TIP] break with label can exit outer loops. continue with label skips to next iteration of labeled loop.

Constructors

Definition: Special method with same name as class, no return type, used to initialize objects.

Types:

  1. Default Constructor: No parameters, provided by JVM if no constructor defined.

  2. Parameterized Constructor: Accepts arguments for initialization.

  3. Copy Constructor: Takes object of same class as parameter (Java doesn't provide by default; must be defined).

Example: Area of Circle


class Circle {

    double radius;

    Circle(double r) { radius = r; } // Parameterized

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

}

[!TIP] Constructor overloading is possible (multiple constructors with different parameters).

static Keyword

  • static variables: Class-level, shared among all objects. Accessed via ClassName.var.

  • static methods: Can be called without object. Cannot access non-static members directly.

  • static block: Executes once when class is loaded. Used for static initialization.


class Example {

    static int count; // static variable

    static { count = 0; } // static block

    static void display() { /* ... */ } // static method

}

final Keyword

Applied To Meaning
Variable Constant (cannot be reassigned)
Method Cannot be overridden
Class Cannot be inherited

final int MAX = 100; // constant

final class Immutable { } // cannot be subclassed

final void show() { } // cannot override

[!TIP] final variables must be initialized once—either at declaration or in constructor.

Garbage Collection

  • Automatic memory management by JVM.

  • Objects with no references are eligible for GC.

  • System.gc(): Suggests JVM to run GC (not guaranteed).

  • finalize(): Called by GC before object is destroyed (deprecated in Java 9+).

[!TIP] finalize() is unreliable—never depend on it for resource cleanup. Use try-with-resources instead.


II. Object-Oriented Programming (OOP)

Features of Java as OOP Language

  1. Encapsulation: Binding data and methods, hide internal details using private and getters/setters.

  2. Inheritance: extends keyword, single inheritance for classes.

  3. Polymorphism: Method overloading (compile-time) and overriding (runtime).

  4. Abstraction: Abstract classes/interfaces hide implementation.

Inheritance Types

Type Description Example
Single One class extends another class B extends A
Multilevel Chain of inheritance C extends B, B extends A
Hierarchical Multiple classes extend one B extends A, C extends A
Multiple Not supported for classes; use interfaces class C implements I1, I2

[!TIP] Java supports multiple inheritance via interfaces only (classes cannot extend multiple classes).

Polymorphism

  • Method Overloading: Same method name, different parameters (compile-time).

  • Method Overriding: Same method signature in subclass (runtime).

  • Dynamic Method Dispatch: Runtime resolution of overridden method call.


class Animal {

    void sound() { System.out.println("Animal sound"); }

}
class Dog extends Animal {

    @Override

    void sound() { System.out.println("Bark"); } // overriding

}
Animal a = new Dog(); a.sound(); // Output: Bark (runtime polymorphism)

Abstraction

  • Abstract Class: Can have abstract methods (no body) and concrete methods. Cannot be instantiated.

  • Interface: All methods are public abstract by default (Java 8+ allows default/static methods).


abstract class Shape {

    abstract double area(); // abstract method

    void display() { System.out.println("Shape"); } // concrete

}
interface Drawable {

    void draw(); // implicitly public abstract

}
class Circle extends Shape implements Drawable {

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

    public void draw() { /* ... */ }

}

Packages

  • Creating: package com.example; (first statement).

  • Importing: import com.example.*; or specific class.

  • Organizes classes, prevents naming conflicts, provides access protection.


// File: com/example/MyClass.java

package com.example;

public class MyClass { }

// Usage:

import com.example.MyClass;

// or

import com.example.*;

Access Modifiers

Modifier Class Package Subclass World
public ✓ ✓ ✓ ✓
protected ✓ ✓ ✓ ✗
default (no modifier) ✓ ✓ ✗ ✗
private ✓ ✗ ✗ ✗

[!TIP] protected allows access in subclasses even in different packages.


III. Exception Handling

Mechanism

  • try: Block containing code that may throw exception.

  • catch: Handles exception of specific type.

  • finally: Always executes (for cleanup), regardless of exception.


try {

    int a = 10/0; // ArithmeticException

} catch (ArithmeticException e) {

    System.out.println("Divide by zero: " + e);

} finally {

    System.out.println("Cleanup code");

}

Exception Classes Hierarchy


Throwable

├── Error (unrecoverable, e.g., OutOfMemoryError)

└── Exception

    ├── RuntimeException (unchecked, e.g., NullPointerException)

    └── Other exceptions (checked, must handle or declare)

throw vs throws

throw throws
Used to throw an exception explicitly Used in method signature to declare exceptions
Example: throw new IOException(); Example: void read() throws IOException
Can throw any Throwable Lists one or more exception classes

Assertions

  • assert statement: assert condition; or assert condition : message;

  • Enabled at runtime with -ea flag; disabled by default.

  • Used for debugging, not for production error handling.

Custom Exceptions


class MyException extends Exception {

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

}
// Usage:

throw new MyException("Custom error");

[!TIP] Checked exceptions must be handled or declared; unchecked (RuntimeException) need not.


IV. Multithreading

Thread Creation

  1. Extend Thread class:

    
    class MyThread extends Thread {
    
        public void run() { /* task */ }
    
    }
    
    new MyThread().start();
    
    
  2. Implement Runnable interface (preferred):

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

[!TIP] Implementing Runnable is better because Java doesn't support multiple inheritance—your class can still extend another class.

Thread Life Cycle


NEW → RUNNABLE → RUNNING → BLOCKED/WATING → TERMINATED

  • NEW: Thread created but not started.

  • RUNNABLE: Ready to run or running.

  • BLOCKED/WAITING: Waiting for resource or sleep()/join().

  • TERMINATED: Completed or killed.

Thread Synchronization

  • synchronized method: Locks the entire object.

    
    synchronized void method() { /* only one thread at a time */ }
    
    
  • synchronized block: Locks specific object, finer control.

    
    synchronized(this) { /* critical section */ }
    
    

Example: Bank Account


class Account {

    private int balance;

    synchronized void deposit(int amt) { balance += amt; }

    synchronized void withdraw(int amt) { balance -= amt; }

}

Inter-thread Communication

  • wait(): Releases lock, waits to be notified.

  • notify(): Wakes up one waiting thread.

  • notifyAll(): Wakes up all waiting threads.

  • Must be called within synchronized context.

Producer-Consumer Skeleton:


synchronized void produce() {

    while (bufferFull) wait();

    // produce item

    notifyAll();

}
synchronized void consume() {

    while (bufferEmpty) wait();

    // consume item

    notifyAll();

}

[!TIP] Always use while loop (not if) with wait() to recheck condition after waking (spurious wakeups).

Example: Multiple Threads with Different Tasks


class Task1 implements Runnable {

    public void run() {

        while(true) { System.out.println("Hello!"); Thread.sleep(1000); }

    }

}
// Similarly for Task2 (2 sec), Task3 (5 sec)


V. Input/Output Streams

Stream Concept

  • Byte Streams: Handle raw binary data (InputStream/OutputStream).

  • Character Streams: Handle text data (Reader/Writer), use encoding.

Character Stream Classes

Class Purpose
FileReader Read characters from file
FileWriter Write characters to file
BufferedReader Efficient reading with buffer (has readLine())
BufferedWriter Efficient writing with buffer
PrintWriter Convenient printing methods (auto-flush option)

Byte Stream Classes

Class Purpose
FileInputStream Read bytes from file
FileOutputStream Write bytes to file

Reading User Input

  1. Scanner (simple, token-based):

    
    Scanner sc = new Scanner(System.in);
    
    int n = sc.nextInt();
    
    
  2. BufferedReader (faster, line-based):

    
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
    String s = br.readLine();
    
    

File Operations: Copy File (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();

    }

} // try-with-resources auto-closes

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


VI. Graphical User Interface (GUI) Programming

AWT (Abstract Window Toolkit)

  • Components: Button, Label, TextField, TextArea, Checkbox, Choice, List, Canvas.

  • Layout Managers:

    | Layout | Arrangement | |--------|-------------| | FlowLayout | Left-to-right, wraps | | BorderLayout | North, South, East, West, Center | | GridLayout | Grid of equal-sized cells | | GridBagLayout | Flexible grid (complex) |

  • Event Handling:

    • Event Source: Component generating event (e.g., Button).

    • Listener Interface: e.g., ActionListener with actionPerformed(ActionEvent e).

    • Adapter Classes: Provide empty implementations (e.g., WindowAdapter).


class MyFrame extends Frame implements ActionListener {

    Button b = new Button("Click");

    MyFrame() {

        b.addActionListener(this);

        add(b);

    }

    public void actionPerformed(ActionEvent e) {

        System.out.println("Clicked");

    }

}

Swing (Lightweight, Pluggable Look and Feel)

  • Components: Prefixed with J—JFrame, JButton, JLabel, JTextField, JTextArea, JCheckBox, JComboBox.

  • Event Handling: Similar to AWT but with JButton.addActionListener(...).

  • Example: Sum of Two Numbers:


import javax.swing.*;

import java.awt.event.*;

class SumGUI extends JFrame implements ActionListener {

    JTextField t1, t2, res;

    JButton add;

    SumGUI() {

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

        add = new JButton("Add");

        add.addActionListener(this);

        // Add components to JFrame using layout (e.g., FlowLayout)

        add(t1); add(t2); add(add); add(res);

    }

    public void actionPerformed(ActionEvent e) {

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

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

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

    }

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

}

Applets (Deprecated in Java 9+, but asked in exams)

Life Cycle Methods:

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

  2. start(): Called after init(), and whenever applet becomes active.

  3. stop(): Called when applet is inactive (e.g., page hidden).

  4. destroy(): Called before applet is unloaded.

  5. paint(Graphics g): Called to draw applet (also on resize/refresh).

HTML Tag:


<applet code="MyApplet.class" width="300" height="200"></applet>

<!-- Modern alternative: <object> or <embed> -->

[!TIP] Applets run in sandbox (security restrictions). They are deprecated due to security issues; use Java Web Start or other technologies.


VII. Database Connectivity (JDBC)

JDBC Architecture & Drivers

  • JDBC API: Java interfaces (Connection, Statement, ResultSet).

  • JDBC Driver: Vendor-specific implementation (converts JDBC calls to DB protocol).

  • Driver Types:

    • Type 1: JDBC-ODBC Bridge (deprecated, uses ODBC driver).

    • Type 2: Native API/part Java driver (uses DB client libraries).

    • Type 3: Middleware/network protocol driver (pure Java, connects to middleware).

    • Type 4: Thin driver (pure Java, direct DB connection—most common).

Steps for Database Access

  1. Load Driver: Class.forName("com.mysql.cj.jdbc.Driver");

  2. Establish Connection:

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

    
    Statement stmt = conn.createStatement();
    
    // or PreparedStatement for parameters:
    
    PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM table WHERE id=?");
    
    
  4. Execute Query:

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

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

  5. Process ResultSet:

    
    while (rs.next()) {
    
        int id = rs.getInt("id");
    
        String name = rs.getString("name");
    
    }
    
    
  6. Close Resources (reverse order):

    
    rs.close(); stmt.close(); conn.close();
    
    // or use try-with-resources (Java 7+)
    
    

Example: Simple SELECT


try (Connection conn = DriverManager.getConnection(url, user, pass);

     Statement stmt = conn.createStatement();

     ResultSet rs = stmt.executeQuery("SELECT * FROM students")) {

    while (rs.next()) {

        System.out.println(rs.getInt("roll") + ": " + rs.getString("name"));

    }

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

[!TIP] Always close ResultSet, Statement, Connection in finally block or use try-with-resources to avoid leaks.


VIII. Networking in Java

Client-Server Model

  • Server: Listens on a port, accepts connections.

  • Client: Connects to server, communicates via streams.

Socket Programming

  • Server: ServerSocket listens, accept() returns Socket for client.

  • Client: Socket connects to server.

  • Communication: Use I/O streams (BufferedReader, PrintWriter) on socket.

Server Code:


ServerSocket ss = new ServerSocket(1234);

Socket client = ss.accept(); // blocks until client connects

BufferedReader in = new BufferedReader(

    new InputStreamReader(client.getInputStream()));

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

String msg = in.readLine();

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

client.close(); ss.close();

Client Code:


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

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

BufferedReader in = new BufferedReader(

    new InputStreamReader(s.getInputStream()));

out.println("Hello Server");

String response = in.readLine();

System.out.println(response);

s.close();

[!TIP] Use try-with-resources for sockets and streams. Server should handle multiple clients via threads.


IX. Java Beans and JNDI

Java Beans

  • Introspection: Analyzing bean properties, events, methods at runtime.

  • BeanInfo Interface: Provides explicit bean information.

    • getPropertyDescriptors(): Returns array of PropertyDescriptor.

    • getEventSetDescriptors(): Returns array of EventSetDescriptor.

    • getMethodDescriptors(): Returns array of MethodDescriptor.

  • Properties: Private fields with getter/setter (getX(), setX()).

  • Events: Follows listener pattern (add/remove listener methods).

  • Methods: Public methods accessible.

Example BeanInfo:


public class MyBeanInfo extends SimpleBeanInfo {

    public PropertyDescriptor[] getPropertyDescriptors() {

        try {

            PropertyDescriptor p = new PropertyDescriptor("name", MyBean.class);

            return new PropertyDescriptor[]{p};

        } catch (IntrospectionException e) { return null; }

    }

}

JNDI (Java Naming and Directory Interface)

  • Context Interface: Core interface for naming operations.

  • Key Methods:

    | Method | Purpose | Syntax | |--------|---------|--------| | bind(String name, Object obj) | Bind name to object | ctx.bind("java:comp/env/bean", obj); | | rebind(String name, Object obj) | Rebind name to new object | ctx.rebind("name", newObj); | | createSubcontext(String name) | Create subcontext | ctx.createSubcontext("apps"); | | getAttributes(String name) | Get attributes of bound object | Attributes attr = ctx.getAttributes("name"); | | modifyAttributes(String name, Attributes attrs) | Modify attributes | ctx.modifyAttributes("name", attrs); |

Typical Usage:


Context ctx = new InitialContext();

Object obj = ctx.lookup("java:comp/env/jdbc/MyDB");

Connection conn = (Connection) obj;

[!TIP] JNDI is used to look up resources (DB connections, EJBs) in Java EE containers.


X. Additional Topics & Programs

Finding $$\displaystyle n^{th} $$ Prime Number

Algorithm:

  1. Initialize count = 0, num = 2.

  2. While count < n:

    • Check if num is prime (test divisibility from 2 to √num).

    • If prime, count++.

    • num++.

  3. Return num-1 (last prime found).

Java Implementation:


static boolean isPrime(int n) {

    if (n <= 1) return false;

    for (int i = 2; i <= Math.sqrt(n); i++) {

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

    }

    return true;

}
static int nthPrime(int n) {

    int count = 0, num = 2;

    while (count < n) {

        if (isPrime(num)) count++;

        num++;

    }

    return num - 1;

}

Other Important Concepts

  • Java as OOP Language Reasons:

    • Everything is inside classes (except packages).

    • Supports all OOP features: encapsulation, inheritance, polymorphism, abstraction.

    • No global functions/variables (except static members).

  • Event Sources and Listeners (GUI):

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

    • Listener: Interface (e.g., ActionListener) with callback method.

    • Registration: source.addListener(listenerInstance).

  • Multiple Inheritance Implementation: Use interfaces—class implements multiple interfaces, provides implementations for all abstract methods.

  • Copy Constructor in Java:

    
    class Student {
    
        int id; String name;
    
        Student(Student s) { this.id = s.id; this.name = s.name; }
    
    }
    
    
  • AWT Facilities Overview:

    • Components, containers, layout managers, event handling model (delegation), graphics toolkit.
  • Levels of Access Protection:

    • Top-level classes: public (accessible everywhere) or package-private (no modifier).

    • Members: public, protected, package-private, private (as per table in Section II).

[!TIP] Past papers frequently ask for comparisons (e.g., overloading vs overriding, byte vs character streams, throw vs throws). Prepare tabular differences.


Final Exam Strategy:

  • Definitions: Memorize key terms (e.g., polymorphism, encapsulation, JDBC steps).

  • Code Snippets: Be ready to write short programs for constructors, multithreading, file copy, GUI sum, JDBC SELECT, client-server.

  • Diagrams: Thread life cycle, exception hierarchy, inheritance types—sketch if asked.

  • Common Pitfalls: static context, final usage, synchronization mistakes, forgetting to close resources, applet deprecation awareness.

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