0% found this document useful (0 votes)
5 views49 pages

Java Notes by Ai

Unit I covers the Java environment and object-oriented programming concepts. It discusses Java's history, features, and differences from C++, along with core OOP principles like encapsulation and inheritance. Additionally, it explains Java's execution model, memory management, and provides insights into classes, objects, methods, and key Java constructs.

Uploaded by

ximagax150
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views49 pages

Java Notes by Ai

Unit I covers the Java environment and object-oriented programming concepts. It discusses Java's history, features, and differences from C++, along with core OOP principles like encapsulation and inheritance. Additionally, it explains Java's execution model, memory management, and provides insights into classes, objects, methods, and key Java constructs.

Uploaded by

ximagax150
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT I — Java Environment + Object Oriented

Programming in Java (Detailed Notes)

From your syllabus image, Unit I includes two parts:

1. The Java Environment

History and features of Java, C++ vs Java, OOP concepts, how Java works, PATH &
CLASSPATH, a simple program, compilation & execution, Java program structure, JVM
concepts, Java platform overview, primitive data types, variables & constants, operators,
expressions, statements (branching/looping/jumping), labeled statements.

2. Object Oriented Programming in Java

Classes, objects and methods: defining a class, adding variables and methods, creating
objects, constructor, instances, field and method initialization by constructors, copy
constructor, memory allocation & garbage collection in Java, keywords, access methods
(access specifiers), Arrays, String and StringBuffer classes, Wrapper classes, using JDK
tools.

I’ll keep it professional, detailed, and exam-ready, while still easy to understand.

PART A: The Java Environment

1) History and Features of Java

History (exam-ready)

Java was developed at Sun Microsystems (James Gosling and team) in the early 1990s. It
was designed to be:

portable across devices,


robust and secure,
suitable for network-based applications.

Key definition
Java: A high-level, class-based, object-oriented programming language designed to have
as few implementation dependencies as possible (platform independent through JVM).

Features of Java (with meaning)

1. Simple
Syntax is cleaner than C++ (no pointers for memory manipulation, no
multiple inheritance of classes).
2. Object-Oriented
Programs are organized around classes/objects; supports encapsulation,
inheritance, polymorphism, abstraction.
3. Platform Independent (Write Once, Run Anywhere)
Java source compiles into bytecode, which runs on any device with a JVM.
4. Robust
Strong type checking, exception handling, and garbage collection reduce
crashes.
5. Secure
Bytecode verification, sandbox model (especially in old applet era), no direct
pointer arithmetic.
6. Multithreaded
Built-in thread support to do multiple tasks concurrently.
7. Distributed / Network-oriented
Rich networking libraries ([Link]), supports network programming easily.
8. High Performance (relative)
JIT (Just-In-Time) compilation converts bytecode to native code at runtime.
9. Portable & Architecture-neutral
Fixed-size primitive types (e.g., int is always 32-bit), bytecode not tied to
CPU.

2) C++ vs Java (Important Differences)

Language level differences

Compilation output
C++: compiles to machine code (platform dependent)
Java: compiles to bytecode (runs on JVM)
Pointers
C++: supports pointers directly
Java: no pointer arithmetic; uses references (safer)
Multiple inheritance
C++: supports multiple inheritance with classes
Java: no multiple inheritance of classes; uses interfaces instead
Memory management
C++: manual using new/delete
Java: automatic garbage collection
Operator overloading
C++: supported
Java: not supported (except + for String concatenation)
Preprocessor
C++: has preprocessor ( #include , #define )
Java: no preprocessor; uses packages and imports
Templates vs Generics
C++: templates (compile-time)
Java: generics (type safety; type erasure in many cases)

Key definition

Platform dependent: Program must be recompiled for each OS/CPU.

Platform independent: Program can run on any platform without change (given the
proper runtime).

3) OOP Concepts (Core Concepts)

Key definition

Object-Oriented Programming (OOP): A programming paradigm where software is


designed using objects (data + behavior) created from classes.

Core OOP pillars

1. Encapsulation
Bundling data (fields) and methods together; controlling access using access
modifiers.
Example idea: private data + public methods.
2. Abstraction
Showing essential features and hiding internal details.
Achieved using abstract classes, interfaces.
3. Inheritance
New class (subclass) derives properties/behavior from an existing class
(superclass) using extends .
4. Polymorphism
One interface, multiple implementations.
In Java, mainly:
Method overloading (compile-time polymorphism)
Method overriding (run-time polymorphism)

4) How Java Works (Java Execution Model)

Java works in two major steps:

1. Compilation
javac compiles .java file into .class file (bytecode)
2. Execution
java command runs bytecode on JVM

Key definition

Bytecode: Intermediate compiled code stored in .class files, executed by the JVM.

What happens during execution (clear flow)

Source code ( .java )

compiled by Java compiler ( javac )

Bytecode ( .class )

loaded by Class Loader

verified by Bytecode Verifier

executed by Interpreter or JIT compiler

Runs on JVM, which sits on OS/hardware

5) PATH and CLASSPATH

PATH
Key definition

PATH: An environment variable that tells the operating system where to find executable
programs (like java , javac ).

If PATH includes the JDK bin folder, you can run:

java
javac

from any directory.

CLASSPATH

Key definition

CLASSPATH: An environment setting that tells the JVM (and sometimes compiler) where
to find compiled .class files and libraries ( .jar files).

If your class is in current folder: include . in classpath


If you use external libraries: include their jar paths

Typical forms:

Windows: .;C:\libs\[Link]
Linux/Mac: .:/home/user/libs/[Link]

6) A Simple Java Program

Example:

A class is defined using class


Main method is the entry point

Key points:

Java is case-sensitive
Every statement ends with ;
Code blocks use { }

Key definitions

Class: A blueprint/template for creating objects.


main method: The starting point of a Java application.

7) Compilation and Execution

Assume file name is [Link] :

1. Compile:

javac [Link]

Output: [Link]

1. Run:

java Hello

(Do not write .class )

Common mistakes

