Unit I – Introduction to Object Oriented Programming

📌 Total Hours: 07

Black: Headings & Definitions
Blue: Explanations
Green: Code Examples
Yellow: Important Keywords

📋 Syllabus Outline

  • Introduction & Need of OOP
  • Principles of Object-Oriented Languages
  • Procedural Language Vs OOP
  • Application of OOP
  • Java Virtual Machine
  • Java Features
  • Program Structures
  • Java Programming Constructs: Variables, Data Types, Identifiers, Literals, Operators, Expressions, Precedence, Type Conversion, Flow of Control

1. Introduction to OOP

Definition: Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects which contain data (attributes) and methods (behaviors) to operate on that data.
In OOP, we think in terms of objects (real-world entities like Student, Car, BankAccount) instead of just functions and procedures. Each object has state (data/attributes) and behavior (methods/functions). OOP makes programs easier to understand, modify, reuse, and maintain.

2. Need of OOP

Why OOP? Because Procedural Programming has limitations in managing large projects, data security, and code reusability.
  1. Overcomes limitations of procedural programming – Procedural languages focus on functions and share data globally, leading to poor data security and difficult maintenance.
  2. Better code reusability – Once a class is written, it can be reused to create many objects and reused in other programs.
  3. Improved maintainability – Changes in one part of code are localized due to encapsulation and modular design.
  4. Closer to real world – OOP models real-world entities as objects, making design more natural.
  5. Data security – Encapsulation hides data and protects it from unauthorized access.
  6. Scalability and extensibility – New features can be added using inheritance and polymorphism with minimal impact on existing code.

3. Principles of Object-Oriented Programming

3.1 Encapsulation

Definition: Encapsulation is the process of binding data and methods together into a single unit called a class, and restricting direct access to some object components.
Key Points:
  • Data is kept safe from outside interference.
  • Access is given through methods (getters/setters).
  • Provides data hiding and data security.

3.2 Inheritance

Definition: Inheritance is a mechanism where one class acquires the properties and behaviors (data members and methods) of another class.
Key Points:
  • The existing class is called Super / Base / Parent class.
  • The new class is called Sub / Derived / Child class.
  • Promotes code reusability.
class Parent { // data and methods } class Child extends Parent { // inherits Parent's members // additional data and methods }

3.3 Polymorphism

Definition: Polymorphism means "many forms" – the same name (method or operator) can be used in different ways or contexts.
Key Points:
  • Same method name can behave differently based on arguments or object type.
  • Method Overloading: Same name, different parameters (Compile-time polymorphism)
  • Method Overriding: Same signature in parent and child (Runtime polymorphism)

3.4 Abstraction

Definition: Abstraction is the process of hiding complex internal details and showing only essential features to the user.
Key Points:
  • User sees what an object does, not how it does it.
  • Achieved using abstract classes and interfaces.
  • Reduces complexity and increases clarity.

4. Procedural Language Vs Object-Oriented Programming

Procedural Programming Object-Oriented Programming
Focus on functions/procedures Focus on objects and data
Top-down design approach Bottom-up design approach
Data and functions are separate Data and functions are bundled in classes
No strong data hiding Data hiding via encapsulation
Low code reusability High code reusability via inheritance
Difficult to manage large projects Easier to manage, modify, and extend
Examples: C, Pascal Examples: Java, C++, Python
★ Exam Point: OOP is preferred for large and complex applications due to code reusability, data security, and modularity.

5. Application of OOP

  • Real-world modeling – Bank, Library, College management systems
  • GUI-based applications – Desktops, Mobile apps
  • Simulation and modeling tools – Scientific simulations
  • Reusable libraries and frameworks – Hibernate, Spring, etc.

6. Java Virtual Machine (JVM)

Definition: JVM (Java Virtual Machine) is an abstract machine that provides the runtime environment to run Java bytecode on any platform.
Key Points:
  • Makes Java platform independent"Write Once, Run Anywhere (WORA)"
  • Converts bytecode into machine-specific code of the underlying OS.
  • Provides memory management, security, and exception handling.

JVM Working Process:

  1. Java source code is written in a file with extension .java
  2. Java compiler converts it to bytecode (.class)
  3. JVM loads the bytecode into memory.
  4. Bytecode verifier checks for illegal or unsafe code.
  5. JVM interprets or JIT-compiles bytecode to machine-specific code.
  6. Program executes and produces output.
┌─────────────────┐ │ Source Code │ │ (.java) │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Compiler │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Bytecode │ │ (.class) │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ JVM │ │ (Interpreter) │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Machine │ │ Code │ └─────────────────┘

7. Java Features

📌 Simple

Syntax similar to C/C++ but without complex features like multiple inheritance using classes, pointer arithmetic, etc. Easy to learn and understand.

📌 Object-Oriented

Everything in Java is represented as objects and classes. Supports all OOP principles natively.

📌 Platform-Independent

Java programs are compiled into bytecode, which can run on any machine with JVM. This is the principle of WORA (Write Once, Run Anywhere).

📌 Secure

  • No explicit pointers (reduces buffer overflow attacks)
  • Bytecode verification at runtime
  • Security manager controls access to system resources

📌 Robust

