JAVA PROGRAMMING
Student-Friendly Notes
Units I – V | OOP Concepts, Java Basics, Inheritance, Exceptions,
Multithreading, I/O, Event Handling & Swing
Student-Friendly Notes (Units I–V)
Java Programming — Student Notes Page 1
UNIT I: Object-Oriented Thinking and Java Basics
1.1 Need for the OOP Paradigm
Before OOP, programs were written using the procedural paradigm (C, Pascal), where a program is a list of
instructions and functions operate on data that is separate from them. As programs grew larger, this created
problems:
●
Data was not protected — any function could accidentally change any data.
●
Code reuse was difficult — functions were tightly coupled to specific data structures.
●
Maintenance was hard — a small change could break unrelated parts of the program.
Object-Oriented Programming solves this by bundling data and the functions that operate on it into a
single unit called an object. This gives us:
●
Better modeling of real-world entities
●
Data protection through encapsulation
●
Reusability through inheritance
●
Flexibility through polymorphism
1.2 Summary of OOP Concepts
Concept Meaning
A real-world entity having state (data) and
Object
behavior (methods)
A blueprint/template from which objects are
Class
created
Wrapping data and code together, hiding internal
Encapsulation
details
Showing only essential features, hiding
Abstraction
implementation
Inheritance Acquiring properties of one class into another
One interface, many implementations (same
Polymorphism
method behaves differently)
Objects communicate by calling each other's
Message Passing
methods
1.3 Coping with Complexity
Software systems are among the most complex things humans build. OOP helps manage this complexity
through:
Java Programming — Student Notes Page 2
●
Abstraction – focusing on *what* an object does, not *how*
●
Decomposition – breaking a large problem into smaller, manageable classes/objects
●
Hierarchical organization – arranging classes in inheritance trees so common behavior is defined once
●
Encapsulation – hiding internal complexity behind a simple, well-defined interface
1.4 Abstraction Mechanisms
●
Class abstraction – separates the interface (public methods) of a class from its implementation.
●
Data abstraction – hides the internal representation of data (e.g., how a Stack stores elements internally).
●
Procedural abstraction – a method groups a sequence of steps into a single, named operation.
Java supports abstraction through abstract classes and interfaces (covered in Unit II).
1.5 History of Java
●
Java was developed by James Gosling and his team at Sun Microsystems, starting in 1991 under the
project name "Oak" (named after an oak tree outside Gosling's office).
●
It was renamed Java in 1995 and released publicly the same year.
●
Originally designed for embedded consumer electronics, its "write once, run anywhere" philosophy made it
ideal for the emerging internet/web era.
●
Sun Microsystems was acquired by Oracle Corporation in 2010, which now maintains Java.
●
Java's syntax is heavily influenced by C and C++, but it removed complex/unsafe features like pointers and
manual memory management.
1.6 Java Buzzwords
Buzzword Meaning
Easy syntax, no pointers, automatic garbage
Simple
collection
Object-Oriented Almost everything is an object
Compiled bytecode runs on any machine with a
Platform-Independent
JVM ("Write Once, Run Anywhere")
Secure No explicit pointers; runs inside a sandboxed JVM
Strong memory management, exception handling,
Robust
type checking at compile time
Architecture-Neutral Bytecode format doesn't depend on CPU/OS
Same bytecode runs identically on different
Portable
platforms
Multithreaded Built-in support for concurrent execution
Bytecode interpreted by JVM, with Just-In-Time
Interpreted & High Performance
(JIT) compilation for speed
Java Programming — Student Notes Page 3
Buzzword Meaning
Distributed Built-in networking capability ([Link])
Dynamic Can load classes at runtime as needed
1.7 Data Types
Java is a strongly typed language — every variable must have a declared type.
Primitive Data Types (8 total)
Type Size Range/Notes
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes ~ -2.1 billion to 2.1 billion
long 8 bytes Very large integers; suffix L
Single-precision decimal; suffix
float 4 bytes
f
Double-precision decimal
double 8 bytes
(default for decimals)
char 2 bytes Single Unicode character
boolean 1 bit (JVM-dependent) true or false only
Reference (Non-Primitive) Data Types
Objects, arrays, Strings, classes, and interfaces — they store a reference (address) to the actual data, not
the data itself.
1.8 Variables, Scope, and Lifetime
Java has three kinds of variables:
1. Local variables – declared inside a method/block; exist only during that method's execution; must be
initialized before use (no default value). 2. Instance variables – declared inside a class but outside methods;
each object gets its own copy; get default values (0, null, false). 3. Static (class) variables – declared with
the static keyword; shared by all objects of the class; only one copy exists.
class Demo {
int instanceVar; // instance variable
static int staticVar; // static/class variable
void show() {
int localVar = 10; // local variable, scope limited to this method
}
Java Programming — Student Notes Page 4
}
Scope = the region of code where a variable can be accessed. Lifetime = how long the variable exists in
memory.
1.9 Arrays
An array is a fixed-size, indexed collection of elements of the same type.
int[] marks = new int[5]; // declaration + creation
int[] nums = {10, 20, 30, 40}; // declaration with initialization
int[][] matrix = new int[3][3]; // 2D array
●
Index starts at 0.
●
Array length is accessed via .length (not a method, no parentheses).
●
Arrays are objects in Java, stored on the heap.
1.10 Operators, Expressions, and Control Statements
Operators
●
Arithmetic: + - * / %
●
Relational: == != > < >= <=
●
Logical: && || !
●
Bitwise: & | ^ ~ << >> >>>
●
Assignment: = += -= *= /=
●
Ternary: condition ? value1 : value2
Control Statements
●
Selection: if, if-else, switch
●
Iteration: for, while, do-while, enhanced for-each
●
Jump: break, continue, return
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) continue;
[Link](i);
}
1.11 Type Conversion and Casting
●
Implicit (widening) conversion – smaller type automatically converted to a larger type (no data loss): int
→ long → float → double.
●
Explicit (narrowing) casting – larger type manually converted to a smaller type (possible data loss),
requires a cast operator:
double d = 100.04;
int i = (int) d; // explicit narrowing cast, i = 100
1.12 Writing Simple Java Programs
Java Programming — Student Notes Page 5
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
●
The file name must match the public class name ([Link]).
●
main is the entry point: it must be public static void main(String[] args).
●
Compile: javac [Link] → Run: java HelloWorld.
1.13 Classes, Objects, Constructors, Methods
●
A class defines the structure (fields) and behavior (methods) of objects.
●
An object is an instance of a class, created using the new keyword.
●
A constructor initializes an object when it is created; it has the same name as the class and no return
type.
class Student {
String name;
int age;
Student(String name, int age) { // constructor
[Link] = name;
[Link] = age;
}
void display() { // method
[Link](name + " is " + age + " years old");
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student("Asha", 20); // object creation
[Link]();
}
}
1.14 Access Control
Subclass (diff
Modifier Same Class Same Package Everywhere
package)
private ✔ ✘ ✘ ✘
*default* (no
✔ ✔ ✘ ✘
modifier)
protected ✔ ✔ ✔ ✘
public ✔ ✔ ✔ ✔
Java Programming — Student Notes Page 6
1.15 The this Keyword
this refers to the current object. Common uses:
●
Distinguishing instance variables from parameters with the same name ([Link] = name;)
●
Calling one constructor from another in the same class (this(...))
●
Passing the current object as an argument
1.16 Garbage Collection
Java automatically manages memory. The Garbage Collector (GC) reclaims memory used by objects that
no longer have any live references, so programmers don't need to manually free memory (unlike C/C++
free/delete).
●
Objects become eligible for GC when no reference points to them.
●
[Link]() *requests* garbage collection but doesn't guarantee immediate execution.
●
The finalize() method (deprecated in modern Java) used to be called before an object was collected.
1.17 Overloading Methods and Constructors
Method Overloading = multiple methods with the same name but different parameter lists (number, type,
or order of parameters) within the same class. This is compile-time (static) polymorphism.
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}
Constructor Overloading works the same way — a class can have multiple constructors with different
parameter lists.
1.18 Parameter Passing
Java is strictly pass-by-value:
●
For primitives, a *copy of the value* is passed — changes inside the method don't affect the original.
●
For objects, a *copy of the reference (address)* is passed — the method can modify the object's fields, but
reassigning the reference inside the method does not affect the caller's variable.
1.19 Recursion
A method that calls itself to solve a smaller instance of the same problem. Requires a base case to stop the
recursive calls.
int factorial(int n) {
if (n == 0) return 1; // base case
return n * factorial(n - 1); // recursive call
}
1.20 Nested and Inner Classes
Java Programming — Student Notes Page 7
●
Static nested class – declared static inside another class; doesn't need an instance of the outer class.
●
Inner (non-static) class – tied to an instance of the outer class; can access outer class members directly.
●
Local class – defined inside a method.
●
Anonymous class – a class without a name, defined and instantiated in a single expression (often used
with interfaces).
class Outer {
class Inner { // inner class
void msg() { [Link]("Inner class"); }
}
}
1.21 Exploring the String Class
●
Strings in Java are immutable — once created, a String object's content cannot change; any
"modification" creates a new object.
●
String literals are stored in the String pool for memory efficiency.
String s1 = "Hello";
String s2 = new String("Hello");
String s3 = [Link](" World");
[Link](); // length of string
[Link](0); // character at index
[Link](s2); // content comparison
s1 == s2; // reference comparison (false here)
[Link](1,3);
[Link]();
●
Use StringBuffer or StringBuilder for frequently modified strings (mutable, more efficient than repeated
String concatenation). StringBuffer is thread-safe (synchronized); StringBuilder is faster but not
thread-safe.
Java Programming — Student Notes Page 8
UNIT II: Inheritance, Packages, and Interfaces
2.1 Hierarchical Abstractions
Inheritance lets us organize classes in a hierarchy — general (base) classes at the top, specialized (derived)
classes below, each adding or refining behavior. This mirrors how we naturally classify things (e.g., Vehicle
→ Car → SportsCar).
2.2 Base Class, Subclass, Subtype, Substitutability
●
Base class (superclass) – the class being inherited from.
●
Subclass (derived class) – the class that inherits from the base class using extends.
●
Subtype – a subclass is considered a *subtype* of its superclass; an object of the subclass can be used
wherever the superclass is expected.
●
Substitutability (Liskov Substitution Principle) – a subclass object should be usable in place of a
superclass object without breaking the program's correctness.
class Animal {
void eat() { [Link]("This animal eats food"); }
}
class Dog extends Animal {
void bark() { [Link]("Dog barks"); }
}
2.3 Forms of Inheritance
Form Description
Subclass adds specific behavior to a general
Specialization
superclass (e.g., Bird → Sparrow)
Superclass declares behavior (often abstract) that
Specification
subclasses must implement
Subclass reuses superclass code for
Construction
convenience, without a true "is-a" relationship
Subclass adds new, unrelated functionality to the
Extension
superclass
Subclass restricts/limits some behavior inherited
Limitation
from the superclass
Subclass combines behaviors from multiple
Combination sources (Java uses interfaces for this, since
multiple class inheritance isn't allowed)
2.4 Benefits and Costs of Inheritance
Java Programming — Student Notes Page 9
Benefits:
●
Code reusability — common code written once in the superclass
●
Easier maintenance — changes in superclass propagate to subclasses
●
Supports polymorphism and extensibility
Costs:
●
Tight coupling between superclass and subclass (changes to superclass can break subclasses)
●
Can lead to deep, hard-to-understand hierarchies if overused
●
Breaks encapsulation to some extent (subclass depends on superclass internals)
2.5 Member Access Rules in Inheritance
●
private members of the superclass are not inherited (not directly accessible in the subclass).
●
protected and public members are accessible in the subclass.
●
Default (package-private) members are accessible only if the subclass is in the same package.
2.6 The super Keyword
Used inside a subclass to refer to its immediate superclass:
class Animal {
Animal() { [Link]("Animal constructor"); }
void sound() { [Link]("Some sound"); }
}
class Dog extends Animal {
Dog() {
super(); // calls superclass constructor (must be first statement)
[Link]("Dog constructor");
}
void sound() {
[Link](); // calls superclass version of the method
[Link]("Bark");
}
}
2.7 The final Keyword with Inheritance
●
final class → cannot be subclassed (e.g., String).
●
final method → cannot be overridden by subclasses.
●
final variable → becomes a constant; value cannot be changed once assigned.
2.8 Polymorphism
Polymorphism = "many forms" — the same method call behaves differently depending on the object.
Method Overriding (Runtime Polymorphism)
A subclass provides a specific implementation of a method already defined in its superclass, with the same
name, return type, and parameters.
class Shape {
Java Programming — Student Notes Page 10
void area() { [Link]("Area of shape"); }
}
class Circle extends Shape {
@Override
void area() { [Link]("Area = πr²"); }
}
Shape s = new Circle(); // superclass reference, subclass object
[Link](); // calls Circle's area() — decided at RUNTIME
Rules for overriding: same signature, same or covariant return type, access modifier can't be more restrictive,
cannot override static or final methods.
Overloading vs Overriding
Overloading Overriding
Same class Superclass–subclass
Different parameter list Same signature
Resolved at compile time Resolved at runtime
Also called static/early binding Also called dynamic/late binding
Abstract Classes
A class declared with abstract that cannot be instantiated and may contain abstract methods (no body)
that subclasses must implement.
abstract class Shape {
abstract void area(); // no body
void display() { [Link]("I am a shape"); } // concrete method allowed
}
class Square extends Shape {
void area() { [Link]("Area = side * side"); }
}
The Object Class
Every class in Java implicitly extends Object (directly or indirectly) — it is the root of the class hierarchy.
Useful inherited methods include:
●
toString() – string representation of the object
●
equals(Object o) – logical equality comparison
●
hashCode() – integer hash code representation
●
getClass() – returns runtime class information
●
clone() – creates a copy of the object
2.9 Packages
A package is a namespace/folder used to group related classes and interfaces, avoiding name conflicts and
improving organization.
package [Link]; // must be the first statement in the file
Java Programming — Student Notes Page 11
public class Helper { ... }
●
Defining a package: use the package statement; the folder structure must match the package name.
●
Creating and accessing: classes in the same package can access each other without importing.
●
CLASSPATH – an environment variable that tells the JVM/compiler where to look for .class files and
packages.
●
Importing packages:
import [Link]; // import a single class
import [Link].*; // import all classes in the package
2.10 Interfaces vs Classes
Interface Class
Only method signatures (until Java 8; now allows
Full implementation
default/static methods)
All fields are implicitly public static final Fields can be any type
A class can implement multiple interfaces A class can extend only one class
Cannot have constructors Can have constructors
Used to achieve full abstraction & multiple
Used to model actual objects
inheritance of type
2.11 Defining, Implementing, and Applying Interfaces
interface Drawable {
void draw(); // implicitly public & abstract
}
class Circle implements Drawable {
public void draw() {
[Link]("Drawing a circle");
}
}
●
A class implements an interface using the implements keyword and must define all its abstract methods
(unless the class itself is abstract).
●
A class can implement multiple interfaces: class A implements X, Y, Z { ... }
2.12 Variables in Interfaces
All variables declared in an interface are implicitly public static final — i.e., constants that must be
initialized at declaration and cannot be changed.
2.13 Extending Interfaces
Java Programming — Student Notes Page 12
An interface can extend one or more other interfaces using extends (interfaces support multiple inheritance,
unlike classes):
interface A { void methodA(); }
interface B { void methodB(); }
interface C extends A, B { // C inherits abstract methods from both A and B
void methodC();
}
Java Programming — Student Notes Page 13
UNIT III: Exception Handling and Multithreading
3.1 Concepts of Exception Handling
An exception is an unwanted/unexpected event that disrupts the normal flow of a program's instructions
(e.g., dividing by zero, accessing an invalid array index). Java's exception handling mechanism lets a
program detect and gracefully respond to such errors instead of crashing.
3.2 Benefits of Exception Handling
●
Separates error-handling code from regular business logic (cleaner code)
●
Allows propagating errors up the call stack to a handler that knows how to deal with them
●
Enables graceful recovery instead of abrupt program termination
●
Groups and differentiates error types clearly
3.3 Termination vs Resumptive Models
●
Termination model (used by Java) – once an exception is thrown, control cannot return to the point
where the exception occurred; the block is considered unrecoverable and execution resumes after the
try-catch.
●
Resumptive model – the handler could, in theory, fix the problem and resume execution from the exact
point the exception occurred. Java does not use this model (some older languages did).
3.4 Exception Hierarchy
Throwable
/ \
Error Exception
(serious, not / \
recoverable, RuntimeException Other Exceptions
e.g. OutOfMemory) (unchecked) (checked, e.g. IOException)
●
Error – serious problems (e.g., OutOfMemoryError, StackOverflowError) that applications normally
shouldn't try to catch.
●
Exception – conditions a program might want to catch and handle.
●
Checked exceptions – checked at compile time; must be either caught or declared with throws (e.g.,
IOException, SQLException).
●
Unchecked exceptions (RuntimeException) – checked only at runtime; not mandatory to catch (e.g.,
NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException).
3.5 try, catch, throw, throws, finally
try {
int result = 10 / 0; // may throw an exception
} catch (ArithmeticException e) { // catches a specific exception type
[Link]("Cannot divide by zero: " + [Link]());
} finally {
[Link]("This always executes"); // cleanup code
}
Java Programming — Student Notes Page 14
●
try – block of code that might throw an exception.
●
catch – handles a specific type of exception; multiple catch blocks can follow one try.
●
throw – used to explicitly throw an exception object: throw new IllegalArgumentException("bad
input");
●
throws – declared in a method signature to indicate the method might throw a checked exception, passing
responsibility to the caller: void readFile() throws IOException { ... }
●
finally – block that always executes, whether or not an exception occurred (used for cleanup like closing
files/connections).
3.6 Built-in Exceptions (common examples)
Exception Cause
ArithmeticException Division by zero
NullPointerException Using a reference that points to null
ArrayIndexOutOfBoundsException Accessing an invalid array index
ClassCastException Invalid type casting
NumberFormatException Invalid string-to-number conversion
IOException Input/output failure (checked)
FileNotFoundException File doesn't exist (checked)
3.7 User-Defined Exceptions
Create a custom exception by extending Exception (checked) or RuntimeException (unchecked):
class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
double balance;
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance)
throw new InsufficientFundsException("Not enough balance!");
balance -= amount;
}
}
3.8 Multithreading vs Multitasking
●
Multitasking – the OS runs multiple programs (processes) concurrently, each with its own memory
space.
Java Programming — Student Notes Page 15
●
Multithreading – multiple threads run concurrently within a single program/process, sharing the same
memory space. Threads are lighter-weight than processes, so context-switching is faster and
communication between threads is easier.
3.9 Thread Life Cycle
New → Runnable → Running → (Waiting/Blocked/Timed Waiting) → Terminated
1. New – thread object created, not yet started. 2. Runnable – after calling start(), thread is ready to run,
waiting for CPU. 3. Running – thread scheduler picks it for execution. 4. Blocked/Waiting – thread is
paused (e.g., waiting for a lock, sleeping, or waiting on another thread). 5. Terminated (Dead) – thread has
finished execution.
3.10 Creating Threads
Method 1 — Extending Thread:
class MyThread extends Thread {
public void run() { [Link]("Thread running"); }
}
MyThread t = new MyThread();
[Link](); // never call run() directly — start() creates a new call stack
Method 2 — Implementing Runnable:
class MyTask implements Runnable {
public void run() { [Link]("Task running"); }
}
Thread t = new Thread(new MyTask());
[Link]();
*(Implementing Runnable is generally preferred since Java doesn't support multiple class inheritance — this
leaves the class free to extend another class if needed.)*
3.11 Thread Priorities
Every thread has a priority (1 to 10):
●
Thread.MIN_PRIORITY = 1
●
Thread.NORM_PRIORITY = 5 (default)
●
Thread.MAX_PRIORITY = 10
Higher-priority threads are *generally* given preference by the scheduler, but this is not guaranteed (depends
on the JVM/OS).
3.12 Synchronizing Threads
When multiple threads access shared data, race conditions can occur. The synchronized keyword ensures
only one thread at a time can execute a synchronized block/method on a given object (mutual exclusion
using an intrinsic lock/monitor).
class Counter {
int count = 0;
Java Programming — Student Notes Page 16
synchronized void increment() { // only one thread at a time
count++;
}
}
3.13 Inter-Thread Communication
Threads can coordinate using Object class methods:
●
wait() – causes the current thread to release the lock and wait until notified.
●
notify() – wakes up one waiting thread.
●
notifyAll() – wakes up all waiting threads.
Commonly used to solve the classic Producer-Consumer problem.
3.14 Thread Groups
A ThreadGroup allows multiple threads to be treated as a single unit — useful for applying operations (like
setting priority or interrupting) to a whole group of related threads at once.
3.15 Daemon Threads
●
Daemon threads run in the background providing services to user threads (e.g., Garbage Collector).
●
The JVM exits automatically once all non-daemon (user) threads finish, regardless of daemon threads still
running.
●
Set using [Link](true); before calling start().
Java Programming — Student Notes Page 17
UNIT IV: Packages, I/O, and Event Handling
4.1 Recap: String and Object Class
(See Unit I §1.21 for String, and Unit II §2.8 for the Object class — both are foundational to [Link] and
[Link] usage.)
4.2 The [Link] Package
Provides utility classes, most notably the Collections Framework:
Interface/Class Purpose
Resizable array, allows duplicates, maintains
ArrayList
insertion order
Doubly-linked list implementation of List and
LinkedList
Deque
HashSet Unordered collection with no duplicates
TreeSet Sorted set (no duplicates)
HashMap Key-value pairs, no guaranteed order
TreeMap Key-value pairs, sorted by key
Iterator Used to traverse a collection sequentially
Scanner Reads formatted input from console/files
Date, Calendar Date and time handling
Random Generates pseudo-random numbers
import [Link].*;
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
for (String fruit : list) [Link](fruit);
4.3 The [Link] Package
Handles Input/Output operations through streams.
●
Byte streams – handle raw binary data, base classes InputStream / OutputStream (e.g.,
FileInputStream, FileOutputStream).
●
Character streams – handle text/Unicode data, base classes Reader / Writer (e.g., FileReader,
FileWriter, BufferedReader).
import [Link].*;
Java Programming — Student Notes Page 18
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
Common classes: File (represents file/directory paths), FileReader/FileWriter,
BufferedReader/BufferedWriter, PrintWriter, ObjectInputStream/ObjectOutputStream (for
serialization).
4.4 Event Handling — Concepts
Java GUI programs (AWT/Swing) follow the Delegation Event Model:
●
Event – an object that describes a state change (e.g., a button click, a key press).
●
Event Source – the GUI component that generates the event (e.g., a JButton).
●
Event Listener – an object that is notified when an event occurs and contains the code to handle it.
●
Event Class – encapsulates information about the event (e.g., ActionEvent, MouseEvent, KeyEvent).
4.5 The Delegation Event Model
1. The event source generates an event object. 2. The event object is passed to all registered listeners. 3.
Each listener's corresponding method is invoked to handle the event. 4. A listener registers itself with the
source using an addXxxListener() method.
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});
4.6 Handling Mouse and Keyboard Events
●
MouseListener – handles mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited.
●
MouseMotionListener – handles mouseDragged, mouseMoved.
●
KeyListener – handles keyPressed, keyReleased, keyTyped.
[Link](new KeyAdapter() {
public void keyPressed(KeyEvent e) {
[Link]("Key pressed: " + [Link]());
}
});
4.7 Adapter Classes
Listener interfaces (like MouseListener) require implementing all their methods, even ones you don't need.
Adapter classes (like MouseAdapter, KeyAdapter, WindowAdapter) provide empty default
implementations of every method, so you only need to override the ones you actually care about.
4.8 Graphics and Layout Managers
Java Programming — Student Notes Page 19
A Layout Manager automatically arranges components within a container instead of using fixed pixel
coordinates.
Layout Manager Behavior
Divides the container into 5 regions: North, South,
BorderLayout
East, West, Center (default for JFrame)
Arranges components in a rectangular grid of
GridLayout
equal-sized cells
Places components left-to-right, wrapping to the
FlowLayout
next line as needed (default for JPanel)
Stacks components like a deck of cards, showing
CardLayout
one at a time (useful for wizards/tabs)
Most flexible; arranges components in a grid with
GridBagLayout variable-sized cells and fine control via
GridBagConstraints
[Link](new BorderLayout());
[Link](new JButton("North"), [Link]);
[Link](new JButton("Center"), [Link]);
Java Programming — Student Notes Page 20
UNIT V: Swing Programming
5.1 Introduction to Swing
Swing is Java's advanced GUI toolkit (part of the JFC – Java Foundation Classes), built on top of AWT.
Unlike AWT, Swing components are written entirely in Java ("lightweight" components), giving them a
consistent look across platforms and far richer functionality.
5.2 Limitations of AWT
●
AWT components are heavyweight — each maps to a native OS GUI component, so appearance varies
across platforms.
●
Limited set of components (no tables, trees, tabbed panes, etc.)
●
Cannot easily customize the look and feel.
●
Poor performance and flexibility compared to Swing.
5.3 MVC Architecture
Swing components internally follow the Model-View-Controller (MVC) pattern:
●
Model – holds the component's data/state (e.g., the text in a text field, whether a checkbox is selected).
●
View – the visual representation shown on screen.
●
Controller – handles user input and updates the model, which in turn updates the view.
This separation allows the same data model to be displayed in different ways and makes components more
flexible ("pluggable look and feel").
5.4 Components and Containers
●
A Component is any visible GUI element (button, label, text field, etc.) — base class [Link].
●
A Container is a component that can hold other components (e.g., JPanel, JFrame) — base class
[Link].
5.5 Exploring Swing Components
Component Purpose
Top-level window with a title bar, border, and
JFrame
(optionally) menu bar
Base class for most Swing components (adds
JComponent
tooltips, borders, etc.)
JLabel Displays a short, non-editable text/icon
Loads and displays image files (used with labels,
ImageIcon
buttons, etc.)
Java Programming — Student Notes Page 21
Component Purpose
JTextField Single-line editable text input
JButton Clickable push button
JCheckBox On/off toggle box; multiple can be selected
Mutually exclusive selection (grouped via
JRadioButton
ButtonGroup)
JList Displays a scrollable list of items
JComboBox Drop-down list of selectable items
JTabbedPane Organizes components into selectable tabs
JScrollPane Adds scroll bars around another component
JTree Displays hierarchical (tree-structured) data
JTable Displays data in a rows-and-columns grid
import [Link].*;
public class SimpleGUI {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Swing App");
JButton button = new JButton("Click Me");
[Link](button);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
5.6 Menu Basics
Class Purpose
The horizontal bar at the top of a JFrame that
JMenuBar
holds menus
A drop-down menu placed on the menu bar (e.g.,
JMenu
"File", "Edit")
A single selectable item within a menu (e.g.,
JMenuItem
"Open", "Save")
A menu item with a checkbox — can be toggled
JCheckBoxMenuItem
on/off
Java Programming — Student Notes Page 22
Class Purpose
A menu item with mutually exclusive selection
JRadioButtonMenuItem
(grouped via ButtonGroup)
A thin dividing line used to visually group related
JSeparator
menu items
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
[Link](openItem);
[Link](saveItem);
[Link]();
[Link](fileMenu);
[Link](menuBar);
5.7 Creating Popup Menus
A JPopupMenu appears at a specific location (usually on a right-click) rather than being attached to a menu
bar.
JPopupMenu popup = new JPopupMenu();
[Link](new JMenuItem("Cut"));
[Link](new JMenuItem("Copy"));
[Link](new JMenuItem("Paste"));
[Link](new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if ([Link]())
[Link]([Link](), [Link](), [Link]());
}
});
Quick Revision Checklist
■ Unit I: OOP need, buzzwords, data types, classes/objects, this, overloading, recursion, String
■ Unit II: Inheritance forms, super/final, overriding vs overloading, abstract classes, interfaces
■ Unit III: Exception hierarchy, try/catch/finally, thread life cycle, synchronization
■ Unit IV: Collections ([Link]), streams ([Link]), delegation event model, layout managers
■ Unit V: Swing vs AWT, MVC, Swing components, menus, popup menus
Java Programming — Student Notes Page 23