File name must match the public class name (if class is public )
Running with wrong classpath causes “ClassNotFoundException”

8) Java Program Structure


A typical Java program can include:

1. Package statement (optional, must be first line)


2. Import statements (optional)
3. Class definition
4. Fields (variables)
5. Methods
6. main method (for applications)

Key definition

Package: A namespace for organizing classes and avoiding naming conflicts.

9) JVM Concepts
What is JVM?

Key definition

JVM (Java Virtual Machine): A virtual runtime environment that executes Java bytecode
and provides platform independence.

Main components (exam-friendly)

1. Class Loader
Loads .class files into memory
2. Bytecode Verifier
Checks bytecode for security and correctness
3. Runtime Data Areas
Method Area, Heap, Java Stacks, PC Register, Native Method Stack (high-level
mention is enough unless teacher asks deep)
4. Execution Engine
Interpreter + JIT compiler + Garbage Collector

JRE vs JDK (Java platform overview)

JDK (Java Development Kit): Tools for development (compiler, debugger) + JRE
JRE (Java Runtime Environment): JVM + core libraries to run Java programs

Key definition

JDK: Used to develop (write + compile) Java programs.

JRE: Used to run Java programs.

10) Primitive Data Types


Java has 8 primitive types:

byte (8-bit)
short (16-bit)
int (32-bit)
long (64-bit)
float (32-bit floating)
double (64-bit floating)
char (16-bit Unicode)
boolean (true/false)
Important notes

char stores a single Unicode character (not just ASCII).


boolean is not numeric.

Key definition

Primitive type: A basic built-in data type that stores simple values directly (not objects).

11) Variables and Constants

Variables

Key definition

Variable: A named memory location that stores a value of a specific type.

Kinds of variables (often asked):

Local variables: declared inside methods/blocks


Instance variables: fields of an object (non-static)
Static variables: class variables shared across all objects

Constants

Java uses:

final to make variables constant

Key definition

Constant: A value that cannot be changed during program execution (in Java, declared
using final ).

12) Operators, Expressions, Statements

Operators (categories)

Arithmetic: + - * / %
Relational: == != > < >= <=
Logical: && || !
Assignment: = += -= *= /= %=
Increment/Decrement: ++ --
Bitwise: & | ^ ~
Shift: << >> >>>
Ternary: ?:
Type cast: (type)

Key definition

Expression: Combination of variables/literals/operators that produces a value.

Statement: A complete instruction in Java (usually ends with ; ).

13) Statements: Branching, Looping, Jumping

Branching

if , if-else , else-if ladder


switch (works with int/char/String/enums in modern Java)

Looping

for
while
do-while

Jumping

break (exit loop/switch)


continue (skip to next iteration)
return (exit method)

14) Labeled Statements

A label is an identifier followed by : placed before a loop.

Used with break label; or continue label; to control nested loops.

Key definition
Labeled break/continue: A way to break/continue an outer loop from inside an inner
loop.

Example idea:

break outer; exits the loop labeled outer .

PART B: Object Oriented Programming in


Java

1) Classes, Objects, and Methods

Class

Key definition

Class: A blueprint that defines data (fields) and behavior (methods).

Object

Key definition

Object: An instance of a class created at runtime, having its own state (field values).

Method

Key definition

Method: A function defined inside a class that describes behavior.

2) Defining a Class, Adding Variables and Methods

Typical class contains:

fields (instance variables)


constructors
methods
Important idea: fields represent state, methods operate on that state.

3) Creating Objects (Instantiation)

Objects are created using new .

Key definition

Instantiation: The process of creating an object from a class.

When you do new , memory is allocated (generally on heap), and a constructor is


executed.

4) Constructors

Key definition

Constructor: A special method used to initialize objects; has the same name as the class
and no return type.

Key points:

Default constructor exists only if you don’t write any constructor.


Constructors can be overloaded.
this() can call another constructor in the same class (must be first statement).
super() calls parent constructor (also typically first statement; compiler inserts it if
needed).

5) Instances, Fields, and Method Initialization by


Constructors

Instance variables (fields)

Belong to an object.
Initialized automatically with default values if not set:
numbers 0
boolean false
references null
char ‘u0000’
Constructor initialization

Constructors set meaningful initial values (not just defaults).

Key idea

Constructors ensure objects start in a valid state.

6) Copy Constructor (Java perspective)


In C++, copy constructor is built-in. In Java, there is no automatic copy constructor, but
you can create one manually.

Key definition

Copy constructor (in Java): A constructor that creates a new object by copying fields
from another object of the same class.

Important notes:

Default copying of object references can cause shallow copy.


Sometimes you need deep copy for contained objects/arrays.

Key definitions

Shallow copy: Copies references (both objects share the same internal objects).
Deep copy: Copies actual internal objects too.

7) Memory Allocation and Garbage Collection in Java

Memory areas (high-level, sufficient for Unit I)

Heap: objects allocated with new


Stack: method calls, local variables, references

Garbage collection

Key definition

Garbage Collection (GC): Automatic process of reclaiming heap memory by deleting


objects that are no longer reachable by any reference.
Important points:

You cannot directly destroy objects like C++ delete .


GC runs automatically; you can request with [Link]() but it’s not guaranteed
immediately.

8) Java Keywords (Unit I level)


Keywords are reserved words with fixed meaning (cannot be used as identifiers).
Examples relevant here:

class , public , private , protected


static , final , this , new
return , void
if , else , switch , case , for , while , do
break , continue
super (will be used more in Unit II inheritance)
abstract , interface (Unit II)

Key definition

Keyword: Reserved word predefined by Java language.

9) Access Methods / Access Specifiers (Encapsulation)


Java access modifiers:

private: accessible only within the same class


default (no keyword): accessible within the same package
protected: package + subclasses outside package
public: accessible from anywhere

Key definition

Access specifier (access modifier): Keyword that controls the visibility/scope of classes,
fields, constructors, and methods.

10) Arrays
Key definition
Array: A fixed-size data structure that stores multiple values of the same type in
contiguous indexed locations.