  • Strong memory management
  • Exception handling mechanism
  • Automatic garbage collection

📌 Multithreaded

Supports multithreading – multiple threads of execution within a single program, enabling concurrent operations.

📌 Portable

Same bytecode can be executed on different platforms without modification, making Java truly portable.

8. Java Program Structure

// Step 1: Package statement (optional) package packagename; // Step 2: Import statements (optional) import java.util.*; import java.io.*; // Step 3: Class definition public class HelloWorld { // Step 4: Data members (variables) // static int count; // Step 5: Methods public static void main(String[] args) { // Program logic here System.out.println("Hello World"); } }
Note:
  • File name must match the public class name.
  • main method is the entry point of every Java program.
  • String[] args allows passing command-line arguments.

9. Java Programming Constructs

9.1 Variables

Definition: A variable is a named memory location used to store data of a specific type.
Types of Variables in Java:
  • Local Variables – Declared inside methods, blocks, or constructors. Accessible only within that scope.
  • Instance Variables – Declared inside class but outside methods. Each object has its own copy.
  • Static (Class) Variables – Declared with keyword static. Shared by all objects of the class.

9.2 Primitive Data Types

Definition: Primitive data types are the basic types used to store single values in Java.
Data Type Size Range / Description Example
byte 1 byte -128 to 127 byte age = 25;
short 2 bytes -32,768 to 32,767 short num = 1000;
int 4 bytes -231 to 231-1 int count = 100;
long 8 bytes -263 to 263-1 long population = 1000000L;
float 4 bytes Single precision decimal float pi = 3.14f;
double 8 bytes Double precision decimal double price = 99.99;
char 2 bytes Unicode character (0 to 65535) char grade = 'A';
boolean 1 bit true or false boolean flag = true;

9.3 Identifier

Definition: An identifier is a name given to variables, methods, classes, packages, etc.
Rules for Identifiers:
  • Can contain letters (a-z, A-Z), digits (0-9), underscore (_), and dollar sign ($)
  • Cannot start with a digit
  • Cannot be a Java reserved keyword
  • Case-sensitive – 'age' and 'Age' are different
  • No spaces allowed

9.4 Literals

Definition: A literal is a fixed value written directly in the program.
  • Integer literals: 10, -5, 0, 100
  • Floating-point literals: 3.14, -2.5, 0.0
  • Character literals: 'A', 'a', '1', '*' (single character in single quotes)
  • String literals: "Java", "Hello World" (in double quotes)
  • Boolean literals: true, false

9.5 Operators in Java

Definition: Operators are special symbols used to perform operations on variables and values.
Types of Operators:
  • Arithmetic Operators: +, -, *, /, % (modulus)
  • Relational Operators: ==, !=, >, <, >=, <= (return boolean)
  • Logical Operators: && (AND), || (OR), ! (NOT)
  • Assignment Operators: =, +=, -=, *=, /=, %=
  • Increment/Decrement: ++ (increment), -- (decrement)
  • Bitwise Operators: &, |, ^, ~, <<, >>, >>>
  • Ternary Operator: condition ? value1 : value2
// Arithmetic Operators int a = 10, b = 3; int sum = a + b; // 13 int diff = a - b; // 7 int product = a * b; // 30 int quotient = a / b; // 3 int remainder = a % b; // 1 // Logical Operators boolean result = (a > b) && (b > 0); // true // Ternary Operator String status = (a > b) ? "a is greater" : "b is greater";

9.6 Expressions

Definition: An expression is a combination of variables, operators, and values that is evaluated to produce a result.
Examples:
  • a + b * c (arithmetic expression)
  • (x > 5) && (y < 10) (logical expression)
  • count++ (post-increment expression)

9.7 Operator Precedence and Associativity

Precedence (High → Low) Operator Associativity
1 (Highest) Parentheses () Left to Right
2 Unary: ++ -- + - ! Right to Left
3 Multiplicative: * / % Left to Right
4 Additive: + - Left to Right
5 Relational: < > <= >= Left to Right
6 Equality: == != Left to Right
7 Logical AND: && Left to Right
8 Logical OR: || Left to Right
9 (Lowest) Assignment: = += -= *= /= Right to Left

9.8 Primitive Type Conversion and Casting

Widening Conversion (Automatic):
Smaller type → Larger type (automatic, no loss of information)
  • byte → short → int → long → float → double
  • Example: int value = 100; double d = value; // Automatic
Narrowing Conversion (Explicit Casting):
Larger type → Smaller type (requires explicit cast, possible loss of information)
  • Syntax: (targetType) value
  • Example: double d = 9.78; int i = (int) d; // Results in 9
// Type Conversion Example public class TypeConversion { public static void main(String[] args) { // Widening (Automatic) int intValue = 100; double doubleValue = intValue; System.out.println("Widening: " + doubleValue); // 100.0 // Narrowing (Explicit) double d = 9.78; int i = (int) d; System.out.println("Narrowing: " + i); // 9 (decimal part lost) // String to int (requires parsing) String str = "123"; int num = Integer.parseInt(str); System.out.println("String to int: " + num); // 123 } }
Widening: 100.0 Narrowing: 9 String to int: 123

9.9 Flow of Control

Definition: Flow of control determines the order in which statements are executed in a program.
Types of Control Structures:
A) Selection Statements (Conditional):
  • if – Executes block if condition is true
  • if-else – Executes one of two blocks based on condition
  • if-else-if ladder – Multiple conditions
  • switch – Selects from multiple options
// if statement if (age >= 18) { System.out.println("You are an adult"); } // if-else statement if (age >= 18) { System.out.println("Adult"); } else { System.out.println("Minor"); } // if-else-if ladder if (marks >= 90) { grade = 'A'; } else if (marks >= 80) { grade = 'B'; } else if (marks >= 70) { grade = 'C'; } else { grade = 'F'; } // switch statement switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Invalid day"); }
B) Iteration Statements (Loops):
  • for – When number of iterations is known
  • while – When condition is checked before execution
  • do-while – When condition is checked after first execution
  • enhanced for (for-each) – For iterating over arrays/collections
// for loop for (int i = 1; i <= 10; i++) { System.out.println(i); } // while loop int count = 1; while (count <= 10) { System.out.println(count); count++; } // do-while loop int num = 1; do { System.out.println(num); num++; } while (num <= 10); // enhanced for loop (for-each) int[] arr = {10, 20, 30, 40, 50}; for (int element : arr) { System.out.println(element); }
C) Jump Statements:
  • break – Exits loop or switch
  • continue – Skips current iteration
  • return – Exits method and returns value

10. Complete Example Program for Unit I

// Program: Calculate Grade class GradeCalculator { public static void main(String[] args) { int marks = 85; char grade; // Flow of control using if-else-if if (marks >= 90) { grade = 'A'; } else if (marks >= 80) { grade = 'B'; } else if (marks >= 70) { grade = 'C'; } else if (marks >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Marks: " + marks); System.out.println("Grade: " + grade); } }
Marks: 85 Grade: B

📝 Unit I – Summary

  • OOP is based on objects containing state and behavior.
  • Four main principles: Encapsulation, Inheritance, Polymorphism, Abstraction
  • Java is platform-independent due to JVM and bytecode.
  • Java features: Simple, OOP, Secure, Robust, Multithreaded, Portable.
  • 8 primitive data types: byte, short, int, long, float, double, char, boolean.
  • Operators: Arithmetic, Relational, Logical, Assignment, Increment/Decrement.
  • Flow of control: if-else, switch, for, while, do-while loops.

⭐ Important Exam Questions

  • (8 marks) Explain the four principles of OOP with real-world examples.
  • (4 marks) Difference between Procedural Language and OOP.
  • (4 marks) Explain JVM and its working. Why is Java platform-independent?
  • (4 marks) Write a program to calculate simple interest using variables and operators.
  • (2 marks) What are primitive data types? List all 8 types with sizes.
  • (4 marks) Explain operator precedence and associativity with examples.
  • (4 marks) Explain type casting with examples (widening and narrowing).
  • (6 marks) Write a program using if-else-if and loops to display multiplication table.

Unit II – Classes and Objects

📌 Total Hours: 07

📋 Syllabus Outline

  • Classes – Definition and syntax
  • Objects – Creation and usage
  • Methods – Calling and declaring
  • Constructors – Default and parameterized
  • Cleaning up Unused Objects – Garbage collection
  • Class Variables and Methods – Static keyword
  • this keyword – Current object reference
  • Arrays – 1D and usage
  • Command Line Arguments – Passing arguments from terminal

1. Classes

Definition: A class is a blueprint or template for creating objects. It defines properties (data members) and behaviors (methods) that objects will have.

Class Syntax:

public class ClassName { // 1. Data members (instance variables) private dataType variable1; private dataType variable2; // 2. Methods (behaviors) public void methodName() { // method body } public returnType methodName2(parameters) { // method body return value; } }

Example – Student Class:

public class Student { // Data members private String name; private int rollNo; private float marks; // Method to set values public void setDetails(String n, int roll, float m) { name = n; rollNo = roll; marks = m; } // Method to display values public void display() { System.out.println("Name: " + name); System.out.println("Roll No: " + rollNo); System.out.println("Marks: " + marks); } }

2. Objects

Definition: An object is an instance of a class. It is a real-world entity having specific values for the properties defined in the class.

Creating Objects:

Syntax: ClassName objectName = new ClassName();
  • new keyword allocates memory for the object.
  • Constructor initializes the object.
// Creating objects of Student class Student s1 = new Student(); Student s2 = new Student(); Student s3 = new Student(); // Each object is independent with its own memory

Accessing Object Members:

Use the dot (.) operator to access members of an object.
// Accessing object members s1.setDetails("John", 101, 85.5f); s1.display(); s2.setDetails("Sarah", 102, 92.0f); s2.display();

3. Methods

Definition: A method is a block of code that performs a specific task. It defines the behavior of objects.

Method Syntax:

accessModifier returnType methodName(parameterList) { // method body // statements return value; // if return type is not void }

Types of Methods:

  • void methods – Do not return any value
  • Parameterized methods – Accept parameters
  • Methods with return type – Return a value of specific type
// void method (no return) public void greet() { System.out.println("Hello!"); } // Method with parameters public void add(int a, int b) { int sum = a + b; System.out.println("Sum: " + sum); } // Method with return type public int multiply(int a, int b) { return a * b; } // Calling methods greet(); add(10, 20); int result = multiply(5, 6);

4. Constructors

Definition: A constructor is a special method used to initialize objects when they are created. It has the same name as the class and no return type.

Types of Constructors:

A) Default Constructor:
Definition: Has no parameters. Automatically provided by Java if no constructor is explicitly defined. Initializes variables with default values (0, null, false).
B) Parameterized Constructor:
Definition: Takes parameters to initialize object with specific values.
public class Student { private String name; private int rollNo; private float marks; // Default Constructor public Student() { name = "Unknown"; rollNo = 0; marks = 0.0f; System.out.println("Default Constructor Called"); } // Parameterized Constructor public Student(String n, int roll, float m) { name = n; rollNo = roll; marks = m; System.out.println("Parameterized Constructor Called"); } public void display() { System.out.println("Name: " + name); System.out.println("Roll: " + rollNo); System.out.println("Marks: " + marks); } } // Using constructors Student s1 = new Student(); // Calls default constructor s1.display(); Student s2 = new Student("Raj", 102, 90.5f); // Calls parameterized s2.display();
Default Constructor Called Name: Unknown Roll: 0 Marks: 0.0 Parameterized Constructor Called Name: Raj Roll: 102 Marks: 90.5

5. Cleaning up Unused Objects

Definition: Java has automatic garbage collection mechanism that removes objects from memory when they are no longer needed.
Key Points:
  • Objects with no reference are eligible for garbage collection.
  • Programmer does not explicitly free memory (unlike C/C++).
  • JVM automatically calls the garbage collector periodically.
  • Finalizer methods can be used for cleanup (not recommended).
Student s = new Student("John", 101, 85); s.display(); s = null; // Object is now eligible for garbage collection // OR Student s = new Student("John", 101, 85); s = new Student("Jane", 102, 90); // Previous object is garbage collected

6. Class Variables and Methods (Static)

Definition: Static members are declared with the static keyword and are shared by all objects of the class.

Class Variables (Static Variables):

  • Declared with static keyword inside class but outside methods.
  • Shared by all objects of the class.
  • Memory allocated once when class is loaded.
  • Initialized with default values (0, null, false).

Static Methods:

  • Declared with static keyword.
  • Can be called using class name without creating object.
  • Cannot directly access non-static members (instance variables).
  • Can only access static members.
public class Counter { // Static variable static int count = 0; // Constructor public Counter() { count++; // Increment count when new object is created } // Static method public static void display() { System.out.println("Total objects created: " + count); } } // Using class members Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); Counter.display(); // Call static method using class name // OR c1.display(); // Can also call using object reference
Total objects created: 3

7. this Keyword

Definition: this is a reference variable that refers to the current object. It is used to distinguish between instance variables and parameters with the same name.

Uses of this Keyword:

  • To refer to current class instance variable when parameter has same name.
  • To call another constructor of the same class (constructor chaining).
  • To pass current object as a parameter.
public class Student { String name; int rollNo; // Constructor using this public Student(String name, int rollNo) { this.name = name; // this.name = instance variable this.rollNo = rollNo; // name, rollNo = parameters } public void display() { System.out.println("Name: " + this.name); System.out.println("Roll: " + this.rollNo); } } // Usage Student s = new Student("Priya", 105); s.display();
Name: Priya Roll: 105

8. Arrays in Java

Definition: An array is a collection of similar type elements stored in contiguous memory locations.

Array Declaration and Creation:

Syntax: dataType[] arrayName = new dataType[size];
  • dataType: Type of elements in array
  • arrayName: Name of the array
  • size: Number of elements the array can hold

Array Initialization:

// Method 1: Declaration and creation int[] marks = new int[5]; // Array of size 5 String[] names = new String[10]; // Method 2: Declaration with initialization int[] numbers = {10, 20, 30, 40, 50}; String[] fruits = {"Apple", "Mango", "Banana", "Orange"}; // Method 3: Accessing array elements marks[0] = 85; marks[1] = 90; marks[2] = 78; System.out.println("First mark: " + marks[0]); // 85 System.out.println("Array length: " + marks.length); // 5

Array with Loops:

// Array Example: Calculate Average Marks public class ArrayDemo { public static void main(String[] args) { int[] marks = {85, 90, 78, 92, 88}; int sum = 0; // Print all marks System.out.println("Marks:"); for (int i = 0; i < marks.length; i++) { System.out.println("Marks[" + i + "] = " + marks[i]); sum += marks[i]; } // Calculate average float average = sum / (float) marks.length; System.out.println("\nAverage: " + average); // Enhanced for loop (for-each) System.out.println("\nUsing for-each:"); for (int mark : marks) { System.out.println(mark); } } }
Marks: Marks[0] = 85 Marks[1] = 90 Marks[2] = 78 Marks[3] = 92 Marks[4] = 88 Average: 86.6 Using for-each: 85 90 78 92 88

9. Command Line Arguments

Definition: Command line arguments are values passed to a Java program from the terminal/command prompt when the program is executed.

How to Pass Command Line Arguments:

Syntax: java ClassName argument1 argument2 argument3 ...
  • Arguments are passed as Strings in the String[] args array in main method.
  • First argument is stored in args[0], second in args[1], and so on.
public class CommandLineArgs { public static void main(String[] args) { // Check if arguments are provided if (args.length == 0) { System.out.println("No arguments provided"); return; } // Display command line arguments System.out.println("Number of arguments: " + args.length); System.out.println("\nArguments provided:"); for (int i = 0; i < args.length; i++) { System.out.println("args[" + i + "] = " + args[i]); } // Example: Convert string argument to integer if (args.length > 0) { int num = Integer.parseInt(args[0]); System.out.println("\nFirst argument as integer: " + num); } } }

Execution Examples:

Example 1: java CommandLineArgs
No arguments provided
Example 2: java CommandLineArgs Hello Java World
Number of arguments: 3 Arguments provided: args[0] = Hello args[1] = Java args[2] = World First argument as integer: Invalid (string cannot be parsed)
Example 3: java CommandLineArgs 42 100 200
Number of arguments: 3 Arguments provided: args[0] = 42 args[1] = 100 args[2] = 200 First argument as integer: 42

📝 Unit II – Summary

  • Class is a blueprint, object is an instance of a class.
  • Objects are created using new keyword and constructors.
  • Constructors initialize objects. Types: Default and Parameterized.
  • Static variables are shared by all objects of a class.
  • Static methods can be called without creating objects.
  • this keyword refers to the current object.
  • Arrays store multiple elements of same type.
  • Command line arguments are passed through terminal in String[] args.
  • Java has automatic garbage collection for memory management.

⭐ Important Exam Questions

  • (4 marks) Define class and object with example. What is the difference?
  • (6 marks) Explain constructors. Write a program with default and parameterized constructor.
  • (4 marks) What is this keyword? Explain its uses with example.
  • (4 marks) Explain static variables and static methods with example.
  • (4 marks) Write a program demonstrating array usage and array operations.
  • (2 marks) What are command line arguments? How do you pass them?
  • (6 marks) Write a complete program (Student class) with constructor, methods, and objects.
  • (4 marks) What is garbage collection? How does Java manage memory automatically?

Unit III – Inheritance, Interfaces and Packages

📌 Total Hours: 07

📋 Syllabus Outline

  • Inheritance: Inheritance vs. Aggregation, Method Overriding, super keyword, final keyword, Abstract class
  • Interfaces: Defining interfaces, Implementing interfaces, Accessing interface variables, Extending interfaces
  • Packages: Packages, java.lang package

1. Inheritance

Definition: Inheritance is a mechanism where one class acquires properties and behaviors of another class, promoting code reusability.

Terminology:

  • Parent Class / Super Class / Base Class – The class whose members are inherited
  • Child Class / Sub Class / Derived Class – The class that inherits members from parent

Syntax:

class Parent { // Parent class members } class Child extends Parent { // Inherits all non-private members from Parent // Can add its own members }

Example Program:

// Parent Class class Animal { String name; public void eat() { System.out.println("Animal is eating"); } public void sleep() { System.out.println("Animal is sleeping"); } } // Child Class class Dog extends Animal { public void bark() { System.out.println("Dog is barking"); } } // Using Inheritance public class InheritanceDemo { public static void main(String[] args) { Dog dog = new Dog(); dog.name = "Tommy"; // Using inherited methods dog.eat(); // From Animal class dog.sleep(); // From Animal class // Using own method dog.bark(); // From Dog class } }
Animal is eating Animal is sleeping Dog is barking

1.1 Inheritance vs. Aggregation

Inheritance (IS-A relationship):

A class extends another class using extends keyword. Child class becomes a specialized version of parent class.
  • Example: Dog IS-A Animal (Dog is a type of Animal)
  • Uses extends keyword

Aggregation (HAS-A relationship):

One class contains reference of another class as a member variable. Does not use extends.
  • Example: Car HAS-A Engine (Car contains Engine object)
  • Uses object composition
// Aggregation Example class Engine { public void start() { System.out.println("Engine started"); } } class Car { Engine engine; // Car HAS-A Engine public Car() { engine = new Engine(); } public void drive() { engine.start(); System.out.println("Car is driving"); } } // Usage Car car = new Car(); car.drive();

Comparison Table:

Feature Inheritance (IS-A) Aggregation (HAS-A)
Keyword extends Object as member variable
Relationship Child IS parent (specialization) Class HAS another class (composition)
Access Direct access to parent members Access through object reference
Example Dog extends Animal Car has Engine

1.2 Method Overriding

Definition: Method Overriding occurs when a child class provides a specific implementation of a method that is already defined in the parent class. The method signature must be same.

Rules for Method Overriding:

  • Method name must be same
  • Parameter list must be identical
  • Return type must be same or covariant
  • Access modifier cannot be more restrictive
  • Should use @Override annotation (optional but recommended)
// Method Overriding Example class Bank { public int getRateOfInterest() { return 0; } } class SBI extends Bank { @Override public int getRateOfInterest() { return 8; // SBI provides 8% interest } } class HDFC extends Bank { @Override public int getRateOfInterest() { return 7; // HDFC provides 7% interest } } // Using Method Overriding public class BankDemo { public static void main(String[] args) { Bank bank = new SBI(); System.out.println("SBI Rate: " + bank.getRateOfInterest()); // 8 bank = new HDFC(); System.out.println("HDFC Rate: " + bank.getRateOfInterest()); // 7 } }
SBI Rate: 8 HDFC Rate: 7

1.3 super Keyword

Definition: super is a reference variable that refers to the immediate parent class object. Used to access parent class members from child class.

Uses of super:

  • To call parent class constructor
  • To call overridden method of parent class
  • To access parent class variable (when both parent and child have same name)
// super Example class Vehicle { String color = "White"; public void display() { System.out.println("This is Vehicle"); } } class Car extends Vehicle { String color = "Red"; public void display() { System.out.println("This is Car"); System.out.println("Car color: " + color); System.out.println("Vehicle color: " + super.color); } public void show() { super.display(); // Call parent's display method display(); // Call child's display method } } // Usage Car car = new Car(); car.show();
This is Vehicle This is Car Car color: Red Vehicle color: White

1.4 final Keyword

Definition: final keyword is used to restrict modification of variables, methods, and classes.

Uses of final:

1) Final Variable:
Cannot be changed once assigned. Acts like a constant.
final double PI = 3.14159; // PI = 3.14; // Error: Cannot assign value to final variable
2) Final Method:
Cannot be overridden in child class.
class Parent { final public void display() { System.out.println("Parent display"); } } class Child extends Parent { // public void display() { // Error: Cannot override final method // System.out.println("Child display"); // } }
3) Final Class:
Cannot be extended. No class can inherit from it.
final class ImmutableClass { // Cannot be extended } // class ChildClass extends ImmutableClass { // Error: Cannot extend final class // }

1.5 Abstract Class

Definition: An abstract class is a class declared with abstract keyword. It cannot be instantiated (cannot create objects). May contain abstract methods (without body) and concrete methods (with body).

Key Points:

  • Cannot create objects of abstract class directly.
  • Can have abstract methods (no body) and regular methods (with body).
  • Child class must implement all abstract methods or itself be abstract.
  • Can have constructors called when child objects are created.
// Abstract Class Example abstract class Shape { // Abstract method (no body) abstract void draw(); // Concrete method (with body) public void display() { System.out.println("This is a shape"); } } // Concrete class implementing abstract methods class Circle extends Shape { @Override void draw() { System.out.println("Drawing Circle"); } } class Rectangle extends Shape { @Override void draw() { System.out.println("Drawing Rectangle"); } } // Usage public class ShapeDemo { public static void main(String[] args) { // Shape s = new Shape(); // Error: Cannot instantiate abstract class Shape s = new Circle(); s.draw(); // Drawing Circle s.display(); // This is a shape s = new Rectangle(); s.draw(); // Drawing Rectangle s.display(); // This is a shape } }
Drawing Circle This is a shape Drawing Rectangle This is a shape

2. Interfaces

Definition: An interface is a blueprint of a class that contains only abstract methods and constants. It is used to achieve 100% abstraction and enable multiple inheritance. All methods are public and abstract by default. All variables are public static final (constants).

Key Differences from Classes:

Class Interface
Declared with class Declared with interface
Can have concrete and abstract methods Only abstract methods (until Java 8)
Can have instance variables Only constants (public static final)
Can be extended by one class only Can be implemented by multiple classes
Objects can be created Cannot instantiate directly

2.1 Defining Interfaces

public interface InterfaceName { // Constants (public static final) int CONSTANT_VALUE = 100; String NAME = "Interface"; // Abstract methods (public abstract) void method1(); void method2(int param); int method3(); }

2.2 Implementing Interfaces

public interface Drawable { void draw(); void erase(); } // Implementing interface public class Circle implements Drawable { @Override public void draw() { System.out.println("Drawing Circle"); } @Override public void erase() { System.out.println("Erasing Circle"); } } public class Rectangle implements Drawable { @Override public void draw() { System.out.println("Drawing Rectangle"); } @Override public void erase() { System.out.println("Erasing Rectangle"); } } // Usage public class InterfaceDemo { public static void main(String[] args) { Drawable d = new Circle(); d.draw(); d.erase(); d = new Rectangle(); d.draw(); d.erase(); } }
Drawing Circle Erasing Circle Drawing Rectangle Erasing Rectangle

2.3 Accessing Interface Variables

Interface constants can be accessed using interface name without creating objects.
public interface Constants { int MAX_USERS = 100; int MIN_USERS = 0; String APP_NAME = "MyApp"; } public class MyClass implements Constants { public static void main(String[] args) { // Access interface constants System.out.println("Max Users: " + MAX_USERS); System.out.println("Min Users: " + MIN_USERS); System.out.println("App Name: " + APP_NAME); // OR using interface name System.out.println("Max: " + Constants.MAX_USERS); } }

2.4 Extending Interfaces

One interface can extend another interface using extends keyword. A child interface inherits all methods from parent interface.
interface Animal { void eat(); void sleep(); } interface Pet extends Animal { void play(); } class Dog implements Pet { @Override public void eat() { System.out.println("Dog is eating"); } @Override public void sleep() { System.out.println("Dog is sleeping"); } @Override public void play() { System.out.println("Dog is playing"); } } // Usage Dog dog = new Dog(); dog.eat(); dog.sleep(); dog.play();

3. Packages

Definition: A package is a group of related classes and interfaces organized into directories. It provides namespace management and access protection.

Types of Packages:

  • Built-in Packages – Provided by Java (java.lang, java.util, java.io, java.awt, etc.)
  • User-defined Packages – Created by programmers

Creating Package:

Syntax: package packageName;
  • Must be the first statement in Java file (before import and class declaration)
  • Package name should match directory structure

Importing Package:

Syntax:
  • import packageName.*; (imports all classes from package)
  • import packageName.ClassName; (imports specific class)
// File: mypack/MyClass.java package mypack; public class MyClass { public void display() { System.out.println("Hello from mypack"); } } // File: myapp/Main.java package myapp; import mypack.MyClass; // Import specific class // OR // import mypack.*; // Import all classes from mypack public class Main { public static void main(String[] args) { MyClass obj = new MyClass(); obj.display(); } }

3.1 java.lang Package

Definition: java.lang package is the core Java package containing fundamental classes. It is automatically imported without explicit import statement.

Important Classes in java.lang:

  • Object – Super class of all Java classes
  • String – String manipulation
  • StringBuffer – Mutable string
  • StringBuilder – Mutable string (faster)
  • Math – Mathematical functions
  • Number – Numeric wrapper classes (Integer, Double, Float, etc.)
  • System – System-related operations (System.out.println, etc.)
  • Thread – Multithreading support
  • Exception – Exception handling
// Using java.lang classes (no explicit import needed) public class JavaLangDemo { public static void main(String[] args) { // String class String str = "Hello Java"; System.out.println("String: " + str); System.out.println("Length: " + str.length()); // Math class System.out.println("Max: " + Math.max(10, 20)); System.out.println("Sqrt: " + Math.sqrt(16)); System.out.println("PI: " + Math.PI); // Integer wrapper class Integer num = Integer.parseInt("42"); System.out.println("Integer: " + num); // System class System.out.println("Current time: " + System.currentTimeMillis()); } }

📝 Unit III – Summary

  • Inheritance (IS-A) promotes code reusability. Uses extends keyword.
  • Aggregation (HAS-A) uses object composition without extends.
  • Method Overriding allows child class to provide specific implementation.
  • super keyword refers to parent class object and its members.
  • final keyword restricts variables, methods, and classes from modification/extension.
  • Abstract class cannot be instantiated but can have abstract and concrete methods.
  • Interface provides 100% abstraction with abstract methods and constants.
  • Package is a group of related classes providing namespace management.
  • java.lang is the core package automatically imported in all Java programs.

⭐ Important Exam Questions

  • (6 marks) Explain inheritance with example. What is IS-A relationship?
  • (4 marks) Difference between inheritance and aggregation with examples.
  • (6 marks) What is method overriding? Explain rules with example.
  • (4 marks) Explain super keyword and its uses.
  • (4 marks) What is abstract class? Write a program with abstract methods.
  • (6 marks) Define interface. Explain how to define and implement interfaces.
  • (4 marks) What are packages? Difference between built-in and user-defined packages.
  • (2 marks) List important classes in java.lang package.

Unit IV – Exception Handling and Input/Output

📌 Total Hours: 07

📋 Syllabus Outline

  • Exception: Introduction, Exception Handling Techniques, User-defined Exception, Exception Encapsulation and Enrichment
  • Input/Output: The java.io.File Class, Reading and Writing data, Randomly Accessing a file, Reading and Writing Files using I/O Package

1. Exception Handling

1.1 Introduction to Exception

Definition: An exception is an abnormal condition or runtime error that occurs during program execution, disrupting the normal flow of the program.

Types of Errors:

  • Compile-time errors – Syntax errors detected by compiler
  • Runtime errors – Occur during program execution (exceptions)
  • Logic errors – Program runs but produces incorrect output

Common Exceptions:

  • ArithmeticException – Division by zero
  • NullPointerException – Accessing null object
  • ArrayIndexOutOfBoundsException – Invalid array index
  • StringIndexOutOfBoundsException – Invalid string index
  • NumberFormatException – Invalid number format
  • FileNotFoundException – File not found

1.2 Exception Handling Techniques

A) Try-Catch Block:
Used to catch and handle exceptions that may occur in the try block.
try { // Code that may throw exception int result = 10 / 0; // ArithmeticException System.out.println("Result: " + result); } catch (ArithmeticException e) { // Handle exception System.out.println("Error: Cannot divide by zero"); System.out.println("Exception: " + e.getMessage()); }
B) Try-Catch-Finally Block:
finally block is always executed whether exception occurs or not. Used for cleanup operations.
try { int arr[] = {1, 2, 3}; System.out.println("Element: " + arr[10]); // ArrayIndexOutOfBoundsException } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: Invalid array index"); } finally { System.out.println("Finally block always executes"); }
C) Multiple Catch Blocks:
Handle different types of exceptions separately.
try { // Some risky code String str = "123abc"; int num = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println("Error: Invalid number format"); } catch (Exception e) { System.out.println("General exception: " + e.getMessage()); }
D) Try-with-resources (Java 7+):
Automatically closes resources (files, streams) without explicit close().
try (FileReader fr = new FileReader("file.txt")) { int ch; while ((ch = fr.read()) != -1) { System.out.print((char) ch); } } catch (IOException e) { System.out.println("Error reading file: " + e.getMessage()); } // FileReader automatically closed here
E) Throw Keyword:
throw is used to manually throw an exception.
public void checkAge(int age) { if (age < 18) { throw new IllegalArgumentException("Age must be 18 or above"); } System.out.println("Age is valid: " + age); } // Usage try { checkAge(15); } catch (IllegalArgumentException e) { System.out.println("Exception: " + e.getMessage()); }
F) Throws Keyword:
throws is used in method signature to declare that a method may throw an exception.
public void readFile(String filename) throws IOException { FileReader fr = new FileReader(filename); int ch; while ((ch = fr.read()) != -1) { System.out.print((char) ch); } fr.close(); } // Caller must handle the exception try { readFile("data.txt"); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); }

1.3 User-Defined Exception

Definition: A user-defined exception is a custom exception created by extending the Exception class or its subclasses.
// Create custom exception class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } } // Using custom exception public class Student { private int age; public void setAge(int age) throws InvalidAgeException { if (age < 5 || age > 50) { throw new InvalidAgeException("Age must be between 5 and 50"); } this.age = age; } } // Usage public class ExceptionDemo { public static void main(String[] args) { Student s = new Student(); try { s.setAge(25); System.out.println("Age set successfully"); s.setAge(100); // Will throw InvalidAgeException } catch (InvalidAgeException e) { System.out.println("Exception: " + e.getMessage()); } } }

1.4 Exception Encapsulation and Enrichment

Exception Encapsulation:

Wrapping a low-level exception into a high-level custom exception, hiding implementation details.

Exception Enrichment:

Adding additional context information to the exception before throwing it.
class DatabaseException extends Exception { private String errorCode; private String errorMessage; public DatabaseException(String errorCode, String errorMessage) { super(errorMessage); this.errorCode = errorCode; this.errorMessage = errorMessage; } public String getErrorCode() { return errorCode; } } // Usage public void fetchData(String id) throws DatabaseException { try { // Database operation if (id == null || id.isEmpty()) { throw new DatabaseException("DB001", "Invalid ID provided"); } } catch (Exception e) { // Enriching exception with context throw new DatabaseException("DB002", "Failed to fetch data: " + e.getMessage()); } }

2. Input/Output (I/O)

2.1 The java.io.File Class

Definition: File class represents a file or directory path in the file system. It provides methods to create, delete, and access file properties.

Common File Methods:

  • exists() – Check if file exists
  • isFile() – Check if it is a file
  • isDirectory() – Check if it is a directory
  • getName() – Get file name
  • getAbsolutePath() – Get absolute path
  • length() – Get file size in bytes
  • delete() – Delete file
  • createNewFile() – Create new file
import java.io.File; import java.io.IOException; public class FileDemo { public static void main(String[] args) { File file = new File("myfile.txt"); // Check if file exists if (file.exists()) { System.out.println("File exists"); System.out.println("File name: " + file.getName()); System.out.println("File size: " + file.length() + " bytes"); System.out.println("Is file: " + file.isFile()); System.out.println("Absolute path: " + file.getAbsolutePath()); } else { System.out.println("File does not exist"); // Create new file try { if (file.createNewFile()) { System.out.println("File created successfully"); } } catch (IOException e) { System.out.println("Error creating file: " + e.getMessage()); } } } }

2.2 Reading and Writing Data

A) FileWriter – Writing Text to File:

import java.io.FileWriter; import java.io.IOException; public class WriteToFile { public static void main(String[] args) { String content = "Hello Java!\nThis is a file.\nLearning I/O."; try (FileWriter fw = new FileWriter("output.txt")) { fw.write(content); System.out.println("Content written to file successfully"); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } }

B) FileReader – Reading Text from File:

import java.io.FileReader; import java.io.IOException; public class ReadFromFile { public static void main(String[] args) { try (FileReader fr = new FileReader("output.txt")) { int ch; System.out.println("File content:"); while ((ch = fr.read()) != -1) { System.out.print((char) ch); } } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } }

C) BufferedWriter – Writing with Buffer:

import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriteDemo { public static void main(String[] args) { try (BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) { bw.write("Line 1"); bw.newLine(); bw.write("Line 2"); bw.newLine(); bw.write("Line 3"); System.out.println("Data written with buffer"); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } }

D) BufferedReader – Reading with Buffer:

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReadDemo { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) { String line; System.out.println("File content:"); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } }

2.3 Randomly Accessing a File

Definition: RandomAccessFile allows reading and writing at any position in a file without reading the entire file.

Common Methods:

  • seek(long pos) – Move to specific position
  • read() – Read byte at current position
  • write(int b) – Write byte at current position
  • getFilePointer() – Get current position
import java.io.RandomAccessFile; import java.io.IOException; public class RandomAccessDemo { public static void main(String[] args) { try { // Create file with initial content RandomAccessFile raf = new RandomAccessFile("random.txt", "rw"); // Write initial data raf.writeBytes("Hello World"); // Move to position 6 and read raf.seek(6); System.out.println("Character at position 6: " + (char) raf.read()); // Move to position 6 and write raf.seek(6); raf.writeBytes("Java"); // Move to beginning and read entire content raf.seek(0); System.out.println("\nFile content after modification:"); int ch; while ((ch = raf.read()) != -1) { System.out.print((char) ch); } raf.close(); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } }

2.4 Reading and Writing Objects (Serialization)

Serialization: Convert object to byte stream (writing object to file). Deserialization: Convert byte stream back to object (reading object from file).
import java.io.*; // Step 1: Create serializable class class Student implements Serializable { private static final long serialVersionUID = 1L; String name; int rollNo; float marks; public Student(String name, int rollNo, float marks) { this.name = name; this.rollNo = rollNo; this.marks = marks; } } // Step 2: Write object to file class WriteObject { public static void main(String[] args) { Student s = new Student("John", 101, 85.5f); try (ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("student.dat"))) { oos.writeObject(s); System.out.println("Object written to file"); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } } // Step 3: Read object from file class ReadObject { public static void main(String[] args) { try (ObjectInputStream ois = new ObjectInputStream( new FileInputStream("student.dat"))) { Student s = (Student) ois.readObject(); System.out.println("Name: " + s.name); System.out.println("Roll: " + s.rollNo); System.out.println("Marks: " + s.marks); } catch (IOException | ClassNotFoundException e) { System.out.println("Error: " + e.getMessage()); } } }

📝 Unit IV – Summary

  • Exception is an abnormal condition during program execution.
  • try-catch blocks handle exceptions gracefully.
  • finally block always executes for cleanup operations.
  • throws declares exception in method signature.
  • throw manually throws an exception.
  • User-defined exceptions extend Exception or its subclasses.
  • File class represents files and directories.
  • FileReader/FileWriter read/write character data.
  • BufferedReader/BufferedWriter provide efficient buffered I/O.
  • RandomAccessFile allows reading/writing at any file position.
  • Serialization converts objects to byte streams for file storage.

⭐ Important Exam Questions

  • (4 marks) What are exceptions? Explain exception handling techniques.
  • (6 marks) Write a program with try-catch-finally block handling multiple exceptions.
  • (4 marks) Create a user-defined exception and demonstrate its usage.
  • (4 marks) Explain File class methods with example.
  • (6 marks) Write a program to read from and write to a file.
  • (4 marks) What is RandomAccessFile? Explain with example.
  • (4 marks) Explain serialization and deserialization with example.

Unit V – Applets

📌 Total Hours: 07

📋 Syllabus Outline

  • Introduction to Applets
  • Applet Class & Lifecycle
  • Common Display Methods: paint(), update(), repaint()
  • Applet Tags and Attributes
  • getDocumentBase() and getCodeBase()
  • Applet Context Interface
  • Graphics, Color, Font, Font Metrics

1. Introduction to Applets

Definition: An applet is a small Java program that runs within a web browser. It has restricted access to system resources for security.

Difference between Applet and Application:

Applet Application
Runs in web browser Runs standalone on computer
Extends Applet class Extends Object class or any class
No main() method Has main() method
Has life cycle methods No predefined life cycle
Limited system access Full system access
Embedded in HTML Runs independently

2. Applet Class

Definition: Applet class is the superclass for all applets. It extends Panel and provides lifecycle methods.
import java.applet.Applet; import java.awt.Graphics; // Syntax: class AppletName extends Applet public class SimpleApplet extends Applet { // Applet class members and methods }

3. Applet Structure and Lifecycle

Applet Lifecycle Methods:

1) init():
Called when applet is first loaded. Used for initialization.
2) start():
Called after init() and whenever applet becomes visible. Used to start animations or threads.
3) paint(Graphics g):
Called to draw graphics on applet. Called after start() and whenever applet needs to be redrawn.
4) stop():
Called when applet becomes invisible. Used to stop animations or threads.
5) destroy():
Called when applet is about to be unloaded. Used for cleanup.

Applet Lifecycle Diagram:

┌──────────────┐ │ Applet │ │ Loaded │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ init() │ Called once at startup └──────┬───────┘ │ ▼ ┌──────────────┐ │ start() │ Called when visible └──────┬───────┘ │ ▼ ┌──────────────┐ │ paint() │ Draw graphics └──────┬───────┘ │ ▼ (User navigates away or page is refreshed) ┌──────────────┐ │ stop() │ Called when hidden └──────┬───────┘ │ ▼ (Browser closes or applet unloaded) ┌──────────────┐ │ destroy() │ Cleanup └──────────────┘

4. Display Methods: paint(), update(), repaint()

paint(Graphics g):

Purpose: Draws graphics on the applet's drawing surface. When called: After start() and whenever applet needs redrawing.

update(Graphics g):

Purpose: Clears applet and calls paint(). Can be overridden for custom updates. When called: When repaint() is invoked.

repaint():

Purpose: Requests browser to call update(), which calls paint(). When called: Manually by programmer or when component needs redrawing.
import java.applet.Applet; import java.awt.*; public class GraphicsApplet extends Applet { public void init() { System.out.println("Applet initialized"); } public void start() { System.out.println("Applet started"); } public void paint(Graphics g) { // Draw rectangle g.drawRect(50, 50, 200, 100); // Draw string g.drawString("Hello Applet!", 100, 150); // Draw circle g.drawOval(100, 200, 100, 100); } public void stop() { System.out.println("Applet stopped"); } public void destroy() { System.out.println("Applet destroyed"); } }

5. Applet HTML Tags

Definition: Applets are embedded in HTML using <applet> tag or <object> tag (newer standard).

Applet Tag Syntax:

<applet code="ClassName.class" width="400" height="300"> <param name="paramName" value="paramValue"> Your browser does not support applets. </applet>

Important Attributes:

  • code – Name of compiled applet class file
  • width – Width of applet window in pixels
  • height – Height of applet window in pixels
  • codebase – Directory containing .class file
  • archive – JAR file containing applet classes
  • name – Unique identifier for applet

Example HTML:

<html> <head> <title>Applet Demo</title> </head> <body> <h1>Welcome to Applet</h1> <applet code="SimpleApplet.class" width="500" height="400"> <param name="color" value="red"> Your browser does not support Java applets. </applet> </body> </html>

6. getDocumentBase() and getCodeBase()

getDocumentBase():

Returns the URL of HTML document that contains the applet.

getCodeBase():

Returns the URL of directory where applet .class file is located.
public class URLApplet extends Applet { public void paint(Graphics g) { String docBase = getDocumentBase().toString(); String codeBase = getCodeBase().toString(); g.drawString("Document Base: " + docBase, 20, 50); g.drawString("Code Base: " + codeBase, 20, 80); } }

7. Applet Context Interface

Definition: AppletContext interface allows applet to communicate with browser and access other applets on the same page.

Common Methods:

  • getApplet(String name) – Get reference to another applet
  • getApplets() – Get enumeration of all applets
  • showDocument(URL url) – Display web page in browser
  • showStatus(String msg) – Display message in status bar
public class ContextApplet extends Applet { public void paint(Graphics g) { AppletContext context = getAppletContext(); // Show message in status bar context.showStatus("Applet is running..."); g.drawString("Click to navigate", 50, 50); } public boolean mouseDown(Event evt, int x, int y) { try { // Navigate to URL getAppletContext().showDocument( new URL("https://www.example.com") ); } catch (Exception e) { e.printStackTrace(); } return true; } }

8. Graphics Class and Drawing

Definition: Graphics class provides methods to draw shapes, text, and images on applet.

Common Graphics Methods:

  • drawLine(x1, y1, x2, y2) – Draw line
  • drawRect(x, y, width, height) – Draw rectangle
  • fillRect(x, y, width, height) – Draw filled rectangle
  • drawOval(x, y, width, height) – Draw oval/circle
  • fillOval(x, y, width, height) – Draw filled oval
  • drawPolygon(xPoints, yPoints, nPoints) – Draw polygon
  • drawString(text, x, y) – Draw text
  • drawImage(image, x, y, observer) – Draw image

9. Color Class

Color class represents colors using RGB values (Red, Green, Blue).

Predefined Colors:

  • Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.BLACK, Color.WHITE, etc.
public class ColorApplet extends Applet { public void paint(Graphics g) { // Set color and draw g.setColor(Color.RED); g.fillRect(50, 50, 100, 100); g.setColor(Color.BLUE); g.fillOval(200, 50, 100, 100); // Custom color (RGB) Color customColor = new Color(255, 165, 0); // Orange g.setColor(customColor); g.fillRect(50, 200, 100, 100); } }

10. Font and FontMetrics

Font Class:

Font class defines font properties: name, style, and size.
// Font constructor new Font(String name, int style, int size) // Font styles Font.PLAIN // No style Font.BOLD // Bold text Font.ITALIC // Italic text Font.BOLD | Font.ITALIC // Bold and Italic

FontMetrics Class:

FontMetrics provides information about font dimensions: ascent, descent, height, width of characters.
public class FontApplet extends Applet { public void paint(Graphics g) { // Create and set font Font font1 = new Font("Arial", Font.PLAIN, 20); g.setFont(font1); g.drawString("Plain Text", 50, 50); Font font2 = new Font("Arial", Font.BOLD, 24); g.setFont(font2); g.drawString("Bold Text", 50, 100); Font font3 = new Font("Arial", Font.ITALIC, 20); g.setFont(font3); g.drawString("Italic Text", 50, 150); // Get font metrics FontMetrics fm = g.getFontMetrics(font2); int ascent = fm.getAscent(); // Height above baseline int descent = fm.getDescent(); // Height below baseline int height = fm.getHeight(); // Total height g.drawString("Height: " + height, 50, 200); } }

📝 Unit V – Summary

  • Applet is a small Java program that runs in a web browser.
  • Applet Lifecycle: init() → start() → paint() → stop() → destroy()
  • paint() draws graphics, repaint() requests redrawing.
  • Applet tag embeds applets in HTML documents.
  • getDocumentBase() returns HTML document URL.
  • getCodeBase() returns applet class directory URL.
  • AppletContext allows communication with browser.
  • Graphics class provides drawing methods.
  • Color and Font control appearance.
  • FontMetrics provides font dimension information.

⭐ Important Exam Questions

  • (4 marks) What is an applet? Difference between applet and application.
  • (6 marks) Explain applet lifecycle with all methods and their purposes.
  • (4 marks) Write a simple applet that draws geometric shapes.
  • (4 marks) Explain paint(), update(), and repaint() methods.
  • (4 marks) What is applet HTML tag? Explain its attributes.
  • (2 marks) Explain getDocumentBase() and getCodeBase().
  • (4 marks) Write an applet using different fonts and colors.

Unit VI – Event Handling and Abstract Window Toolkit (AWT)

📌 Total Hours: 07

📋 Syllabus Outline

  • Event Handling: Event Delegation Model, java.awt.event Package, Event Sources, Event Listeners, Adapter Classes, Inner Classes
  • AWT Components: Button, Label, Checkbox, RadioButtons, ListBox, ChoiceBox, TextField, TextArea, Container, Layouts, Menu, Scrollbar

1. Introduction to Event Handling

Definition: Event handling is the mechanism by which a Java program responds to user interactions such as mouse clicks, keyboard presses, window closing, etc.

Types of Events:

  • Action events – Button click, pressing Enter in text field
  • Mouse events – Mouse click, mouse drag, mouse move
  • Keyboard events – Key press, key release
  • Window events – Window open, window close
  • Focus events – Component gains/loses focus

2. Event Delegation Model

Definition: Delegation event model is the mechanism where event source (component where event occurs) creates an event object and sends it to event listeners (objects that handle events).

Flow of Event Delegation:

User Action (Click Button) │ ▼ Event Source (Button) │ ▼ Creates Event Object Event Object (ActionEvent) │ ▼ Passes to registered listeners Event Listener (Interface) │ ▼ Calls event handler method Event Handler (actionPerformed) │ ▼ Response

3. java.awt.event Package

Package containing event classes and listener interfaces for handling events in Swing and AWT components.

Important Event Classes:

  • ActionEvent – Button clicks, menu selections
  • MouseEvent – Mouse operations
  • KeyEvent – Keyboard operations
  • WindowEvent – Window operations
  • ItemEvent – Checkbox, radio button, list selections
  • TextEvent – Text field/area changes

Important Listener Interfaces:

  • ActionListener – Listens for action events
  • MouseListener – Listens for mouse events
  • KeyListener – Listens for keyboard events
  • WindowListener – Listens for window events
  • ItemListener – Listens for item selections
  • TextListener – Listens for text changes

4. Event Sources and Event Listeners

Event Source:

Component where event occurs (Button, TextField, etc.). Has methods to register listeners.

Event Listener:

Interface with abstract methods that must be implemented to handle events.
import java.awt.*; import java.awt.event.*; // Simple Event Handling Example public class ButtonExample extends Frame implements ActionListener { Button btn; Label label; public ButtonExample() { setLayout(new FlowLayout()); // Create button (Event Source) btn = new Button("Click Me"); btn.addActionListener(this); // Register listener add(btn); // Create label to display message label = new Label("Click the button"); add(label); setSize(300, 200); setVisible(true); } // Implement ActionListener method (Event Handler) @Override public void actionPerformed(ActionEvent e) { label.setText("Button was clicked!"); System.out.println("Button action event occurred"); } public static void main(String[] args) { new ButtonExample(); } }

5. Adapter Classes

Definition: Adapter classes are abstract classes that provide default implementations of all methods in a listener interface. Programmer can override only necessary methods.

Advantages of Adapter Classes:

  • No need to implement all methods of an interface if only one or few are needed.
  • Reduces code clutter with unnecessary empty method implementations.

Common Adapter Classes:

  • MouseAdapter – Implements MouseListener
  • KeyAdapter – Implements KeyListener
  • WindowAdapter – Implements WindowListener
  • FocusAdapter – Implements FocusListener
import java.awt.*; import java.awt.event.*; public class MouseEventDemo extends Frame { public MouseEventDemo() { setLayout(new FlowLayout()); setSize(400, 300); setVisible(true); // Using MouseAdapter instead of implementing MouseListener addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY()); } @Override public void mouseEntered(MouseEvent e) { System.out.println("Mouse entered"); } @Override public void mouseExited(MouseEvent e) { System.out.println("Mouse exited"); } }); } public static void main(String[] args) { new MouseEventDemo(); } }

6. Inner Classes

Definition: Inner class is a class defined inside another class. Can access outer class members directly.

Types of Inner Classes:

  • Member Inner Class – Defined as member of outer class
  • Local Inner Class – Defined inside method
  • Anonymous Inner Class – Unnamed class defined inline
  • Static Inner Class – Declared with static keyword
// Using Anonymous Inner Class for Event Handling import java.awt.*; import java.awt.event.*; public class InnerClassExample extends Frame { Button btn; public InnerClassExample() { setLayout(new FlowLayout()); btn = new Button("Press"); // Anonymous inner class implementing ActionListener btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Button pressed!"); } }); add(btn); setSize(300, 200); setVisible(true); } public static void main(String[] args) { new InnerClassExample(); } }

7. Abstract Window Toolkit (AWT)

Definition: AWT (Abstract Window Toolkit) is a package that provides GUI components and tools for building user interfaces in Java.

7.1 Components and Containers

Component:

Basic building block of GUI. Examples: Button, TextField, Label, etc.

Container:

Component that can hold other components. Examples: Frame, Panel, Dialog.

7.2 Common AWT Components

Button:

Button btn = new Button("Click Me"); btn.addActionListener(listener); container.add(btn);

Label:

Label label = new Label("Welcome"); label.setAlignment(Label.CENTER); container.add(label);

TextField:

TextField tf = new TextField("Enter text", 20); tf.setEchoChar('*'); // For password field container.add(tf);

TextArea:

TextArea ta = new TextArea(10, 30); ta.setText("Multiple\nLines\nofText"); container.add(ta);

Checkbox:

Checkbox cb = new Checkbox("Accept Terms"); cb.addItemListener(listener); container.add(cb);

Radio Buttons (Checkbox with CheckboxGroup):

CheckboxGroup group = new CheckboxGroup(); Checkbox rb1 = new Checkbox("Male", group, false); Checkbox rb2 = new Checkbox("Female", group, false); container.add(rb1); container.add(rb2);

List:

List list = new List(5, false); // 5 visible items, single selection list.add("Java"); list.add("Python"); list.add("C++"); container.add(list);

Choice (Dropdown):

Choice choice = new Choice(); choice.add("Select Language"); choice.add("Java"); choice.add("Python"); container.add(choice);

7.3 Layouts

Definition: Layout managers control the positioning and sizing of components in containers.

Common Layout Managers:

1) FlowLayout:
Components arranged left to right in rows. Default for Applet and Panel.
container.setLayout(new FlowLayout()); container.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
2) BorderLayout:
Divides container into five regions: North, South, East, West, Center.
container.setLayout(new BorderLayout()); container.add(button1, BorderLayout.NORTH); container.add(button2, BorderLayout.CENTER);
3) GridLayout:
Arranges components in grid of rows and columns.
container.setLayout(new GridLayout(3, 3)); // 3 rows, 3 columns
4) CardLayout:
Components stacked like cards. Only one visible at a time.
5) GridBagLayout:
Flexible layout with complex component positioning.

7.4 Menu

Definition: Menu provides list of options accessible via menu bar.
import java.awt.*; import java.awt.event.*; public class MenuExample extends Frame implements ActionListener { MenuBar menuBar; Menu fileMenu, editMenu; MenuItem newItem, openItem, exitItem; public MenuExample() { // Create menu bar menuBar = new MenuBar(); // Create File menu fileMenu = new Menu("File"); newItem = new MenuItem("New"); openItem = new MenuItem("Open"); exitItem = new MenuItem("Exit"); newItem.addActionListener(this); openItem.addActionListener(this); exitItem.addActionListener(this); fileMenu.add(newItem); fileMenu.add(openItem); fileMenu.addSeparator(); fileMenu.add(exitItem); // Add menu to menu bar menuBar.add(fileMenu); setMenuBar(menuBar); setSize(400, 300); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == exitItem) { System.exit(0); } } public static void main(String[] args) { new MenuExample(); } }

7.5 Scrollbar

Definition: Scrollbar provides horizontal or vertical scroll control.
// Vertical scrollbar Scrollbar vscroll = new Scrollbar(Scrollbar.VERTICAL, 50, 10, 0, 100); // Horizontal scrollbar Scrollbar hscroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 20, 0, 200); // Add listener vscroll.addAdjustmentListener(listener); container.add(vscroll);

Complete AWT Application Example:

import java.awt.*; import java.awt.event.*; public class CompleteAWT extends Frame implements ActionListener { TextField tf; Button btnSubmit; Label label; TextArea ta; public CompleteAWT() { setLayout(new BorderLayout()); // Panel 1: North - Input Panel panel1 = new Panel(new FlowLayout()); label = new Label("Enter name: "); tf = new TextField(20); btnSubmit = new Button("Submit"); btnSubmit.addActionListener(this); panel1.add(label); panel1.add(tf); panel1.add(btnSubmit); // Panel 2: Center - Output ta = new TextArea(10, 40); ta.setEditable(false); // Add panels to frame add(panel1, BorderLayout.NORTH); add(ta, BorderLayout.CENTER); // Window closing event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setSize(500, 400); setTitle("AWT Application"); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { String name = tf.getText(); ta.append("Name entered: " + name + "\n"); tf.setText(""); } public static void main(String[] args) { new CompleteAWT(); } }

📝 Unit VI – Summary

  • Event is user interaction with GUI component.
  • Event Delegation Model: Source → Event → Listener → Handler
  • Event Listeners implement interfaces to handle specific events.
  • Adapter classes provide default implementations to avoid coding unnecessary methods.
  • Inner classes can be used for event handling (anonymous inner classes).
  • AWT Components: Button, Label, TextField, TextArea, Checkbox, List, Choice, etc.
  • Layout Managers: FlowLayout, BorderLayout, GridLayout, CardLayout, GridBagLayout.
  • Menu provides navigation options via menu bar and menu items.
  • Scrollbar provides scroll functionality for long content.

⭐ Important Exam Questions

  • (6 marks) Explain event delegation model with flow diagram.
  • (4 marks) Explain event sources, listeners, and event handlers with example.
  • (4 marks) What are adapter classes? Why are they useful?
  • (6 marks) Write a program demonstrating button click event handling.
  • (4 marks) Explain different AWT components with examples.
  • (6 marks) Explain different layout managers with examples.
  • (4 marks) Write a program with menu and menu items.
  • (6 marks) Write a complete AWT application with multiple components and event handling.