Key points:

Index starts at 0.
Arrays are objects in Java.
length gives size (field, not method).

Types:

1D array: int[] a
2D array: int[][] m (array of arrays; can be jagged)

11) String and StringBuffer Classes

String

Key definition

String: An immutable sequence of characters in Java.

Immutability means:

once created, contents cannot change


operations like concatenation create a new String object

Why important:

safe for sharing


supports string pool optimization

StringBuffer

Key definition

StringBuffer: A mutable sequence of characters (changes in place), thread-safe.

Use StringBuffer when:

many modifications (append, insert, delete) are needed

(Also StringBuilder exists: mutable but not synchronized; faster; but your syllabus
mentions StringBuffer specifically.)
Key difference (must know)

String: immutable
StringBuffer: mutable

12) Wrapper Classes


Java provides object versions of primitives:

Integer for int


Double for double
Character for char
Boolean for boolean , etc.

Key definition

Wrapper class: A class that wraps a primitive type into an object.

Why needed:

collections store objects (e.g., ArrayList)


utility methods (parsing, conversion)

Autoboxing/unboxing idea:

automatic conversion between primitive and wrapper.

13) Using JDK Tools (basic)


Common JDK tools:

javac : compiler
java : runs Java program
javadoc : generates documentation
jar : creates/extracts jar files
javap : class file disassembler (shows bytecode info)
jshell (newer): interactive shell (if included in your version)

Key definition

JAR: Java ARchive file that packages classes and resources.


Unit I Quick Summary (Revision)

Java compiles to bytecode and runs on JVM (platform independence).


PATH locates tools; CLASSPATH locates classes/libraries.
Program structure: package imports class main.
Primitive types, variables, operators, expressions, and control statements are core
syntax.
OOP in Java centers on classes/objects/methods; constructors initialize objects.
Java manages memory automatically using garbage collection.
Arrays store same-type elements; String is immutable; StringBuffer is mutable.
Wrapper classes convert primitives into objects.

Unit I Practice Questions (Exam-style)


1. Define Java and list any six features of Java.
2. Compare C++ and Java (any five differences).
3. Explain the Java execution model with bytecode and JVM.
4. Define PATH and CLASSPATH. Why are they needed?
5. Explain Java program structure with main method.
6. Explain primitive data types in Java.
7. Define class, object, method, and constructor with examples.
8. What is garbage collection? Explain heap and stack at a high level.
9. Differentiate String and StringBuffer.
10. What are wrapper classes? Why are they used?

UNIT II — Inheritance + Interfaces + Multithreading and


Exception Handling (Detailed Notes)

From your syllabus image, Unit II contains:

Inheritance: inheritance basics, superclass, subclass, method overloading, abstract


classes
Interfaces: defining an interface, implementing & applying interfaces, variables in
interfaces, extending interfaces
Multithreading and Exception Handling: basic idea of multithreaded programming,
thread lifecycle, creating thread with Thread class and Runnable interface, thread
synchronization, thread scheduling, basics of exception handling: try, catch, throw,
throws
PART A: INHERITANCE

1) Inheritance Basics

Key definition

Inheritance: An OOP mechanism where a new class (subclass) acquires the properties
(fields) and behaviors (methods) of an existing class (superclass), allowing code reuse and
hierarchical classification.

Why inheritance is used

1. Code reusability: common code is written once in superclass.


2. Extensibility: subclass can add new features without changing existing code.
3. Maintainability: changes in base behavior can be centralized (carefully).
4. Polymorphism: a superclass reference can refer to subclass objects (runtime
method dispatch).

Types of inheritance (Java perspective)

Single inheritance: one class extends one class (supported)

Multilevel inheritance: class extends a class which extends another (supported)

Hierarchical inheritance: many subclasses extend one superclass (supported)

Multiple inheritance (classes): NOT supported in Java (to avoid ambiguity like
diamond problem)

Instead Java provides multiple inheritance of type via interfaces.

2) Superclass and Subclass

Key definitions

Superclass (base class / parent class): the class being inherited from.
Subclass (derived class / child class): the class that inherits from another class
using extends .
Syntax

class SubClass extends SuperClass { ... }

What a subclass gets (inherits)

Non-private fields and methods of superclass (subject to access rules)


The ability to use/override superclass methods

What is NOT inherited

Constructors are not inherited, but they are executed via super() during object
creation.

3) The super keyword (important with inheritance)

Uses of super

1. Access superclass members


[Link]() calls parent version
[Link] accesses parent field (if accessible)
2. Call superclass constructor
super() or super(args) must be the first statement in subclass constructor.

Key definition

super: A reference used to access members of the immediate superclass.

4) Method Overloading (listed in your Unit II)

Key definition

Method overloading: Defining multiple methods in the same class with the same name
but different parameter lists (different type/number/order of parameters). It is compile-
time polymorphism.

Important rules:

Return type alone cannot distinguish overloads.


Overloading can occur in same class (and also across inheritance if subclass
defines same method name with different parameters).

Example idea (concept):

add(int a, int b)
add(double a, double b)
add(int a, int b, int c)

5) Abstract Classes

Key definition

Abstract class: A class declared with abstract that cannot be instantiated directly and
may contain abstract methods (methods without body) and concrete methods (methods
with implementation).

Why abstract classes are used

To define a common template for subclasses


To force subclasses to implement certain behaviors
To partially implement a concept and leave the rest to specialized classes

Abstract methods

Key definition

Abstract method: A method declared without implementation ( abstract ) that must be


implemented (overridden) in the first non-abstract subclass.

Rules:

If a class has an abstract method, the class must be abstract.


Abstract class can have constructors (used when subclass object is created).
Abstract class can have fields, concrete methods, static methods too.

PART B: INTERFACES
1) What is an Interface?

Key definition

Interface: A fully abstract type that defines a contract (a set of method signatures) that
implementing classes must provide.

Why interfaces are used:

1. Achieve multiple inheritance of type


2. Provide a standard contract across unrelated classes
3. Support loose coupling and polymorphism (program to an interface)

2) Defining an Interface
Syntax:

interface InterfaceName { ... }

Interface typically contains:

abstract methods (implicitly public abstract )


constants (implicitly public static final )

3) Implementing and Applying Interfaces

Implementing

A class implements an interface using implements .

Key definition

implements: Keyword used by a class to promise that it will define all methods declared
in an interface.

Rules:

If class does not implement all interface methods, class must be declared
abstract .
A class can implement multiple interfaces:
class A implements I1, I2, I3 { ... }
Applying (using interface references)

You can write:

I1 ref = new SomeClass();

This enables polymorphism: the code depends on the interface, not the concrete class.

4) Variables in Interfaces
All variables declared in an interface are automatically:

public static final

Meaning:

They are constants


Belong to the interface itself (not objects)
Must be initialized at declaration

Key definition

Interface constant: A variable in an interface that is implicitly public static final and
cannot be changed.

5) Extending Interfaces
An interface can extend one or more interfaces.

Key definition

Interface inheritance: An interface can inherit method signatures/constants from other


interfaces using extends .

Example idea:

interface I3 extends I1, I2 { }

Important difference:

class extends one class only


interface can extend multiple interfaces
PART C: MULTITHREADING

1) Basic Idea of Multithreaded Programming

Key definition

Thread: The smallest unit of execution within a process; a thread represents an


independent path of execution.

Why multithreading is used

Better CPU utilization (especially for multi-core)


Responsive GUI (UI stays active while background tasks run)
Parallel tasks (downloading + processing + displaying)
Server applications handling multiple clients

Process vs Thread

Process: running program with its own memory space


Thread: runs inside a process and shares process memory

2) Lifecycle of a Thread (Thread States)


Common states (conceptual exam answer):

1. New: thread object created, not started


2. Runnable: ready to run (may actually be running)
3. Running: executing on CPU (often included within runnable concept)
4. Blocked/Waiting: waiting for lock, I/O, or another thread signal
5. Timed Waiting: sleeping/waiting for a fixed time
6. Terminated (Dead): finished execution

Key definition

Thread lifecycle: The sequence of states a thread passes through from creation to
termination.
3) Creating Threads

Method 1: Extending Thread class

Steps:

1. Create a subclass of Thread


2. Override run()
3. Create object and call start()

Important:

start() creates a new thread and calls run() internally.


Calling run() directly does NOT start a new thread (it runs like a normal method
call).

Method 2: Implementing Runnable interface

Steps:

1. Create a class that implements Runnable


2. Implement run()
3. Pass Runnable object to Thread constructor
4. Call start()

Key definition

Runnable: A functional interface containing run() representing a task to be executed by


a thread.

Why Runnable is often preferred

Java allows only single inheritance for classes; implementing Runnable keeps
inheritance option open.
Encourages separating “task” from “thread”.

4) Thread Synchronization
When threads share data, problems occur:

race conditions (wrong results due to interleaving)


inconsistent updates
Key definitions

Critical section: Code that accesses shared resources and must not be executed
by more than one thread at a time.
Race condition: Error caused when multiple threads access/update shared data
without proper synchronization.
Synchronization: Ensuring only one thread at a time executes critical section
code.

How Java supports synchronization (conceptual)

synchronized methods/blocks use an intrinsic lock (monitor) on an object.


Only one thread can hold that lock at a time.

Example idea:

synchronize updates to a shared bank account balance.

5) Thread Scheduling (Basic Idea)

Thread scheduling decides which runnable thread gets CPU.

Scheduling depends on:

OS scheduler + JVM
thread priorities (in Java, priority is a hint, not a guarantee)
time slicing/preemptive scheduling (common)

Key definition

Thread scheduling: The mechanism that decides the execution order of multiple
runnable threads.

Common thread methods (conceptual mentions):

sleep(ms) makes thread timed-waiting


yield() hints to give chance to other threads
join() waits for another thread to finish

(Exact inclusion may depend on your teacher; your syllabus says “thread scheduling”
generally.)
PART D: EXCEPTION HANDLING

1) Basic Idea of Exception Handling

Key definition

Exception: An event (error condition) that occurs during program execution and disrupts
normal flow.

Exception handling provides:

separation of error handling code from normal code


graceful recovery
prevents abrupt termination (when handled properly)

Types (basic mention)

Checked exceptions: must be handled/declared (e.g., many I/O exceptions)


Unchecked exceptions: runtime exceptions (e.g., divide by zero, null pointer)

2) try and catch

try block

Contains code that might throw an exception.

catch block

Handles a specific type of exception.

Key definition

try-catch: A construct to detect and handle exceptions without crashing the program.

Rules:

multiple catches allowed


more specific exceptions should be caught before more general ones
3) throw

Key definition

throw: Keyword used to explicitly throw an exception object from code.

Used when:

you detect an error condition and want to signal it.

Example idea:

if age < 0 then throw IllegalArgumentException

4) throws

Key definition

throws: Clause in a method declaration indicating that the method may pass (propagate)
certain exceptions to the caller.

Used when:

method cannot handle exception meaningfully


caller should decide how to handle

Example idea:

void readFile() throws IOException

Unit II Summary (Quick Revision)


Inheritance: subclass extends superclass; enables reuse and polymorphism.
Overloading: same method name with different parameter lists (compile-time).
Abstract classes: cannot instantiate; may contain abstract methods; subclasses
must implement.
Interfaces: contracts; class implements interface; interface variables are constants;
interfaces can extend multiple interfaces.
Multithreading: multiple execution paths; create threads using Thread or
Runnable; synchronization prevents race conditions; scheduling decides CPU time.
Exception handling: try-catch handles runtime issues; throw throws exception
explicitly; throws declares possible exceptions.

Unit II Practice Questions (Exam-style)


1. Define inheritance. Differentiate superclass and subclass.
2. Explain method overloading with rules and examples.
3. What is an abstract class? Why can’t it be instantiated?
4. Differentiate abstract class and interface (any five points).
5. Explain interface variables. Why are they public static final ?
6. What is multithreading? List advantages.
7. Explain thread lifecycle with states.
8. Differentiate creating threads using Thread class and Runnable interface.
9. What is synchronization? Explain race condition and critical section.
10. Explain try, catch, throw, throws with suitable examples.

Unit 3: Applet Programming + AWT (Abstract Window


Toolkit)

Part A: Applet Programming

3.1 What is an Applet?

An applet is a small Java program designed to run inside another application—


traditionally a web browser or an applet viewer.

Definition (Applet): An applet is a Java program that runs within a Java-enabled


environment (such as a browser or applet viewer) rather than running as a
standalone application.

Important exam note: Modern browsers no longer support Java applets due to security
and plugin removal, but applets remain in many older syllabi for understanding Java GUI
and sandbox security ideas.

3.2 Local and Remote Applets

Local Applet: Stored on the same machine; loaded from a local file system.
Remote Applet: Stored on a server; loaded via a network URL.
Definition (Local applet): An applet loaded from the local computer’s file system.

Definition (Remote applet): An applet loaded from a remote server through the
network.

3.3 Applet vs Application

A very common long-answer question.

Java Application

Runs independently using the JVM ( java ClassName )


Has public static void main(String[] args)
Has full access to system resources (subject to OS security)

Java Applet

Runs inside a container (browser/appletviewer)


Does not use main() for execution
Life cycle is controlled by the browser/viewer
Usually runs under security restrictions (sandbox)

Definition (Application): A standalone Java program that runs independently on


the JVM and typically starts execution from the main() method.

3.4 Applet Life Cycle (Core Concept)

Applet execution is managed by a life cycle—methods that are called automatically.

Common life-cycle methods:

init() – called once when applet is initialized


start() – called when applet becomes active
paint(Graphics g) – called whenever the applet needs to redraw
stop() – called when applet becomes inactive
destroy() – called when applet is removed/unloaded

Definition (Applet life cycle): The sequence of automatic method calls ( init ,
start , paint , stop , destroy ) that control an applet’s execution.

Example / Case Study:

Imagine a quiz applet embedded in a webpage:

When the page opens: init() loads questions, start() begins the quiz timer.
If the user switches tabs: stop() pauses animations/timers.
When the user returns: start() resumes.
On refresh/close: destroy() releases resources.

3.5 Creating and Executing Java Applets

General steps (conceptual, exam-friendly):

1. Write an applet class (commonly extending Applet or JApplet )

2. Implement life-cycle methods

3. Display output using paint()

4. Run it using:

appletviewer (traditional tool), or


embed in HTML (historically)

Definition (appletviewer): A JDK tool used to run and test applets without a web
browser.

3.6 Inserting Applets in a Web Page

Historically, applets were embedded in HTML using tags like:

<applet> (older)
<object> / <embed> (later)

Syllabus mentions HTML Tags & Applet Tag.

Definition (Applet tag): An HTML tag historically used to embed a Java applet into a
web page by specifying the applet class and parameters.

3.7 Java Security (Applet Security Model)

Applets were designed to run with restrictions to protect the user’s system.

Typical sandbox restrictions:

Cannot read/write local files freely


Cannot execute local programs
Network access may be limited (often only to the host server)
Definition (Sandbox security): A restricted execution environment that limits an
applet’s access to system resources to protect the user’s machine.

3.8 Passing Parameters to Applets

Applets can receive parameters from HTML (e.g., username, colors, speed). Inside Java,
parameters are read using methods like getParameter() .

Definition (Applet parameter): A named value provided from HTML to an applet at


runtime to control its behavior without changing the code.

Example:

A “Digital Clock” applet may accept parameters like bgColor , fontSize , or timezone .

3.9 Aligning the Display

This refers to controlling where and how output appears in the applet area (layout,
position, and drawing).

In applets:

Basic drawing uses the Graphics context inside paint(Graphics g)


Components (buttons/text fields) use layout managers (covered in AWT part)

Definition (Graphics context): An object used for drawing text and shapes on the
screen, typically provided to the paint() method.

3.10 Getting Input from User

User input can be obtained through:

AWT components (TextField, Button, Checkbox, etc.)


Event handling (mouse/keyboard actions—detailed in Unit 4, but you should
mention it)

Example:

A login applet can take username/password via text fields and respond when a button is
clicked.

Part B: The AWT (Abstract Window Toolkit)


3.11 AWT Class Hierarchy (Window Fundamentals)

AWT provides classes for building GUI applications.

At a high level:

Component: base class for GUI elements (buttons, labels, text fields)
Container: a component that can hold other components
Window / Frame: top-level windows
Panel: container used inside windows/applets

Definition (Component): A GUI element (like button, label, text field) that can be
displayed on the screen.

Definition (Container): A GUI component that can hold and organize other
components.

3.12 Basic User Interface Components (as per syllabus)

1. Label

Displays non-editable text.

Definition (Label): A component used to display a fixed line of text.

2. Button

Clickable component that triggers an action.

Definition (Button): A clickable component used to initiate an action.

3. Check Box

Used to select/deselect an option (true/false).

Definition (Checkbox): A component that represents an on/off choice.

4. Radio Button

Used where only one option should be selected from a group (in AWT,
implemented using CheckboxGroup).

Definition (Radio button): A mutually exclusive option selector where only one
choice in a group can be active.

5. Choice Menu

Drop-down list to select one item.


Definition (Choice): A drop-down list component that allows selecting one item
from multiple choices.

6. Text Area

Multi-line text input/output.

Definition (TextArea): A component used for multi-line text entry or display.

7. Scroll List

List of items, sometimes allowing single or multiple selection.

Definition (List): A component that displays a list of items for user selection.

8. Scroll Bar

A bar used to scroll content horizontally or vertically.

Definition (Scrollbar): A GUI control used to scroll through content.

9. Frame

A top-level window with title bar, border, and controls (minimize/close).

Definition (Frame): A top-level AWT window that can contain other GUI
components.

3.13 Layout Managers

A layout manager automatically arranges components in a container.

Definition (Layout manager): An object that controls the size and position of GUI
components inside a container.

Layouts in your syllabus:

(a) Flow Layout

Places components left-to-right, top-to-bottom (like words in a sentence).

Use-case: Simple forms, toolbars.

(b) Grid Layout

Arranges components in a grid of rows and columns, equal-sized cells.

Use-case: Calculator interface, uniform buttons.


© Border Layout

Divides area into 5 regions: North, South, East, West, Center.

Use-case: Typical application window (menu top, status bottom, main center).

(d) Card Layout

Holds multiple “cards” (screens) but shows one at a time.

Use-case: Wizard forms, step-by-step UI, multi-page applet screens.

Case Study Example (CardLayout):

A “Student Registration” GUI can have:

Card 1: Personal details


Card 2: Course selection
Card 3: Confirmation

Only one card is visible at a time; “Next/Back” navigates between cards.

Summary (Unit 3)

Applets are Java programs designed to run inside a browser/appletviewer with a


controlled life cycle ( init , start , paint , stop , destroy ).
Applets can be local or remote, and differ from applications in how they start (no
main ) and what system access they have (security sandbox).
Applets can be embedded in HTML and can accept runtime parameters supplied
through the page.
AWT provides Java’s early GUI toolkit, with a class hierarchy of Component and
Container.
Common AWT components include Label, Button, Checkbox, Radio Button, Choice,
TextArea, List, Scrollbar, and Frame.
Layout managers (Flow, Grid, Border, Card) control automatic arrangement of
GUI components.

Practice Questions (Unit 3)

1. Define an applet. Explain the complete applet life cycle with the purpose of each
method.
2. Differentiate between Java applet and Java application (any five points).

3. What is the security sandbox model in applets? Why was it needed?

4. Explain AWT Component and Container with examples of each.

5. Compare FlowLayout, GridLayout, BorderLayout, and CardLayout with one


practical use-case for each.

Unit 4: The Java Event Handling Model + Networking


Basics

Part A: The Java Event Handling Model (Event Delegation Model)

4.1 Introduction to Event Handling

In GUI programming, a user interacts with components (buttons, text fields, windows) by
clicking, typing, moving the mouse, etc. Each such interaction generates an event, and
Java provides a mechanism to detect and respond to these events.

Definition (Event): An event is an object that represents a change in state (such as


a mouse click, key press, or window action) generated by user or system activity.

Definition (Event handling): Event handling is the process of responding to events


by executing specific code when an event occurs.

4.2 Java’s Event Delegation Model

Java uses the event delegation model, where the responsibility of handling events is
delegated to separate handler objects.

Key idea:

A GUI component generates an event.


The event is sent to one or more listener objects.
The listener executes the appropriate method to handle the event.

Definition (Event delegation model): A model in which event handling is delegated


to listener objects that register themselves with event sources.

4.3 Event Source and Listener


Event Source: The component that generates the event (Button, TextField,
Window, etc.).
Event Listener: The object that receives and handles the event by implementing a
listener interface.

Definition (Event source): A GUI component that generates events when a user
interacts with it.

Definition (Event listener): An object that implements a listener interface to


receive and handle events from an event source.

Example:

Button is the event source.


ActionListener is the listener.
Clicking the button generates an ActionEvent .

4.4 Event Classes and Event Class Hierarchy

Java represents events as objects from event classes. Many AWT events are part of a
hierarchy.

Broad categories:

Semantic events: High-level meaning (e.g., button clicked).


Low-level events: Raw input or window activity (e.g., mouse moved, key pressed).

Definition (Event class): A class whose objects store details about a specific event,
such as the source, type, and additional parameters.

Typical hierarchy idea (conceptual for exams):

Base event object (often taught as EventObject / AWTEvent)


Subclasses like ActionEvent , MouseEvent , KeyEvent , WindowEvent , etc.

4.5 Self-Contained Events vs Delegating Events

This syllabus line usually means:

Self-contained event handling: A component handles its own events (older Java
1.0 style, not recommended).
Delegating events: Events are delegated to external listener objects (Java 1.1+
event model).
Definition (Self-contained event): An event model where the component itself
processes events internally (older approach).

Definition (Delegated event handling): An approach where event handling is


performed by separate listener objects registered with the source.

4.6 Relationship Between Interface, Methods Called, Parameters and Event Source

When you implement a listener interface, you must define certain methods. Java will call
those methods automatically when the event happens.

Listener interface defines handler methods


Event object is passed as a parameter
Event object contains the event source and details

Definition (Listener interface): An interface that contains one or more event-


handling method declarations which must be implemented to respond to events.

Example (conceptual):

Implement ActionListener
Provide method actionPerformed(ActionEvent e)
[Link]() identifies which component fired the event

4.7 Adapter Classes

Some listener interfaces have many methods (e.g., MouseListener has multiple methods).
If you only need one method, implementing all becomes tedious. Java provides adapter
classes—ready-made classes with empty method bodies.

You can:

Extend an adapter class


Override only the required methods

Definition (Adapter class): A class that provides default (empty) implementations


of listener interface methods, allowing you to override only the methods you need.

Example / Case Study:

If you want only “mouse clicked” behavior, you can extend MouseAdapter and override
mouseClicked() only, instead of implementing all MouseListener methods.
4.8 Important Event Classes (As in Syllabus)

(a) ActionEvent

Generated when an action occurs, such as:

Button click
Pressing Enter in a TextField
Selecting a menu item

Definition (ActionEvent): An event generated when a component-specific action


occurs, commonly a button click.

(b) AdjustmentEvent

Generated when the value of an adjustable component changes (e.g., Scrollbar).

Definition (AdjustmentEvent): An event generated when a scrollbar (or similar


adjustable component) changes its value.

© ContainerEvent

Generated when a component is added to or removed from a container.

Definition (ContainerEvent): An event generated when components are added to or


removed from a container.

(d) FocusEvent

Generated when a component gains or loses input focus.

Definition (FocusEvent): An event that occurs when a component gains or loses


focus for receiving keyboard input.

(e) ItemEvent

Generated when the state of an item changes (checkbox selected, list item selected, etc.).

Definition (ItemEvent): An event generated when an item’s selection state changes.

(f) MouseEvent
Generated by mouse actions such as click, press, release, move, drag, enter, exit.

Definition (MouseEvent): An event generated in response to mouse actions like


clicking, moving, dragging, entering, or exiting a component.

(g) TextEvent

Generated when the text value of a text component changes (TextField/TextArea).

Definition (TextEvent): An event generated when the content of a text component


changes.

(h) WindowEvent

Generated when window-related activities occur (opening, closing, minimizing,


activating).

Definition (WindowEvent): An event associated with changes in a window’s state,


such as opening, closing, or activation.

Part B: Networking Basics in Java

4.9 Introduction to Networking

Networking allows two or more computers to exchange data. Java supports networking
through classes and interfaces, mainly in the [Link] package.

Definition (Computer network): A set of interconnected computers that


communicate and share resources.

Definition (Protocol): A set of rules that governs communication between


computers on a network.

4.10 Networking Classes and Interfaces ([Link] package)

Java’s [Link] contains:

Addressing classes (IP/Inet)


Connection-oriented communication (TCP)
Connectionless communication (UDP/datagrams)
Definition ([Link] package): A Java package providing classes and interfaces for
network communication, including sockets, URLs, and datagrams.

4.11 TCP/IP Basics

IP (Internet Protocol): Handles addressing and routing of packets.


TCP (Transmission Control Protocol): Ensures reliable, ordered, error-checked
delivery of data.

Definition (TCP): A connection-oriented protocol that provides reliable, ordered


data transmission.

Definition (IP): A protocol responsible for addressing and routing packets across
networks.

Example / Case Study:

Web browsing uses TCP because data must arrive correctly and in order (HTML, images,
scripts).

4.12 Datagram Programming (UDP Concept)

Datagrams are used in connectionless communication (commonly UDP).

Characteristics:

No connection setup
Faster, less overhead
No guarantee of delivery/order

Definition (Datagram): A self-contained packet of data transmitted over a network,


typically using a connectionless protocol like UDP.

Case Study Example:

Live video/audio streaming or online games may prefer UDP because small losses are
acceptable, but speed matters more than perfect reliability.

4.13 Networking in Java: TCP vs Datagram Programming

TCP in Java (Socket-based)


Uses Socket and ServerSocket
Reliable communication
Typically for client-server applications (chat, file transfer, web)

Definition (Socket): An endpoint for two-way network communication between a


client and server.

UDP in Java (Datagram-based)

Uses DatagramSocket and DatagramPacket


Connectionless
Suitable for lightweight message passing

Definition (DatagramSocket): A socket used to send and receive UDP datagram


packets.

Summary (Unit 4)
Java uses the event delegation model: event sources generate events, and
listeners handle them.
Event handling is based on listener interfaces, event-handling methods, and event
objects containing event details and source.
Adapter classes simplify handling by providing empty implementations of listener
interfaces.
Important events include ActionEvent, AdjustmentEvent, ContainerEvent,
FocusEvent, ItemEvent, MouseEvent, TextEvent, WindowEvent.
Java networking is supported mainly by the [Link] package.
TCP/IP provides reliable connection-oriented communication (TCP) and
addressing/routing (IP).
Datagram programming (UDP) is connectionless and faster but does not
guarantee delivery or order.

Practice Questions (Unit 4)

1. Explain Java’s event delegation model with a neat diagram (event source event
object listener).

2. Define event source and event listener. How does a listener get registered with a
source?
3. What are adapter classes? Why are they used? Give one example.

4. Write notes on any four event classes: ActionEvent, ItemEvent, MouseEvent,


WindowEvent, FocusEvent, TextEvent.

5. Explain TCP vs UDP (datagram). Mention one real-world application where each is
preferred.

Unit 5: Input/Output (Java I/O) + Byte Streams + JDBC

Part A: Input / Output in Java

5.1 Exploring Java I/O (Overview)

Input/Output (I/O) in Java is handled mainly through the [Link] package (and in modern
Java also [Link] ). I/O means reading data into a program (input) and sending data out
(output).

Java uses the concept of a stream.

Definition (Stream): A stream is a flow of data between a program and an


input/output source such as a file, keyboard, memory, or network.

Two main stream categories:

Byte streams: handle raw bytes (binary data)


Character streams: handle text (Unicode characters)

5.2 Directories

A directory is a folder used to organize files. Java can work with directories using the
File class.

Common directory operations:

Create a directory
List files in a directory
Check whether a path is a file or directory

Definition (Directory): A filesystem container used to store and organize files and
subdirectories.

Example / Case Study:


A “Student Record System” may store records in:

students/ directory
inside it, files like [Link] , [Link] , etc.

5.3 Stream Classes (High-Level View)

Java provides many I/O classes, but they follow a pattern:

Input streams read data


Output streams write data
Many streams can be chained for efficiency (buffering) or formatting

Definition (Input stream): A stream that reads data from a source into the
program.

Definition (Output stream): A stream that writes data from the program to a
destination.

Part B: The Byte Stream (Detailed)

5.4 Byte Stream Basics

Byte streams operate on 8-bit bytes and are suitable for:

images
audio/video files
binary files
any raw data transfer

Main abstract classes:

InputStream
OutputStream

Definition (Byte stream): A stream that reads/writes data as raw bytes (8-bit units).

5.5 InputStream and OutputStream

InputStream is used for reading bytes.


OutputStream is used for writing bytes.

Common methods:
read() reads byte(s)
write() writes byte(s)
close() releases resources

Definition (InputStream): An abstract class representing a byte input stream.

Definition (OutputStream): An abstract class representing a byte output stream.

5.6 FileInputStream and FileOutputStream

These are byte streams specifically for files.

FileInputStream reads bytes from a file


FileOutputStream writes bytes to a file

Definition (FileInputStream): A byte stream class used to read data from a file.

Definition (FileOutputStream): A byte stream class used to write data to a file.

Example / Case Study:

Copying an image file:

read image bytes using FileInputStream


write to another file using FileOutputStream

This works because images are binary data (byte-oriented).

5.7 PrintStream

PrintStream is used to print representations of different data types easily.

Examples:

[Link] is a PrintStream
Provides print() and println()

Definition (PrintStream): An output stream that prints formatted representations


of primitive values and strings.

5.8 RandomAccessFile

RandomAccessFile allows reading/writing at any position within a file, not only


sequentially.
Key concept: file pointer (cursor position).

Definition (RandomAccessFile): A class that allows reading and writing to a file at


any arbitrary position using a movable file pointer.

Case Study Example:

In a banking application, account records may be fixed-size. Using random access, the
program can directly jump to a specific account record location instead of reading the
entire file.

Part C: Character Streams

5.9 Character Streams (Reader/Writer)

Character streams handle text and Unicode characters.

Main abstract classes:

Reader (input)
Writer (output)

Definition (Character stream): A stream that reads/writes data as characters,


suitable for text processing.

5.10 BufferedReader and BufferedWriter

Buffering improves performance by reducing direct I/O operations.

BufferedReader reads text efficiently (supports readLine() ).


BufferedWriter writes text efficiently.

Definition (Buffering): A technique that stores data temporarily in memory to


reduce frequent I/O operations and improve efficiency.

Definition (BufferedReader): A character input stream that reads text efficiently


using an internal buffer and can read full lines.

Definition (BufferedWriter): A character output stream that writes text efficiently


using an internal buffer.

5.11 PrintWriter
PrintWriter is a convenient character output class that supports printing of text with
methods like print() and println() .

Definition (PrintWriter): A character-output writer that provides convenient


methods for printing formatted text.

Part D: Serialization

5.12 Serialization

Serialization is the process of converting an object into a byte stream so it can be:

saved to a file
sent over a network
stored for later use

Deserialization reconstructs the object.

Definition (Serialization): The process of converting an object into a byte stream for
storage or transmission.

Definition (Deserialization): The process of reconstructing an object from its


serialized byte stream form.

Case Study Example:

In an “online exam system,” a Student object (name, roll, answers) could be serialized and
saved periodically so the exam can be restored after a crash.

Part E: JDBC (Java Database Connectivity)

5.13 JDBC Overview

JDBC is a standard API for connecting Java programs to databases and executing SQL.

Definition (JDBC): Java Database Connectivity (JDBC) is an API that enables Java
applications to connect to databases, execute SQL statements, and process results.

5.14 JDBC-ODBC Bridge

The JDBC-ODBC bridge was an older method to connect JDBC to databases using ODBC
drivers.
Important exam idea:

It acts as a translator between JDBC calls and ODBC calls.


Historically used when native JDBC drivers were not available.

Definition (JDBC-ODBC bridge): A driver mechanism that translates JDBC calls into
ODBC calls to access databases using ODBC drivers.

5.15 The Connectivity Model (JDBC Architecture)

Basic JDBC flow:

1. Load/obtain a driver

2. Create a connection to database

3. Create a statement

4. Execute query/update

5. Process results (for SELECT)

6. Close resources

Core objects:

DriverManager
Connection
Statement / PreparedStatement
ResultSet

Definition (Connection): An object representing an active link between a Java


application and a database.

Definition (Statement): An object used to execute SQL commands against a


database.

Definition (ResultSet): An object that stores and allows traversal of the result
returned by a SELECT query.

5.16 DriverManager

DriverManager manages JDBC drivers and establishes a connection.

Definition (DriverManager): A JDBC class that manages database drivers and


provides methods to establish a connection using a database URL.
5.17 Navigating the ResultSet

ResultSet works like a cursor moving row-by-row.

Common navigation methods (conceptual):

Move to next row


Retrieve column data by name or index

Definition (ResultSet cursor): A pointer that indicates the current row in the
ResultSet during traversal.

Example:

A query returns multiple students; you iterate through each row to print roll number and
marks.

5.18 JDBC Package ([Link])

JDBC core interfaces and classes are in:

[Link]

Definition ([Link] package): A Java package that provides JDBC interfaces and
classes for database connection, SQL execution, and result processing.

5.19 JDBC Exception Classes

Database operations can fail due to:

wrong URL
wrong username/password
SQL syntax error
network failure
missing driver

These failures are represented by SQL exceptions.

Definition (SQLException): An exception that provides information about database


access errors or other SQL-related problems.

5.20 Connecting to a Remote Database

Connecting remotely typically means:


database server is on another machine
connection uses network + credentials

Key requirements:

reachable host/port
correct JDBC URL
correct driver
proper authentication

Case Study Example:

A college “Library Management System” may run the database on a central server.
Multiple lab computers connect remotely to the same database to search books and
issue returns.

Summary (Unit 5)
Java I/O is based on streams, representing a flow of data.
Byte streams ( InputStream/OutputStream ) handle binary data using classes like
FileInputStream , FileOutputStream , and PrintStream .
RandomAccessFile enables reading/writing at any file position using a file pointer.
Character streams ( Reader/Writer ) handle text data; buffering
( BufferedReader/BufferedWriter ) improves performance; PrintWriter simplifies
writing formatted text.
Serialization converts objects to byte streams for storage/transmission.
JDBC allows Java programs to interact with databases using DriverManager ,
Connection , Statement , and ResultSet .
JDBC includes exception handling via SQLException and supports connecting to
local or remote databases.

Practice Questions (Unit 5)


1. What is a stream in Java? Differentiate between byte streams and character
streams with examples.

2. Explain FileInputStream and FileOutputStream . Where are byte streams


preferred over character streams?

3. What is RandomAccessFile ? Explain its advantage with one application scenario.


4. Define serialization and deserialization. Mention one real-life use case of
serialization.

5. Explain JDBC connectivity model. Describe the roles of DriverManager ,


Connection , Statement , and ResultSet .

You might also like