DIPLOMA IN COMPUTER ENGINEERING • 5TH SEMESTER
Java Programming
CSE-3-506-T • 2 Credits • 30 Learning Hours
A presenter's guide for learners coming from C and C++
BEFORE WE BEGIN
Welcome
▸ You already think like a programmer — you know variables, loops, functions, and how a compiler
turns source code into a running program.
▸ Java keeps almost all of that syntax. What changes is the philosophy: everything lives inside a
class, memory is managed for you, and the same compiled code runs on any machine.
▸ This deck calls out every place Java departs from C/C++ habits, and gives you a hands-on task
right after each new idea.
▸ Look for the green PRACTICE NOW slides — stop and type the code yourself before moving on.
Java Programming • CSE-3-506-T
SYLLABUS
Course Objectives
▸ Understand the fundamentals of Java and object-oriented programming concepts.
▸ Develop Java programs using classes, objects, methods, constructors, arrays, and strings.
▸ Apply inheritance, polymorphism, abstraction, exception handling, and packages.
▸ Build console-based and basic event-driven (GUI) applications.
▸ Develop problem-solving skills for real-world Java applications.
Java Programming • CSE-3-506-T
Six Units, Thirty Hours
Unit Topic Hours
1 Introduction to Java Programming 5
2 Classes and Objects 5
3 Strings and Collection Basics 5
4 Exception Handling and File Handling 5
5 Java GUI Programming 5
6 Java Database Connectivity and 5
Applications
Java Programming • CSE-3-506-T
Scheme of Examination
Component Max. Marks Weightage
End of Semester Examination (EoSE) 100 70%
Continuous Assessment (CA) 100 30%
Minimum pass requirement 40% separately in EoSE and CA —
Java Programming • CSE-3-506-T
R E F E R E N C E M AT E R I A L
Recommended Books & References
▸ Herbert Schildt — Java: The Complete Reference, McGraw Hill, 11th Ed., 2019
▸ E. Balagurusamy — Programming with Java: A Primer, McGraw Hill, 6th Ed., 2019
▸ Y. Daniel Liang — Introduction to Java Programming and Data Structures, Pearson, 12th Ed., 2020
▸ Cay S. Horstmann — Core Java Volume I: Fundamentals, Pearson, 11th Ed., 2019
▸ Deitel & Deitel — Java: How to Program, Pearson, 11th Ed., 2018
Java Programming • CSE-3-506-T
READING THE SLIDES
How To Use This Deck
▸ Compare panels
▸ Side-by-side slides map a Java idea onto the equivalent C/C++ idea, so you can anchor new syntax
to what you already know.
▸ Code slides
▸ Short, runnable snippets — type them into a real editor, don't just read them.
▸ Practice Now slides (green)
▸ A concrete micro-exercise, placed right after the concept that enables it. Do it before the next
slide.
▸ Unit check slides (dark)
▸ A short set of questions to test yourself before moving to the next unit.
Java Programming • CSE-3-506-T
UNIT 1
Introduction to Java
Programming
5 hours • Course Content
→ Java, features & applications
→ JVM, JRE, JDK
→ Program structure, variables, operators
→ I/O, decisions, loops, arrays
→ OOP concepts — a first look
UNIT 1
What Is Java?
▸ A general-purpose, object-oriented, compiled-and-interpreted language released by Sun
Microsystems in 1995 (now owned by Oracle).
▸ Designed around one promise: “Write Once, Run Anywhere” (WORA).
▸ C and C++ compile straight to machine code for one platform; Java compiles to an intermediate
form called bytecode that runs on any device with a JVM.
▸ You will recognise most of the syntax immediately — curly braces, semicolons, if/for/while —
Java's syntax is a direct descendant of C++.
Java Programming • CSE-3-506-T UNIT 1
Java vs. C / C++ — The Big Picture
C / C++ Java
• Compiles to native machine code for one • Compiles to bytecode, run by the JVM on any
OS/CPU platform
• Manual memory management (malloc/free, • Automatic memory management via Garbage
new/delete) Collection
• Supports pointers and pointer arithmetic • No pointers exposed to the programmer
• Multiple inheritance of classes (C++) • Single inheritance of classes; multiple interfaces
instead
• Procedural code allowed outside any class
• Every line of code lives inside a class
• Header files + separate compilation units
• One .java file per public class, package-based
organisation
Java Programming • CSE-3-506-T UNIT 1
W H Y JAVA?
Key Features of Java
▸ Simple
▸ Removed pointers, operator overloading and multiple class inheritance from C++.
▸ Object-Oriented
▸ Almost everything is an object; encourages reusable, modular design.
▸ Platform Independent
▸ Bytecode + JVM — the same .class file runs on Windows, Linux, macOS.
▸ Robust & Secure
▸ Strong compile-time checking, no explicit pointers, runtime exception handling, a security
manager and class-loader sandbox.
Java Programming • CSE-3-506-T UNIT 1
W H Y JAVA?
More Key Features
▸ Multithreaded
▸ Built-in language support for concurrent tasks via the Thread class.
▸ Architecture-Neutral & Portable
▸ No implementation-dependent data type sizes (an int is always 32 bits).
▸ High Performance
▸ Just-In-Time (JIT) compilation converts hot bytecode to native code at run time.
▸ Distributed
▸ Networking libraries built into the standard library from day one.
Java Programming • CSE-3-506-T UNIT 1
A P P L I C AT I O N S
Where Java Is Used
▸ Enterprise back-end systems — banking, insurance, e-commerce (Java EE / Spring)
▸ Android mobile applications
▸ Large-scale web applications and REST APIs
▸ Embedded and IoT devices
▸ Big-data tooling — Hadoop, Kafka, and much of the Apache ecosystem are written in Java
▸ Desktop utilities and enterprise tools using Swing/JavaFX
Java Programming • CSE-3-506-T UNIT 1
JDK, JRE and JVM — Who Contains Whom
JDK JRE JVM
Java Development Kit: compiler (javac), Java Runtime Environment: JVM + core class Java Virtual Machine: loads bytecode,
debugger, tools + JRE. What you install to libraries. What you need to run Java. verifies it, and executes it on the real
write Java.
→ → machine.
Think of it as three concentric boxes: JDK ⊇ JRE ⊇ JVM. C/C++ has no equivalent — gcc/g++ produces a
native binary directly; there is nothing left to “run inside”.
Java Programming • CSE-3-506-T UNIT 1
From Source Code To Output
[Link] javac [Link] JVM (java) Output
Source code you write Java compiler checks Platform-independent Interprets / JIT- Runs on Windows,
→ syntax & types
→ bytecode
→ compiles bytecode
→ Linux or macOS
unchanged
Compare with C: gcc file.c compiles straight to an .exe / [Link] tied to that OS and CPU — you must recompile
for every target platform.
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Set Up Your Toolchain
✓ Install a JDK (Java 17 or later) and confirm with: java -version and javac -version
✓ Pick an editor — VS Code, IntelliJ IDEA Community, or even a plain text editor + terminal.
✓ Create a folder for this course; every exercise in this deck will live there as one .java file per
program.
Java Programming • CSE-3-506-T UNIT 1
Structure of a Java Program
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, Java!");
}
}
▸ The file name MUST match the public class name exactly: [Link].
▸ main is the entry point, exactly like int main() in C — but it must sit inside a class and is always public static void.
▸ String[] args is the same idea as C's (int argc, char *argv[]).
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Compile and Run Your First Program
✓ Type the HelloWorld program above exactly, save as [Link].
✓ Compile: javac [Link] — this produces [Link].
✓ Run: java HelloWorld — note you run the class name, not the file name and not the .class
extension.
✓ Change the printed message and repeat the compile/run cycle.
Java Programming • CSE-3-506-T UNIT 1
F U N D A M E N TA L S
Variables and Identifiers
▸ Declaration syntax is identical to C/C++: type name = value;
▸ Java has no separate declaration-only int x; ambiguity issue — local variables must be initialised
before use, and the compiler enforces this (definite assignment).
▸ Identifiers: letters, digits, _ and $, cannot start with a digit, case-sensitive, no length limit.
▸ Java naming convention: camelCase for variables/methods, PascalCase for classes, ALL_CAPS for
constants.
Java Programming • CSE-3-506-T UNIT 1
Primitive Data Types
Type Size Example Same as C/C++?
byte 8-bit byte b = 10; no direct equivalent
(closest: signed char)
short 16-bit short s = 200; same as C short
int 32-bit, always int x = 42; C int size varies by platform
— Java's is fixed
long 64-bit long n = 123L; same idea as C long long
float 32-bit IEEE754 float f = 3.5f; same as C float
double 64-bit IEEE754 double d = 3.14; same as C double
char 16-bit Unicode char c = 'A'; C char is 8-bit ASCII; Java
char is 16-bit Unicode
C has no real boolean
boolean true/false only boolean ok = true; (0/non-zero); Java's is a
distinct type
Java Programming • CSE-3-506-T UNIT 1
TYPE CONVERSION
Type Casting
▸ Widening (implicit): byte → short → int → long → float → double — no data loss, no cast needed,
same as C's automatic promotion.
▸ Narrowing (explicit): must cast manually, e.g. int i = (int) 3.99; // i becomes 3
▸ Unlike C, Java never silently converts an int to a boolean or vice-versa — if (x) is a compile error
unless x is boolean.
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Declare and Cast
✓ Declare one variable of each primitive type with a sensible value.
✓ Divide an int by another int and print the result — notice integer division, same as C.
✓ Now cast one operand to double before dividing and compare the output.
Java Programming • CSE-3-506-T UNIT 1
O P E R AT O R S
Operators — Mostly Familiar Territory
▸ Arithmetic: + - * / % — identical to C/C++, including % on integers.
▸ Relational: == != > < >= <= — but == on objects compares references, not content (more in
Unit 3).
▸ Logical: && || ! — short-circuit evaluation, exactly like C/C++.
▸ Assignment & compound assignment: = += -= *= /= %=
▸ Bitwise: & | ^ ~ << >> and Java adds >>> (unsigned right shift, no equivalent in C).
▸ Ternary: condition ? a : b — identical to C/C++.
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Operator Warm-Up
✓ Write a program that reads two integers and prints the results of +, -, *, /, and % on them.
✓ Try the bitwise >>> operator on a negative number and compare it to >>.
✓ Rewrite an if/else you would write in C using Java's ternary operator.
Java Programming • CSE-3-506-T UNIT 1
Console I/O — The First Real Difference
C / C++ Java ([Link])
• scanf("%d", &age); • Scanner sc = new Scanner([Link]);
• printf("Age: %d\n", age); • int age = [Link]();
• cin >> age; • [Link]("Age: " + age);
• cout << "Age: " << age << endl; • No format specifiers — use + to build strings.
• Format specifiers (%d, %s…) must match the • No addresses/pointers — the method call itself
variable type exactly. returns the value.
• Pass the address (&) of the variable to scanf. • Scanner also gives you nextLine(), nextDouble(),
next(), etc.
Java Programming • CSE-3-506-T UNIT 1
Reading Input With Scanner
import [Link];
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();
[Link]("Sum = " + (a + b));
}
▸ }import brings in a class from a package, similar in spirit to #include but for compiled classes rather than text
headers.
▸ [Link] vs println: print stays on the same line, println adds a newline.
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Scanner Practice
✓ Write a program that reads your name (nextLine) and age (nextInt) and prints a greeting
sentence.
✓ Watch out: calling nextInt() then nextLine() immediately after can capture a stray newline —
look up why and fix it.
✓ Extend the AddTwoNumbers program to also print the product and average of the two
numbers.
Java Programming • CSE-3-506-T UNIT 1
Decision Making — if / else / switch
C / C++ Java
• if (x > 0) { … } else { … } • if (x > 0) { … } else { … } — identical syntax.
• switch(x) { case 1: … break; default: … } • switch(x) { case 1 -> …; default -> …; } —
modern arrow form, or classic colon form.
• switch works only on int/char/enum in classic
C; strings need if/else chains. • switch also works directly on String and enum
values.
• Fall-through happens unless you add break.
• Same fall-through rule applies to the classic
colon form — the arrow form does not fall
through.
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Decisions Exercise
✓ Write a grading program: read marks and print a grade using if/else if/else.
✓ Rewrite the same logic using a switch on the tens-digit of the marks.
✓ Try a switch statement directly on a String day-of-week value.
Java Programming • CSE-3-506-T UNIT 1
Loops — Same Three, Plus One New Friend
C / C++ Java
• for (int i = 0; i < n; i++) { … } • for (int i = 0; i < n; i++) { … } — identical.
• while (condition) { … } • while (condition) { … } — identical.
• do { … } while (condition); • do { … } while (condition); — identical.
• No built-in “for each” in C; C++11 added range- • for (int x : array) { … } — the enhanced for-each
based for(auto x : arr). loop, very close to C++11's version.
Java Programming • CSE-3-506-T UNIT 1
LOOPS
break, continue and Loop Control
▸ break exits the nearest enclosing loop or switch — identical to C/C++.
▸ continue skips to the next iteration — identical to C/C++.
▸ Java adds labelled break/continue for jumping out of nested loops, e.g. outer: for(...) { for(...)
{ break outer; } } — C/C++ has no equivalent (only goto).
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Loop Drills
✓ Print a multiplication table (1–10) using a for loop.
✓ Sum digits of a number using a while loop, exactly as you would in C.
✓ Use a labelled break to exit two nested loops early when a target value is found in a 2D grid.
Java Programming • CSE-3-506-T UNIT 1
Arrays — Familiar Shape, Safer Behaviour
C / C++ Java
• int arr[10]; // fixed at compile time, on the • int[] arr = new int[10]; // always on the heap
stack
• int[] arr = {1, 2, 3}; // literal initialisation
• int *arr = malloc(n * sizeof(int)); // dynamic
• Bounds are checked at run time — arr[15]
• No automatic bounds checking — reading throws ArrayIndexOutOfBoundsException
arr[15] on a size-10 array is undefined instead of corrupting memory.
behaviour.
• [Link] gives the size directly; no pointer
• Array name decays to a pointer; pointer arithmetic exists.
arithmetic works.
Java Programming • CSE-3-506-T UNIT 1
Working With Arrays
int[] marks = {78, 85, 92, 60, 74};
int total = 0;
for (int i = 0; i < [Link]; i++) {
total += marks[i];
}
[Link]("Average = " + (total / (double) [Link]));
// 2D array — same idea as C's int grid[3][3]
int[][] grid = new int[3][3];
▸ grid[1][2]
[Link] is a = 9;not a function call — no parentheses.
field,
▸ 2D arrays in Java are really “arrays of arrays”, so each row could even have a different length (a jagged array) — not
possible with a plain C 2D array.
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Array Practice
✓ Store 10 integers in an array, then find the maximum and minimum values.
✓ Reverse an array in place, the same way you would in C.
✓ Create a 3x3 2D array, fill it with values, and print it as a grid using nested loops.
Java Programming • CSE-3-506-T UNIT 1
P R E V I E W — C O V E R E D F U L LY I N U N I T 2
A First Look at Object-Oriented Concepts
▸ Class
▸ a blueprint — like a C struct, but it can also hold functions (methods).
▸ Object
▸ a concrete instance of a class, created on the heap with new.
▸ Encapsulation
▸ bundling data and the methods that act on it, hiding internals behind access modifiers.
▸ Inheritance
▸ a class acquiring fields/methods from another class.
▸ Polymorphism
▸ the same method call behaving differently depending on the object.
▸ We only name these ideas here — Unit 2 is where you'll actually write classes and objects.
Java Programming • CSE-3-506-T UNIT 1
UNIT 1 CHECK
Before You Move On…
1. What does WORA stand for, and which two pieces make it possible?
2. Put JDK, JRE and JVM in order from broadest to narrowest.
3. Why does Java define int as always 32 bits, unlike C?
4. What exception do you get from reading past the end of an array, and why doesn't C give
you one?
5. Write the one-line Scanner call to read a double from the keyboard.
6. What is the difference between a labelled break and a normal break?
Java Programming • CSE-3-506-T UNIT 1
Operator Precedence — A Quick Reference
Category Operators Associativity
Postfix expr++ expr-- left to right
Unary ++expr --expr + - ! ~ right to left
Multiplicative * / % left to right
Additive + - left to right
Relational < > <= >= instanceof left to right
Equality == != left to right
Logical AND / OR && / || left to right
Assignment = += -= *= /= right to left
Java Programming • CSE-3-506-T UNIT 1
Increment / Decrement — Same Trap as C
C / C++ Java
• int i = 5; int a = i++ + ++i; // exact same • int i = 5; int a = i++ + ++i; // identical rules to C
evaluation-order subtleties — a becomes 12
• Pre-increment (++i) changes the value before • Same pre/post distinction, same operator, same
it's used in the expression. behaviour.
• Post-increment (i++) uses the current value, • One difference: Java defines evaluation order
then changes it. left-to-right strictly, removing some of C's
undefined-behaviour corner cases.
If you're comfortable with ++/-- in C, you already know it fully in Java.
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Precedence and Increment Practice
✓ Predict the output of int i = 5; int a = i++ + ++i; [Link](a + " " + i); — then run it to
check.
✓ Write an expression mixing && and || and add parentheses to make the precedence explicit,
then remove them and confirm the result is unchanged.
Java Programming • CSE-3-506-T UNIT 1
Command-Line Arguments
public class Greet {
public static void main(String[] args) {
if ([Link] > 0) {
[Link]("Hello, " + args[0] + "!");
} else {
[Link]("Hello, stranger!");
}
}
}
▸ // Runargswith:
String[] java
plays exactly Greet
the role of C'sAsha
argv, minus argc — [Link] replaces argc directly.
▸ Unlike C, args[0] is the FIRST user-supplied argument, not the program name — Java doesn't include the program
name in the array.
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Command-Line Arguments Practice
✓ Write a program that accepts two numbers as command-line arguments and prints their sum.
✓ Remember to convert each String argument with [Link]() before doing arithmetic.
✓ Handle the case where the user supplies fewer than 2 arguments gracefully.
Java Programming • CSE-3-506-T UNIT 1
S TA N D A R D L I B R A R Y
The Math Class — Java's <math.h>
▸ Math is a class full of static methods — call them directly on the class, no object needed:
[Link](16), [Link](2, 10), [Link](-5).
▸ [Link](a, b) and [Link](a, b) work on int, long, float, double.
▸ [Link]() returns a double in [0.0, 1.0) — multiply and cast to get a random int range, e.g.
(int)([Link]() * 6) + 1 for a die roll.
▸ Constants: [Link], Math.E.
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Math Class Practice
✓ Write a program that computes the hypotenuse of a right triangle using [Link] and
[Link].
✓ Simulate rolling a six-sided die 10 times using [Link]() in a loop.
✓ Find the largest of three numbers using [Link] twice.
Java Programming • CSE-3-506-T UNIT 1
SCOPE
Scope and Lifetime of Variables
▸ Local variables (declared inside a method or block) exist only within that block — identical
scoping rules to C/C++.
▸ Java has no global variables — anything that needs to be widely accessible becomes a static field
of some class instead.
▸ Instance fields (declared in a class, outside any method) live as long as their object does, and are
automatically initialised to a default (0, false, null) if you don't set them — unlike C, where an
uninitialised local variable holds garbage.
Java Programming • CSE-3-506-T UNIT 1
Default Values for Fields (Not Local Variables)
Type Default value
int, short, byte, long 0
float, double 0.0
boolean false
char '\u0000'
Any object reference (String, arrays…) null
Java Programming • CSE-3-506-T UNIT 1
PRACTICE NOW
✎
Scope and Defaults Practice
✓ Declare a class field of each primitive type without initialising it, then print all of them from a
method — confirm the defaults shown above.
✓ Try declaring a local variable and using it before assigning a value — read the compiler error
carefully; this is enforced, unlike C.
Java Programming • CSE-3-506-T UNIT 1
UNIT 2
Classes and Objects
5 hours • Course Content
→ Classes, objects & methods
→ Constructors & access modifiers
→ Wrapper classes & encapsulation
→ Inheritance & polymorphism
→ Abstract classes, interfaces & inner classes
From struct to class
C / C++ Java
• struct Student { char name[30]; int roll; float • class Student { String name; int roll; float marks;
marks; }; }
• Functions that act on a struct are written • Methods live inside the class itself, next to the
separately and take the struct as a parameter. data they operate on.
• No access control — every field is public by • Fields can be private, protected, public, or
default. package-private.
• Student s; // stack allocation, no ‘new’ needed • Student s = new Student(); // objects live on
the heap, created with new
Java Programming • CSE-3-506-T UNIT 2
CORE IDEA
Classes and Objects
▸ A class is a template; an object is a real instance built from that template — just like a struct type
versus a struct variable, but richer.
▸ One Java source file may contain many classes, but at most one public class, and its name must
match the file name.
▸ Everything you write — variables, methods, even main — lives inside some class.
Java Programming • CSE-3-506-T UNIT 2
Defining a Class and Creating Objects
class Student {
String name;
int roll;
float marks;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // object created on the heap
[Link] = "Asha";
[Link] = 12;
[Link] = 88.5f;
[Link]([Link] + " scored " + [Link]);
}
▸ new Student() allocates memory and returns a reference — conceptually similar to malloc(sizeof(struct Student))
}
but the compiler manages the size and the deallocation for you.
▸ There is no free()/delete — Java's Garbage Collector reclaims objects nobody refers to anymore.
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Your First Class
✓ Create a Book class with title, author and price fields.
✓ In main, create two Book objects, set their fields, and print both.
✓ Create an array of 3 Book objects and print them all with a loop.
Java Programming • CSE-3-506-T UNIT 2
B E H AV I O U R
Methods
▸ A method is a function defined inside a class — same parameter/return syntax as a C function.
▸ returnType methodName(parameters) { … } — use void for no return value, exactly like C.
▸ Every method call happens through an object (or the class itself for static methods) — there are
no free-floating functions outside classes.
▸ Java is strictly pass-by-value: for objects, the value passed is the reference itself (similar to
passing a pointer by value in C).
Java Programming • CSE-3-506-T UNIT 2
Adding Methods to a Class
class Student {
String name;
int roll;
float marks;
void display() {
[Link](roll + " " + name + " " + marks);
}
boolean isPassing() {
return marks >= 40;
}
▸ }display() and isPassing() can read the object's own fields directly — no need to pass them in, unlike a plain C
function operating on a struct pointer.
▸ Call them as [Link](); and [Link]();
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Method Practice
✓ Add a method calculateGrade() to your Book/Student class that returns a String.
✓ Add a method that takes parameters, e.g. applyDiscount(double percent), and modifies the
object's own field.
✓ Call your methods from main and print the results.
Java Programming • CSE-3-506-T UNIT 2
O B J E C T C R E AT I O N
Constructors
▸ A constructor has the same name as the class and no return type — it runs automatically when
you say new.
▸ Default constructor: if you write none, Java silently supplies a no-argument one (unlike C++
struct/class rules, this always happens unless you define any constructor yourself).
▸ Parameterised constructor: lets you initialise fields at creation time — similar in spirit to a C++
constructor.
▸ Constructor overloading: define several constructors with different parameter lists, exactly like
overloaded functions in C++.
Java Programming • CSE-3-506-T UNIT 2
Constructor Overloading and this
class Student {
String name;
int roll;
Student() { // default
this("Unknown", 0);
}
Student(String name, int roll) { // parameterised
[Link] = name; // 'this' = the current object
[Link] = roll;
}
}
Student s1 = new Student();
▸ [Link] refers to the field; name (right side) refers to the parameter — this resolves the name clash, similar to
Student s2 = new Student("Rahul", 5);
using this-> in a C++ member function.
▸ this(…) calls another constructor of the same class — there is no equivalent shortcut in C.
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Constructor Practice
✓ Give your class two constructors: one default, one that accepts all fields.
✓ Use this(…) inside the default constructor to delegate to the parameterised one.
✓ Create objects both ways and print them to confirm both paths work.
Java Programming • CSE-3-506-T UNIT 2
Access Modifiers
C / C++ Java
• public / private / protected apply per class, • public, private, protected, and default (no
using : sections keyword) apply per member, individually
• friend classes/functions can bypass private • No friend mechanism — default (package-
entirely private) is the closest substitute
• No package concept — only translation units • Packages group related classes; protected also
and headers grants same-package access
• Default struct members are public; default class • All members default to package-private unless
members are private marked otherwise
Java Programming • CSE-3-506-T UNIT 2
Java Access Modifiers At a Glance
Modifier Same class Same package Subclass (other pkg) Everywhere
private yes no no no
default (none) yes yes no no
protected yes yes yes no
public yes yes yes yes
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Encapsulate It
✓ Make every field of your class private.
✓ Add public getX() and setX(value) methods for each field.
✓ Update main to use the getters/setters instead of touching fields directly, and add validation in
a setter (e.g. reject negative price).
Java Programming • CSE-3-506-T UNIT 2
BRIDGING PRIMITIVES AND OBJECTS
Wrapper Classes
▸ Every primitive has an object counterpart: int → Integer, double → Double, char → Character,
boolean → Boolean…
▸ Needed because collections (Unit 3) can only store objects, not primitives.
▸ Autoboxing: Integer x = 5; (int silently wrapped into an Integer)
▸ Auto-unboxing: int y = x; (Integer silently unwrapped back to int)
▸ Useful static helpers: [Link]("42"), [Link]("3.14") — the Java equivalent
of C's atoi/atof.
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Wrapper Class Practice
✓ Read a number as a String using Scanner's next(), then convert it with [Link].
✓ Create an Integer variable from an int literal and confirm autoboxing with [Link].
✓ Look up Integer.MAX_VALUE and Integer.MIN_VALUE and print them.
Java Programming • CSE-3-506-T UNIT 2
DESIGN PRINCIPLE
Encapsulation, Revisited
▸ Encapsulation = private fields + public getters/setters that control access.
▸ Benefits: you can add validation, logging, or change the internal representation later without
breaking calling code — the same motivation as making C struct fields opaque behind accessor
functions in a .h/.c pair.
▸ In Java this is enforced by the language (private keyword), not just by convention.
Java Programming • CSE-3-506-T UNIT 2
Inheritance
C / C++ Java
• class Derived : public Base { … }; (C++) • class Derived extends Base { … }
• class Derived : public Base, public Other { … }; • extends only ONE class — Java has no multiple
— multiple inheritance allowed class inheritance (avoids the diamond problem)
• Base class members accessed via • [Link] accesses the parent's version
BaseClass::member or normal scoping explicitly
• Constructors chained with an initializer list: • super(x); as the first line of the derived
Derived() : Base(x) { … } constructor calls the parent constructor
Java Programming • CSE-3-506-T UNIT 2
Inheritance With extends and super
class Person {
String name;
Person(String name) { [Link] = name; }
void greet() { [Link]("Hi, I'm " + name); }
}
class Student extends Person {
int roll;
Student(String name, int roll) {
super(name); // must be the first statement
[Link] = roll;
}
void greet() {
[Link](); // call parent version too
[Link]("Roll number: " + roll);
}
▸ extends creates an “is-a” relationship: a Student is-a Person.
}
▸ super(name) forwards initialisation to the parent, just as a C++ base-class constructor call does.
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Inheritance Practice
✓ Create a Vehicle class with brand and speed, and a method describe().
✓ Create a Car class that extends Vehicle and adds a numDoors field.
✓ Override describe() in Car to call [Link]() and add door info.
Java Programming • CSE-3-506-T UNIT 2
I N H E R I TA N C E
Types of Inheritance Java Supports
▸ Single — one class extends one parent (most common).
▸ Multilevel — A → B → C, a chain of extends.
▸ Hierarchical — several classes extend the same parent.
▸ Multiple inheritance of classes is NOT allowed (unlike C++) — avoids ambiguity when two parents
define the same method.
▸ Java achieves the useful parts of multiple inheritance through interfaces instead (coming up
shortly).
Java Programming • CSE-3-506-T UNIT 2
P O LY M O R P H I S M
Polymorphism — Two Flavours
▸ Compile-time (method overloading)
▸ same method name, different parameter lists, resolved by the compiler.
▸ Run-time (method overriding)
▸ a subclass redefines a parent method; the version that runs is decided at run time based on the
object's actual type.
▸ Both concepts exist in C++ too (function overloading and virtual functions) — but in Java every
non-static, non-final method is virtual by default.
Java Programming • CSE-3-506-T UNIT 2
Method Overloading (Compile-Time)
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; }
}
▸ Same method name, different parameter type or count — the compiler picks the right one at compile time based
on the arguments you pass.
▸ Return type alone cannot distinguish overloads — same rule as in C++.
Java Programming • CSE-3-506-T UNIT 2
Method Overriding (Run-Time)
class Shape {
double area() { return 0; }
}
class Circle extends Shape {
double radius;
Circle(double r) { radius = r; }
@Override
double area() { return [Link] * radius * radius; }
}
Shape s = new Circle(3);
▸ [Link]([Link]());
@Override is optional but strongly recommended — the compiler
// calls Circle'sflagsversion
a mistake ifat
therun
signature
timedoesn't actually
match a parent method.
▸ This is the same run-time dispatch behaviour as a C++ virtual function — except in Java it is the default, you don't
need a virtual keyword.
Java Programming • CSE-3-506-T UNIT 2
Overloading vs. Overriding
Aspect Overloading Overriding
Where Same class (or subclass adds a Subclass redefines a parent method
variant)
Signature Must differ (parameters) Must match exactly
Resolved At compile time At run time
Also called Static / early binding Dynamic / late binding
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Polymorphism Practice
✓ Write three overloaded versions of a method area() for a square, rectangle, and circle in one
“Utility” class.
✓ Create a Shape parent with an area() method, and Circle/Rectangle subclasses that override it.
✓ Store several shapes in a Shape[] array and call area() on each in a loop — observe which
version runs.
Java Programming • CSE-3-506-T UNIT 2
A B S T R A C T I O N , PA R T 1
Abstract Classes
▸ Declared with abstract class — cannot be instantiated directly (no new AbstractThing()).
▸ May mix fully-implemented methods with abstract methods (no body, just a signature).
▸ A subclass MUST override every abstract method, or it must also be declared abstract.
▸ Conceptually close to a C++ class with at least one pure virtual function (= 0), but Java forces the
abstract keyword explicitly.
Java Programming • CSE-3-506-T UNIT 2
Writing an Abstract Class
abstract class Shape {
abstract double area(); // no body — subclasses must supply one
void printArea() { // regular method, fully implemented
[Link]("Area = " + area());
}
}
class Square extends Shape {
double side;
Square(double s) { side = s; }
double area() { return side * side; }
▸ }Shape s = new Shape(); would not compile — abstract classes exist only to be extended.
▸ printArea() can call area() even though Shape itself has no implementation for it — the correct override is plugged
in at run time.
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Abstract Class Practice
✓ Make Shape from the earlier exercise abstract, with an abstract area() method.
✓ Try instantiating Shape directly and read the compiler error.
✓ Add a non-abstract helper method to Shape that every subclass inherits for free.
Java Programming • CSE-3-506-T UNIT 2
Interfaces — Java's Answer to Multiple Inheritance
C / C++ Java
• class Bird : public Flyable, public Swimmable { … • class Bird implements Flyable, Swimmable { … }
}; — direct multiple inheritance — a class can implement many interfaces
• Risk: the diamond problem if two base classes • No diamond problem: interfaces only declare
share a common ancestor. method signatures (plus optional default
methods), never state.
• Pure abstract classes (all methods = 0) are the
closest analogue to an interface. • interface Flyable { void fly(); } — all methods
are implicitly public and abstract.
Java Programming • CSE-3-506-T UNIT 2
Defining and Implementing an Interface
interface Playable {
void play(); // implicitly public abstract
}
interface Recordable {
void record();
}
class Instrument implements Playable, Recordable {
public void play() { [Link]("Playing..."); }
public void record() { [Link]("Recording..."); }
▸ }A class can implement any number of interfaces, giving Java the flexibility of multiple inheritance without the
ambiguity.
▸ Since Java 8, interfaces may also have default methods with a body — look this up as extra reading.
Java Programming • CSE-3-506-T UNIT 2
Abstract Class vs. Interface
Aspect Abstract Class Interface
Fields Any kind, any access modifier Constants only (public static final)
Methods Abstract and/or concrete Abstract by default; default/static
methods allowed since Java 8
Inheritance extends — one only implements — any number
Use when Classes share common Unrelated classes share only a
state/behaviour capability
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Interface Practice
✓ Define an interface Washable with a method wash().
✓ Implement it in two unrelated classes, e.g. Car and Dish.
✓ Store both in a Washable[] array and call wash() on each — this is polymorphism through an
interface.
Java Programming • CSE-3-506-T UNIT 2
ORGANISING CODE
Inner (Nested) Classes — A Quick Tour
▸ Member inner class
▸ defined inside another class, has access to the outer object's fields.
▸ Static nested class
▸ like a member class but marked static — doesn't need an outer instance.
▸ Local class
▸ defined inside a method body, visible only there.
▸ Anonymous class
▸ a class with no name, defined and instantiated in one expression — handy for quick interface
implementations (you'll use this in Unit 5 for event handling).
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Inner Class Practice
✓ Add a small static nested class Address inside your Student class, with street and city fields.
✓ Give Student an Address field and print it from display().
✓ Optional: implement Playable from the earlier exercise using an anonymous class instead of a
named one.
Java Programming • CSE-3-506-T UNIT 2
UNIT 2 CHECK
Before You Move On…
1. Why does Java always need new to create an object, unlike a C struct on the stack?
2. What line must be first inside a subclass constructor that calls the parent constructor?
3. Give one reason Java forbids multiple inheritance of classes but allows multiple interfaces.
4. Is method overloading resolved at compile time or run time? What about overriding?
5. When would you choose an abstract class over an interface?
6. What's the difference between this() and super() inside a constructor?
Java Programming • CSE-3-506-T UNIT 2
static — Belongs to the Class, Not the Object
C / C++ Java
• static int counter = 0; // file/translation-unit • static int counter = 0; // one copy shared by
scope variable, or a class-level static member in ALL objects of the class
C++
• static methods (like main itself!) can be called
• C++ static class members work almost without creating an object:
identically to Java's. [Link]()
• Plain C has no classes, so “static data shared by • A static method cannot use this or access non-
all instances” must be hand-rolled with a file- static (instance) fields directly — it doesn't
scope global. know which object you mean.
Java Programming • CSE-3-506-T UNIT 2
static Fields and Methods
class Counter {
static int totalObjects = 0; // shared by every Counter object
int id;
Counter() {
totalObjects++;
id = totalObjects;
}
static void showTotal() {
[Link]("Objects created: " + totalObjects);
}
}
new Counter(); new Counter(); new Counter();
▸ Every Counter object shares the same totalObjects — this is exactly how you'd implement an object counter,
[Link](); // "Objects created: 3"
something you'd otherwise track with a global variable in C.
▸ showTotal() is called on the CLASS, not an object: [Link](), not [Link]().
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
static Practice
✓ Add a static counter to your Student class that tracks how many Student objects have been
created.
✓ Add a static method printTotalStudents() and call it via [Link]() rather than
through an object.
✓ Try to access an instance field from inside a static method and read the compiler error.
Java Programming • CSE-3-506-T UNIT 2
I M M U TA B I L I T Y & S A F E T Y
final — Locking Things Down
▸ final variable
▸ a constant — must be assigned exactly once. final double PI = 3.14159; — the same purpose as
const in C/C++.
▸ final method
▸ cannot be overridden by a subclass — similar to marking a C++ virtual method as unable to be
overridden (there's no direct old-C++ keyword for this pre-C++11's final).
▸ final class
▸ cannot be extended at all — String itself is a final class, which is part of why it can be safely
shared and pooled.
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
final Practice
✓ Declare a final variable for a tax rate or similar constant and try to reassign it — read the
compiler error.
✓ Mark one method in your Shape hierarchy as final and try to override it in a subclass.
✓ Explain in one sentence why making a utility class final can be a good design choice.
Java Programming • CSE-3-506-T UNIT 2
C O D E O R G A N I S AT I O N
Packages — Organising Classes
▸ A package is a namespace that groups related classes, similar in spirit to a C++ namespace, but
tied directly to your folder structure.
▸ package [Link]; at the top of a file places that class in the [Link]
package — it must live in a matching folder path: com/school/students/.
▸ Import a class from another package with import [Link]; — or import
[Link].*; for everything in it.
▸ [Link], [Link], [Link] (the packages behind Scanner, FileReader, and JDBC) are all part of the
standard library's own package hierarchy.
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
Packages Practice
✓ Put your Student class in a package named [Link], in the matching folder structure.
✓ Put your Main class with main() in the default package (or another package) and import
Student from [Link].
✓ Compile both with javac and confirm the folder-to-package mapping is required for it to work.
Java Programming • CSE-3-506-T UNIT 2
T H E U N I V E R S A L PA R E N T
Object Class Methods You'll See Everywhere
▸ Every class in Java implicitly extends Object, whether you write extends or not — there is no
equivalent universal base class in C/C++.
▸ toString() — override it to control what println(myObject) prints instead of a memory-address-
looking default.
▸ equals(Object o) — override it to define what “equal” means for your class's content (default is
reference equality, the same trap as String's == you saw in Unit 3's preview).
▸ hashCode() — should be overridden together with equals() whenever you override equals().
Java Programming • CSE-3-506-T UNIT 2
Overriding toString()
class Student {
String name;
int roll;
Student(String name, int roll) { [Link] = name; [Link] = roll; }
@Override
public String toString() {
return roll + " - " + name;
}
}
Student s = new Student("Asha", 12);
▸ [Link](s);
Without overriding toString(), println(s) prints the"12
// prints class-name plus instead
Asha" a hash codeof
— rarely useful for debugging.
Student@1b6d3586
▸ This is one of the very first overrides worth adding to any class you write.
Java Programming • CSE-3-506-T UNIT 2
PRACTICE NOW
✎
toString() Practice
✓ Add a toString() override to your Student or Book class that returns a readable one-line
summary.
✓ Print an array of your objects with a for-each loop and confirm each one now displays
meaningfully.
✓ Optional: look up and try overriding equals() to compare two Student objects by roll number.
Java Programming • CSE-3-506-T UNIT 2
UNIT 3
Strings and Collection Basics
5 hours • Course Content
→ The String class & immutability
→ String operations
→ Intro to the Collection Framework
→ The Vector class
→ Arrays vs. Vectors
Strings — A Genuine Paradigm Shift
C / C++ Java
• char name[20] = "Asha"; // a mutable array of • String name = "Asha"; // an object, backed by
characters an immutable char sequence
• You manipulate strings by hand with strcpy, • You call methods on the object: [Link](),
strcat, strcmp, strlen from <string.h>. [Link](), [Link](other).
• Forgetting the null terminator, or writing past • A String can never be modified after creation —
the buffer, corrupts memory — a classic C bug. every “modifying” method actually returns a
brand-new String.
• std::string in C++ is closer to Java's String, but is
still mutable. • No buffer overruns are possible — the JVM
manages the backing storage.
Java Programming • CSE-3-506-T UNIT 3
THE STRING CLASS
Creating Strings
▸ String literal: String s1 = "hello"; — stored in a special String pool and reused if the same literal
appears again.
▸ String object: String s2 = new String("hello"); — always creates a fresh object, even if an identical
literal exists.
▸ Because String is immutable, [Link]() does not change s1 — it returns a new String that
you must capture: s1 = [Link]();
Java Programming • CSE-3-506-T UNIT 3
PRACTICE NOW
✎
String Creation Practice
✓ Create a String using a literal and another using new String(…) with the same text.
✓ Call toUpperCase() on the first one, print both the original and the result, and confirm the
original is unchanged.
✓ Predict, then verify: does s1 == s2 give true or false for the two Strings above?
Java Programming • CSE-3-506-T UNIT 3
Comparing Strings — A Classic Trap
C / C++ Java
• strcmp(a, b) == 0 — compares actual character • a == b — compares REFERENCES (are they the
content. same object in memory?).
• There is no reference-vs-content ambiguity for • [Link](b) — compares CONTENT (are the
C strings, since they are plain char arrays. characters the same?). Always use .equals() for
text comparison.
• [Link](b) — returns
negative/zero/positive, like strcmp, useful for
sorting.
This is the single most common bug new Java learners write: using == to compare Strings.
Java Programming • CSE-3-506-T UNIT 3
PRACTICE NOW
✎
The == vs .equals() Trap
✓ Compare two Strings built with new String("cat") using both == and .equals() — note the
different results.
✓ Now compare two literal Strings "cat" == "cat" and explain why it happens to print true (String
pool).
✓ Write a rule for yourself: never use == on String objects. Only use .equals().
Java Programming • CSE-3-506-T UNIT 3
Common String Methods
Method Purpose Example
length() number of characters [Link]()
charAt(i) character at index i [Link](0)
substring(a,b) extract part of the string [Link](1, 4)
concat(s2) / + join two strings [Link]("!") or s + "!"
indexOf(x) first position of x, or -1 [Link]("ash")
replace(a,b) replace all occurrences [Link]('a','@')
trim() remove leading/trailing spaces [Link]()
split(regex) break into a String[] array [Link](",")
toCharArray() convert to a char[] [Link]()
Java Programming • CSE-3-506-T UNIT 3
PRACTICE NOW
✎
String Methods Practice
✓ Read a full name with Scanner and print the first name and last name separately using
substring or split.
✓ Count how many times a given character appears in a string using charAt() in a loop.
✓ Check if a string is a palindrome (reads the same forwards and backwards).
Java Programming • CSE-3-506-T UNIT 3
String Concatenation and substring
String first = "Java";
String second = "Programming";
String full = first + " " + second; // "Java Programming"
String s = "Hello, World!";
[Link]([Link](7)); // "World!"
[Link]([Link](7, 12)); // "World"
[Link]([Link]("World")); // 7
▸ [Link]([Link]("World", "Java")); // "Hello, Java!"
substring(a) takes from index a to the end; substring(a, b) takes from a up to (not including) b — same half-open
convention as many C library functions.
▸ + with a String operand converts the other operand automatically — "Total: " + 5 gives "Total: 5", something C
requires sprintf for.
Java Programming • CSE-3-506-T UNIT 3
PERFORMANCE TIP
StringBuilder — When You Need a Mutable String
▸ Repeatedly using + inside a loop creates a new String object every single time — wasteful for
large amounts of text building.
▸ StringBuilder sb = new StringBuilder(); [Link]("a").append("b"); — grows in place, no new
object per call.
▸ Call [Link]() at the end to get back a normal String.
▸ StringBuffer is the same idea but thread-safe (slower) — use StringBuilder unless you specifically
need thread safety.
Java Programming • CSE-3-506-T UNIT 3
PRACTICE NOW
✎
StringBuilder Practice
✓ Use a loop to build a comma-separated list of numbers 1 to 10 with plain + concatenation.
✓ Rewrite the same loop using [Link]().
✓ Try [Link]() and [Link](0, "Start: ") and observe the results.
Java Programming • CSE-3-506-T UNIT 3
COLLECTION FRAMEWORK
Why Collections? The Limits of Arrays
▸ An array has a fixed size decided at creation time — you cannot grow or shrink it.
▸ Adding an element “in the middle” means writing the shifting logic yourself.
▸ C++'s Standard Template Library (vector, list, map) solves this with generic containers — Java has
its own parallel: the Collection Framework.
▸ The Collection Framework is a family of interfaces and classes: List, Set, Map, Queue — all built
on top of a common Collection interface.
Java Programming • CSE-3-506-T UNIT 3
Collection Framework — Where Vector Fits
Collection List Vector
root interface: add, remove, size… ordered, duplicates allowed a synchronized, growable List — our focus
→ → this unit
ArrayList is Vector's modern, non-synchronized cousin and is far more common in new code, but this syllabus
focuses on Vector, so we'll use it here.
Java Programming • CSE-3-506-T UNIT 3
DYNAMIC STORAGE
The Vector Class
▸ Vector is a resizable array — conceptually similar to a std::vector<int> in C++, but it can hold only
objects (use wrapper classes for primitives).
▸ import [Link]; then: Vector<Integer> v = new Vector<>();
▸ It grows automatically as you add elements — no need to know the size in advance, unlike a plain
Java array or a C array.
▸ Being synchronized, Vector is safe to share across threads, at a small performance cost versus
ArrayList.
Java Programming • CSE-3-506-T UNIT 3
Creating and Using a Vector
import [Link];
Vector<String> names = new Vector<>();
[Link]("Asha"); // add to the end
[Link]("Ravi");
[Link](1, "Meera"); // insert at index 1
[Link]([Link](0)); // "Asha"
[Link]([Link]()); // 3
[Link]("Ravi"); // remove by value
[Link](0); // remove by index
for (String n : names) {
[Link](n);
▸ add(value) appends; add(index, value) inserts — later elements shift automatically, something a plain array cannot
}
do for you.
▸ get(index) replaces array-style [] indexing since Vector is not accessed with square brackets.
Java Programming • CSE-3-506-T UNIT 3
Frequently Used Vector Methods
Method Purpose
add(value) / add(index, value) insert an element at the end or a given position
get(index) retrieve the element at a position
set(index, value) replace the element at a position
remove(index) / remove(Object) delete by position or by value
size() current number of elements
isEmpty() true if size() == 0
contains(value) true if the value exists in the vector
elementAt(index) older-style equivalent of get(index)
Java Programming • CSE-3-506-T UNIT 3
PRACTICE NOW
✎
Vector Practice
✓ Create a Vector<String> of five fruit names, then print them with a for-each loop.
✓ Insert a new fruit at index 2 and remove one by name.
✓ Write a method that takes a Vector<Integer> and returns the sum of its elements.
Java Programming • CSE-3-506-T UNIT 3
Arrays vs. Vector — Choosing the Right Tool
Aspect Array Vector
Size Fixed at creation Grows and shrinks automatically
Data types Primitives and objects Objects only (use wrapper classes)
Access arr[i] [Link](i)
Insert/remove middle Manual shifting required Built-in add(index,…) / remove(index)
Performance Slightly faster, less overhead Small synchronization overhead
When to use Fixed, known-size numeric data Size unknown in advance, frequent
insert/remove
Java Programming • CSE-3-506-T UNIT 3
PRACTICE NOW
✎
Arrays vs. Vector — Rewrite Exercise
✓ Take your array-based marks program from Unit 1 and rewrite it using a Vector<Integer>.
✓ Add a sixth mark to the vector after it's created — note how much simpler this is than resizing
an array by hand.
✓ Write down, in your own words, one situation where an array is still the better choice than a
Vector.
Java Programming • CSE-3-506-T UNIT 3
UNIT 3 CHECK
Before You Move On…
1. Why is a == b unreliable for comparing the text content of two Strings?
2. What does immutability mean for the String class, and why does concatenation in a loop
then become expensive?
3. Where does StringBuilder solve a real performance problem?
4. Name two capabilities a Vector has that a plain array does not.
5. Why can a Vector not directly store an int, only an Integer?
Java Programming • CSE-3-506-T UNIT 3
More String Methods Worth Knowing
Method Purpose Example
equalsIgnoreCase(s2) content match, case-insensitive "Cat".equalsIgnoreCase("cat") → true
startsWith(prefix) check the beginning [Link]("Mr")
endsWith(suffix) check the ending [Link](".java")
isEmpty() / isBlank() check for no characters / only [Link]()
whitespace
toLowerCase() / toUpperCase() case conversion [Link]()
contains(seq) substring search, boolean result [Link]("err")
format(...) printf-style formatting [Link]("%d items", n)
Java Programming • CSE-3-506-T UNIT 3
[Link] — printf's Java Cousin
String name = "Asha";
int marks = 88;
String line = [Link]("%-10s scored %3d marks", name,
marks);
[Link](line);
▸ [Link]("Pi
[Link] uses the exact same format-specifier
is about syntax as C's printf (%d,
%.2f%n", %s, %.2f, width and padding flags all
3.14159);
carry over).
▸ [Link]() is a convenience wrapper that formats and prints in one call, avoiding a separate println.
Java Programming • CSE-3-506-T UNIT 3
PRACTICE NOW
✎
Formatting Practice
✓ Print a small table of 3 students' names and marks, aligned in columns, using [Link].
✓ Format a double to exactly 2 decimal places for a price display.
✓ Compare the result with what you'd get from C's printf for the same format string — confirm
they match.
Java Programming • CSE-3-506-T UNIT 3
B E YON D T HE SY L L A B U S — OPT I ON A L R EA D I N G
A Peek Ahead: ArrayList and HashMap
▸ This syllabus focuses on Vector, but almost all modern Java code uses ArrayList<T> instead —
same idea, not synchronized, generally faster.
▸ List<String> names = new ArrayList<>(); — nearly identical API to Vector (add, get, remove, size).
▸ Map<String, Integer> ages = new HashMap<>(); [Link]("Asha", 20); int a = [Link]("Asha"); —
a key-value store, similar in purpose to a C++ std::map or std::unordered_map.
▸ Worth exploring on your own once this unit's Vector material feels solid — the concepts transfer
directly.
Java Programming • CSE-3-506-T UNIT 3
PRACTICE NOW
✎
Optional Stretch: Try ArrayList
✓ Take one of your Vector exercises and rewrite it using ArrayList<String> instead — notice how
little changes.
✓ Try a simple HashMap<String, Integer> that maps student names to marks, and print all entries
with a for-each over [Link]().
Java Programming • CSE-3-506-T UNIT 3
SORTING
Sorting a Vector
▸ [Link](vector) sorts a Vector of Comparable elements (String, Integer, etc.) in
natural (ascending) order.
▸ import [Link]; then: [Link](names); — alphabetical order for Strings,
numeric order for numbers.
▸ [Link](vector) reverses the current order in place.
▸ This mirrors qsort() in C, but you don't need to write a comparison function for simple natural
ordering.
Java Programming • CSE-3-506-T UNIT 3
PRACTICE NOW
✎
Sorting Practice
✓ Sort your Vector<String> of fruit names alphabetically using [Link].
✓ Sort a Vector<Integer> of marks in ascending order, then reverse it for descending order.
✓ Print before and after each operation to confirm the sort happened in place.
Java Programming • CSE-3-506-T UNIT 3
UNIT 3 — EXTRA CHECK
One More Pass
1. What's the difference between equals() and equalsIgnoreCase()?
2. Which class from the standard library gives you printf-style formatting for a String?
3. Name the modern, more commonly used cousin of Vector.
4. What single import do you need to call [Link]()?
Java Programming • CSE-3-506-T UNIT 3
UNIT 4
Exception Handling and File
Handling
5 hours • Course Content
→ What an exception is
→ try / catch / finally
→ throw & throws, checked vs unchecked
→ Byte streams & character streams
→ Reading and writing files
Handling Errors — A Genuine Paradigm Shift
C / C++ Java
• Functions signal failure through a return code: • An unusual condition throws an exception
if (fopen(...) == NULL) { /* handle it */ } object, which immediately stops normal
execution and jumps to a handler.
• The caller MUST remember to check every
return value — nothing forces this. • The compiler forces you to handle or declare
certain exceptions — you cannot silently ignore
• A forgotten check often means the program
them.
silently continues with garbage data, or crashes
far from the real cause. • The failure is caught close to its cause, with a
full stack trace showing exactly where it
• errno gives more detail, but you must check it
happened.
manually too.
• Normal code and error-handling code are
visually separated (try vs. catch), instead of
interleaved if-checks.
Java Programming • CSE-3-506-T UNIT 4
CONCEPT
What Is an Exception?
▸ An exception is an object representing an abnormal event during program execution — dividing
by zero, accessing a bad array index, reading a missing file.
▸ When it occurs, the JVM “throws” the exception; if nothing “catches” it, the program terminates
and prints a stack trace.
▸ Exceptions let you separate the “happy path” logic from error-recovery logic, instead of tangling
if-checks everywhere as in C.
Java Programming • CSE-3-506-T UNIT 4
The Throwable Hierarchy
Throwable Error Exception
root of everything that can be thrown serious JVM problems problems your program can reasonably
(OutOfMemoryError). Not meant to be handle
→ caught. →
Exception itself splits into checked exceptions (e.g. IOException — must be declared or caught) and
unchecked / RuntimeException (e.g. ArithmeticException, NullPointerException — optional to catch).
Java Programming • CSE-3-506-T UNIT 4
try / catch — Basic Syntax
try {
int a = 10, b = 0;
int result = a / b; // throws
ArithmeticException
[Link](result); // never reached
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " +
▸ [Link]());
Code that might fail goes in try; the matching handler goes in catch — the program does NOT crash, unlike an
}unguarded C division by zero (undefined behaviour) or a Windows/Linux SIGFPE signal.
▸ [Link]("Program
[Link]() gives a human-readable description continues normally");
of what went wrong.
Java Programming • CSE-3-506-T UNIT 4
PRACTICE NOW
✎
Your First try/catch
✓ Write a program that divides two numbers read from Scanner, wrapped in try/catch for
ArithmeticException.
✓ Deliberately enter 0 as the divisor and confirm the program prints a friendly message instead
of crashing.
✓ Trigger an ArrayIndexOutOfBoundsException on purpose and catch it too.
Java Programming • CSE-3-506-T UNIT 4
H A N D L I N G M U LT I P L E FA I L U R E T Y P E S
Multiple catch Blocks
▸ You can stack several catch blocks after one try, each handling a different exception type.
▸ Java checks them top to bottom and runs the FIRST one that matches — order matters, put more
specific exception types before more general ones.
▸ A single catch can also handle several types at once: catch (IOException | SQLException e) { … }
Java Programming • CSE-3-506-T UNIT 4
Multiple catch Blocks in Action
try {
int[] arr = new int[5];
arr[10] = 50 / 0;
} catch (ArithmeticException e) {
[Link]("Arithmetic problem: " + [Link]());
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array problem: " + [Link]());
} catch (Exception e) {
[Link]("Something else went wrong: " + [Link]());
▸ }
Only ONE catch block runs per try — the first match wins, then control skips the rest.
▸ catch (Exception e) as a final, general handler is a common safety net — but put it last.
Java Programming • CSE-3-506-T UNIT 4
PRACTICE NOW
✎
Multiple catch Practice
✓ Write one try block that could throw either ArithmeticException or
ArrayIndexOutOfBoundsException depending on user input.
✓ Add a catch for each specific type, plus a general catch (Exception e) at the end.
✓ Test both failure paths by choosing inputs that trigger each one.
Java Programming • CSE-3-506-T UNIT 4
GUARANTEED CLEANUP
The finally Block
▸ finally runs after try/catch, whether or not an exception occurred, and even if the try block
returned early.
▸ Used for cleanup that must always happen: closing a file, a database connection, a network
socket.
▸ There is no direct single-keyword equivalent in C — the closest habit is manually repeating
cleanup code at every exit point, or using goto cleanup; labels, which finally replaces cleanly.
Java Programming • CSE-3-506-T UNIT 4
try / catch / finally Together
try {
[Link]("Opening resource...");
int x = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Handled: " + [Link]());
} finally {
[Link]("Closing resource... (always runs)");
▸ }
Output order: “Opening resource…” → “Handled: …” → “Closing resource…” — finally always executes last.
▸ Even if you remove the catch and let the exception propagate, finally still runs before the program terminates.
Java Programming • CSE-3-506-T UNIT 4
PRACTICE NOW
✎
finally Practice
✓ Add a finally block to your earlier try/catch exercise that prints “Done processing.”
✓ Remove the catch block entirely (leave try/finally only), trigger the exception, and observe that
finally still runs before the crash message.
Java Programming • CSE-3-506-T UNIT 4
RAISING EXCEPTIONS
throw and throws
▸ throw
▸ used INSIDE a method to actually raise an exception yourself: throw new
IllegalArgumentException("age must be positive");
▸ throws
▸ used in a method SIGNATURE to declare that this method might pass a checked exception up to
its caller: void readFile() throws IOException { … }
▸ Easy to confuse by name alone — throw does the raising; throws is a warning label on the
method.
Java Programming • CSE-3-506-T UNIT 4
Checked vs. Unchecked Exceptions
Aspect Checked Unchecked (RuntimeException)
Checked at Compile time — must catch or Not enforced by the compiler
declare
ArithmeticException,
Examples IOException, SQLException NullPointerException,
ArrayIndexOutOfBoundsException
Typical cause External conditions (missing file, no Programming mistakes
network)
No real equivalent — closest is a Undefined behaviour if unguarded
C/C++ parallel documented error code you're (e.g. dereferencing NULL)
expected to check
Java Programming • CSE-3-506-T UNIT 4
Custom Exceptions
class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
void withdraw(double balance, double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Not enough balance!");
}
[Link]("Withdrawal successful");
▸ }Extending Exception creates your own checked exception type, meaningful to your own application domain.
▸ Callers of withdraw must now catch InsufficientFundsException or declare throws themselves — the compiler
enforces it.
Java Programming • CSE-3-506-T UNIT 4
PRACTICE NOW
✎
throw / throws / Custom Exception Practice
✓ Write a method validateAge(int age) that throws IllegalArgumentException if age is negative.
✓ Create your own checked exception class, e.g. InvalidMarksException, and throw it from a
method that validates a marks value between 0 and 100.
✓ Call that method from main inside a try/catch and print your custom message.
Java Programming • CSE-3-506-T UNIT 4
EXCEPTIONS — QU ICK CHECK
Pause and Verify
1. What is the difference between throw and throws?
2. Why does finally run even when a try block returns a value early?
3. Give one checked and one unchecked exception, and explain the practical difference.
4. In a stack of catch blocks, which one runs if two of them could technically match?
Java Programming • CSE-3-506-T UNIT 4
FILE I/O
File Handling — The Concept of Streams
▸ A stream is a sequence of data flowing between your program and a source/destination (a file, in
this unit).
▸ Byte streams
▸ read/write raw 8-bit bytes — good for images, audio, any binary data. Classes: FileInputStream,
FileOutputStream.
▸ Character streams
▸ read/write 16-bit Unicode characters — good for text. Classes: FileReader, FileWriter.
▸ This mirrors C's distinction between binary mode ("rb"/"wb") and text mode ("r"/"w") in fopen —
Java simply uses different classes instead of a mode flag.
Java Programming • CSE-3-506-T UNIT 4
File I/O Compared
C / C++ Java
• FILE *fp = fopen("[Link]", "w"); • FileWriter fw = new FileWriter("[Link]");
• fprintf(fp, "%s", text); • [Link](text);
• fclose(fp); // you must remember to call this • [Link](); // or use try-with-resources to close
it automatically
• Forgetting fclose leaks the file handle.
• try (FileWriter fw = new FileWriter("[Link]")) {
… } closes it for you even if an exception occurs.
Java Programming • CSE-3-506-T UNIT 4
Writing a Text File with FileWriter
import [Link];
import [Link];
public class WriteFile {
public static void main(String[] args) {
try (FileWriter fw = new FileWriter("[Link]")) {
[Link]("Java file handling is straightforward.\n");
[Link]("Streams do the heavy lifting.");
} catch (IOException e) {
[Link]("Write failed: " + [Link]());
}
}
▸ }IOException is a CHECKED exception — the compiler forces you to catch it or declare throws.
▸ try (…) is called try-with-resources: any resource opened in the parentheses is auto-closed at the end of the block,
checked exception or not.
Java Programming • CSE-3-506-T UNIT 4
PRACTICE NOW
✎
FileWriter Practice
✓ Write a program that asks the user for 3 lines of text and saves them to [Link] using
FileWriter.
✓ Confirm the file was created by opening it outside your program.
✓ Modify the program to append rather than overwrite (look up the FileWriter(String, boolean)
constructor).
Java Programming • CSE-3-506-T UNIT 4
Reading a Text File with FileReader
import [Link];
import [Link];
import [Link];
public class ReadFile {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]("Read failed: " + [Link]());
}
}
▸ FileReader reads raw characters; wrapping it in BufferedReader adds the convenient readLine() method and
}
improves performance by reading in chunks.
▸ while ((line = [Link]()) != null) is the standard Java idiom for “read until end of file”, similar in spirit to while
(fgets(buf, size, fp) != NULL) in C.
Java Programming • CSE-3-506-T UNIT 4
PRACTICE NOW
✎
FileReader Practice
✓ Read back [Link] line by line and print each line prefixed with its line number.
✓ Count the total number of words across the file.
✓ Combine both programs: write 5 numbers to a file, then read them back and print their sum.
Java Programming • CSE-3-506-T UNIT 4
BYT E STREAMS
FileInputStream and FileOutputStream — Byte-
Level Access
▸ Same idea as FileReader/FileWriter but operating on raw bytes — needed for non-text files
(images, serialized data).
▸ FileOutputStream fos = new FileOutputStream("[Link]"); [Link](65); // writes one byte
▸ FileInputStream fis = new FileInputStream("[Link]"); int b = [Link](); // reads one byte, or -1 at
end of file
▸ Prefer Reader/Writer classes for text, and InputStream/OutputStream classes for binary data —
mixing them up leads to encoding bugs.
Java Programming • CSE-3-506-T UNIT 4
PRACTICE NOW
✎
Byte Stream Practice
✓ Use FileOutputStream to write the bytes of a short String (via getBytes()) to a file.
✓ Use FileInputStream to read it back byte by byte in a loop until read() returns -1.
✓ Compare the code and the result with your FileReader/FileWriter exercise — note the same
read()-until-(-1) pattern.
Java Programming • CSE-3-506-T UNIT 4
UNIT 4 CHECK
Before You Move On…
1. What is the practical difference between a byte stream and a character stream?
2. Why does try-with-resources matter for file handling specifically?
3. What checked exception must you handle around almost every file operation?
4. Write the one-line idiom for “read a text file line by line until EOF” in Java.
5. Name one situation where you would pick FileOutputStream over FileWriter.
Java Programming • CSE-3-506-T UNIT 4
KN OW YOUR EN EMY
Common Built-In Exceptions You Will Meet
▸ ArithmeticException — divide by zero on integers (note: floating-point division by zero gives
Infinity/NaN instead, no exception).
▸ ArrayIndexOutOfBoundsException — index outside an array's valid range.
▸ NullPointerException — calling a method or accessing a field on a reference that is null. The
single most common runtime exception you will encounter.
▸ NumberFormatException — thrown by [Link]("abc") when the String isn't a valid
number.
▸ ClassCastException — an invalid cast between incompatible object types.
Java Programming • CSE-3-506-T UNIT 4
NullPointerException — Java's Most Common Bug
Student s = null;
[Link]([Link]); // throws NullPointerException
// Guard against it:
if (s != null) {
[Link]([Link]);
} else {
[Link]("No student record.");
▸ }
null in Java is the equivalent of a NULL pointer in C — a reference that points to “nothing”.
▸ Unlike C, dereferencing a bad pointer in Java never corrupts memory or crashes silently — it always throws a
catchable, descriptive exception.
▸ Since Java 14+, the exception message itself often names exactly which variable was null — read it before guessing.
Java Programming • CSE-3-506-T UNIT 4
PRACTICE NOW
✎
NullPointerException Practice
✓ Deliberately create a null Student reference and call a method on it to trigger a
NullPointerException.
✓ Add a null-check guard before the call and confirm the program now handles it gracefully.
✓ Use [Link] on a non-numeric String inside a try/catch for NumberFormatException.
Java Programming • CSE-3-506-T UNIT 4
WRITING EXCEPTIONS WELL
Exception Handling Best Practices
▸ Catch the most specific exception type you can usefully react to — don't blanket-catch Exception
unless you're logging and re-throwing.
▸ Never leave a catch block empty — a silently swallowed exception is one of the hardest bugs to
track down later.
▸ Only put in try{} the statements that can actually throw — keep the block focused so you know
exactly what triggered a given catch.
▸ Use finally (or try-with-resources) for cleanup, not for normal program logic.
Java Programming • CSE-3-506-T UNIT 4
PRACTICE NOW
✎
Refactor for Robustness
✓ Take an earlier program (e.g. AddTwoNumbers) and wrap the Scanner input in a try/catch for
both ArithmeticException and NumberFormatException-producing paths.
✓ Review one of your own catch blocks and make sure it actually does something useful, not just
an empty {}.
Java Programming • CSE-3-506-T UNIT 4
NUMBERS VS. TEXT IN FILES
Reading and Writing Numbers to Files
▸ Text files store everything as characters, so a number written to a file must be converted to/from
String — the same idea as fprintf("%d", n) and fscanf("%d", &n) in C.
▸ Write: [Link]([Link](94)); or [Link]([Link](94));
▸ Read: int n = [Link]([Link]()); after reading a line with BufferedReader.
Java Programming • CSE-3-506-T UNIT 4
A Small Marks File Processor
// Write marks to a file, one per line
try (FileWriter fw = new FileWriter("[Link]")) {
int[] marks = {78, 85, 92, 60, 74};
for (int m : marks) {
[Link](m + [Link]());
}
}
// Read them back and compute the average
int total = 0, count = 0;
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
total += [Link]([Link]());
count++;
}
▸ }
[Link]() writes the correct newline for the current OS (\n on Linux/macOS, \r\n on Windows) —
[Link]("Average = " + (total / (double) count));
more portable than hard-coding \n.
▸ This two-part pattern — write once, read-and-process later — is exactly what a real file-based data pipeline looks
like.
Java Programming • CSE-3-506-T UNIT 4
PRACTICE NOW
✎
Marks File Capstone
✓ Build the write-then-read marks program shown above.
✓ Extend it to also find and print the highest and lowest mark from the file.
✓ Wrap the file operations in try/catch for IOException and print a friendly message if [Link] is
missing.
Java Programming • CSE-3-506-T UNIT 4
UNIT 4 — EXTRA CHECK
One More Pass
1. What is the single most common runtime exception in real Java programs, and what causes
it?
2. Why is an empty catch block considered bad practice?
3. What method converts an int to a String for writing to a text file?
4. Why is [Link]() more portable than writing \n directly?
Java Programming • CSE-3-506-T UNIT 4
UNIT 5
Java GUI Programming
5 hours • Course Content
→ Introduction to Swing
→ JFrame, JLabel, JButton
→ Text, choice & selection components
→ Layout managers
→ Basic event handling
A NEW PROGRAMMING MODEL
From Console to Windows
▸ Everything so far has run in a terminal — text in, text out, top to bottom.
▸ A GUI program is event-driven: it draws a window and then waits, reacting to clicks and
keystrokes instead of running straight through.
▸ C has no standard GUI library at all — you'd reach for a third-party toolkit (GTK, Win32 API). C++
is similar (Qt, MFC).
▸ Java ships a GUI toolkit in the standard library itself: Swing (built on the older, more limited AWT).
Java Programming • CSE-3-506-T UNIT 5
TWO TOOLKITS, ONE EVENT MODEL
Swing vs. AWT, Briefly
▸ AWT (Abstract Window Toolkit) was Java's original GUI library — it draws components using the
underlying OS's native widgets.
▸ Swing is built on top of AWT's event system but draws its own components in pure Java, giving a
consistent look across platforms.
▸ This syllabus focuses on Swing components, prefixed with a capital J: JFrame, JButton, JLabel…
(their AWT ancestors have no J: Frame, Button, Label).
Java Programming • CSE-3-506-T UNIT 5
JFrame — Your First Window
import [Link];
public class FirstWindow {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Java GUI");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
▸ }
JFrame is the top-level window — every Swing app needs at least one.
▸ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) makes the red X actually quit the program — without it, the
window closes but the JVM keeps running.
▸ setVisible(true) must come LAST, after you've added your components (coming up next).
Java Programming • CSE-3-506-T UNIT 5
PRACTICE NOW
✎
Your First Window
✓ Create a JFrame titled with your name, sized 400x300.
✓ Set the close operation so the app exits cleanly when you click the X.
✓ Change the size and re-run — confirm the window resizes accordingly.
Java Programming • CSE-3-506-T UNIT 5
FIRST COMPONENTS
JLabel and JButton
▸ JLabel
▸ displays non-editable text or an icon — JLabel lbl = new JLabel("Enter your name:");
▸ JButton
▸ a clickable button — JButton btn = new JButton("Submit");
▸ Both must be added to a container (usually the frame's content pane) before they appear:
[Link](lbl);
Java Programming • CSE-3-506-T UNIT 5
Adding Labels and a Button
import [Link].*;
JFrame frame = new JFrame("Greeting App");
[Link](new [Link]());
JLabel label = new JLabel("Click the button below:");
JButton button = new JButton("Say Hello");
[Link](label);
[Link](button);
[Link](350, 150);
[Link](JFrame.EXIT_ON_CLOSE);
▸ setLayout(…) controls how added components are arranged — more on layout managers shortly.
[Link](true);
▸ Nothing happens yet when you click the button; wiring up behaviour needs an event listener (later in this unit).
Java Programming • CSE-3-506-T UNIT 5
PRACTICE NOW
✎
Labels and Buttons Practice
✓ Add a JLabel and two JButtons ("Yes" and "No") to a frame.
✓ Change the button text, then the label's font size using setFont(new Font("Arial", [Link],
16)).
✓ Experiment: comment out [Link](button) and confirm the button disappears.
Java Programming • CSE-3-506-T UNIT 5
TEXT INPUT
JTextField and JTextArea
▸ JTextField
▸ a single-line input box — JTextField tf = new JTextField(20); (20 is the visible width in columns).
▸ JTextArea
▸ a multi-line input/output box — JTextArea ta = new JTextArea(5, 20); (5 rows, 20 columns).
▸ Read what the user typed with [Link](); set text programmatically with [Link]("…");
▸ JTextArea has no built-in scrollbars — wrap it in a JScrollPane if the text may overflow.
Java Programming • CSE-3-506-T UNIT 5
PRACTICE NOW
✎
Text Fields Practice
✓ Add a JLabel ("Name:"), a JTextField, and a JButton ("Show") to a frame.
✓ For now just confirm the field accepts typed text — next section wires up the button to actually
read it.
✓ Add a JTextArea below the field and set some placeholder text with setText().
Java Programming • CSE-3-506-T UNIT 5
CHOICE COMPONENTS
JCheckBox and JRadioButton
▸ JCheckBox
▸ an independent on/off toggle — any number can be checked at once. isSelected() tells you its
state.
▸ JRadioButton
▸ mutually exclusive options — group them with a ButtonGroup so only one can be selected at a
time.
▸ ButtonGroup group = new ButtonGroup(); [Link](radio1); [Link](radio2);
Java Programming • CSE-3-506-T UNIT 5
Grouping Radio Buttons
JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
[Link](male);
[Link](female);
[Link](male);
▸ [Link](female);
Without the ButtonGroup, both radio buttons could be selected simultaneously — defeating the point of a radio
button.
▸ JCheckBox needs no grouping since each one is independent by design.
Java Programming • CSE-3-506-T UNIT 5
PRACTICE NOW
✎
Checkboxes & Radio Buttons Practice
✓ Add three JCheckBoxes for hobbies (Reading, Sports, Music) — confirm any combination can
be checked.
✓ Add two JRadioButtons for gender selection, grouped with a ButtonGroup.
✓ Print isSelected() for each component to the console after adding them (before wiring real
events).
Java Programming • CSE-3-506-T UNIT 5
DROPDOWN SELECTION
JComboBox
▸ A drop-down list allowing one selection from several options — saves screen space compared to
a column of radio buttons.
▸ String[] cities = {"Delhi", "Mumbai", "Chennai"}; JComboBox<String> combo = new
JComboBox<>(cities);
▸ Read the current choice with [Link]();
Java Programming • CSE-3-506-T UNIT 5
PRACTICE NOW
✎
JComboBox Practice
✓ Create a JComboBox with 4 favourite-colour options and add it to a frame.
✓ Print the initially selected item using getSelectedItem().
✓ Add a second combo box for a different category (e.g. size: Small/Medium/Large) on the same
frame.
Java Programming • CSE-3-506-T UNIT 5
Layout Managers at a Glance
Layout Behaviour Good for
FlowLayout Places components left-to-right, Simple forms, default for JPanel
wraps to a new row
BorderLayout Five zones: NORTH, SOUTH, EAST, Default for JFrame; toolbars + main
WEST, CENTER content
GridLayout Equal-sized cells in a fixed rows × Calculator buttons, uniform forms
columns grid
GridBagLayout Flexible grid with per-cell Complex, precisely aligned forms
sizing/weighting (advanced)
Java Programming • CSE-3-506-T UNIT 5
BorderLayout and GridLayout Compared
// BorderLayout — 5 named regions
[Link](new [Link]());
[Link](new JLabel("Header"), [Link]);
[Link](new JButton("Center"), [Link]);
// GridLayout — a neat 2x2 grid, e.g. for a login form
JPanel panel = new JPanel(new [Link](2, 2));
[Link](new JLabel("Username:"));
[Link](new JTextField());
[Link](new JLabel("Password:"));
▸ [Link](new
A JPanel is a lightweight container you can nest inside a JFrame — useful for combining several layouts in one
JPasswordField());
window (e.g. GridLayout inside a [Link]).
Java Programming • CSE-3-506-T UNIT 5
PRACTICE NOW
✎
Layout Managers Practice
✓ Recreate your earlier label/button frame three times, once with each of FlowLayout,
BorderLayout, and GridLayout — compare the results.
✓ Build a simple login form (2 labels + 1 text field + 1 password field) using GridLayout(2,2) inside
a JPanel.
✓ Combine a GridLayout form (CENTER) with a JButton (SOUTH) using BorderLayout on the
JFrame itself.
Java Programming • CSE-3-506-T UNIT 5
MAKING THINGS RESPOND
Event Handling — The Core Idea
▸ A GUI program spends most of its life waiting inside an event loop, reacting only when something
happens — very different from a console program's top-to-bottom flow.
▸ An event source (e.g. a JButton) is connected to a listener object that defines what should
happen.
▸ For button clicks, the listener implements the ActionListener interface and its single method:
actionPerformed(ActionEvent e).
▸ This is the same “callback” idea as registering a function pointer in C, but expressed through
Java's interface mechanism from Unit 2.
Java Programming • CSE-3-506-T UNIT 5
Wiring a Button With an Anonymous Class
JButton button = new JButton("Say Hello");
JLabel result = new JLabel(" ");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Hello, Java!");
}
});
[Link](button);
▸ [Link](result);
new ActionListener() { … } is an anonymous class (Unit 2) — a one-off implementation of the interface, created and
used in a single expression.
▸ actionPerformed runs automatically whenever the button is clicked — you never call it yourself.
Java Programming • CSE-3-506-T UNIT 5
Reading a Text Field on Click
JTextField nameField = new JTextField(15);
JButton greetButton = new JButton("Greet");
JLabel output = new JLabel(" ");
[Link](e -> {
String name = [Link]();
[Link]("Hello, " + name + "!");
▸ });
e -> { … } is a lambda expression — a shorter, modern way to implement a single-method interface like
ActionListener, available since Java 8.
▸ Functionally identical to the anonymous-class version on the previous slide, just less boilerplate.
Java Programming • CSE-3-506-T UNIT 5
PRACTICE NOW
✎
Event Handling Practice
✓ Build a form with a JTextField and a “Greet” JButton that updates a JLabel with a personalised
greeting on click.
✓ Add a second button, “Clear”, that resets the text field and label.
✓ Wire up one of your earlier JCheckBoxes so clicking a button prints its isSelected() state to the
label.
Java Programming • CSE-3-506-T UNIT 5
UNIT 5 CHECK
Before You Move On…
1. What is the key difference between a console program's flow and a GUI program's flow?
2. Which method must be called last when building a JFrame, and why?
3. Which layout manager would you choose for a calculator's button grid, and why?
4. What interface and method do you implement to respond to a button click?
5. Why must radio buttons be added to a ButtonGroup but checkboxes must not?
Java Programming • CSE-3-506-T UNIT 5
CONVENIENCE DIALOGS
JOptionPane — Quick Dialog Boxes
▸ A fast way to pop up a message or ask a question without building a full form.
▸ [Link](null, "Saved successfully!");
▸ String name = [Link]("Enter your name:"); — returns what the user
typed, or null if they cancel.
▸ int choice = [Link](null, "Delete this record?"); — returns YES_OPTION,
NO_OPTION, or CANCEL_OPTION.
Java Programming • CSE-3-506-T UNIT 5
PRACTICE NOW
✎
JOptionPane Practice
✓ Use showInputDialog to collect a user's name and showMessageDialog to greet them.
✓ Use showConfirmDialog before performing a destructive action (e.g. clearing a text field) and
only proceed if the user confirms.
Java Programming • CSE-3-506-T UNIT 5
T H E L I S T E N E R F A M I LY
Beyond ActionListener — Other Common
Listeners
▸ KeyListener
▸ reacts to individual key presses — keyPressed, keyReleased, keyTyped.
▸ MouseListener
▸ reacts to clicks, presses, and releases — mouseClicked, mousePressed, mouseEntered,
mouseExited.
▸ WindowListener
▸ reacts to window events — windowClosing, windowOpened, useful for custom close
confirmation.
▸ All follow the same pattern as ActionListener: implement the interface (or its no-op Adapter
class), override the method you care about.
Java Programming • CSE-3-506-T UNIT 5
MouseListener via a MouseAdapter
import [Link];
import [Link];
[Link](new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Hovering!");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Click me");
}
▸ });
MouseAdapter provides empty default implementations for ALL MouseListener methods, so you only override the
one you need — avoids writing five empty method bodies.
▸ This anonymous-subclass pattern is the same idea you used for ActionListener earlier in this unit.
Java Programming • CSE-3-506-T UNIT 5
PRACTICE NOW
✎
Listener Practice
✓ Add a MouseAdapter to a JButton or JLabel that changes its background colour on
mouseEntered and restores it on mouseExited.
✓ Add a simple WindowListener (or its Adapter) that shows a JOptionPane confirm dialog before
the window actually closes.
Java Programming • CSE-3-506-T UNIT 5
MENUS
JMenuBar — A Familiar Menu Strip
▸ JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem
openItem = new JMenuItem("Open");
▸ [Link](openItem); [Link](fileMenu); [Link](menuBar);
▸ Each JMenuItem gets an ActionListener exactly like a JButton — the same event-handling
knowledge you already have applies directly.
Java Programming • CSE-3-506-T UNIT 5
PRACTICE NOW
✎
Menu Practice
✓ Add a JMenuBar with a “File” menu containing “New”, “Save” and “Exit” items.
✓ Wire the “Exit” item's ActionListener to call [Link](0).
✓ Wire “Save” to show a JOptionPane confirming the (pretend) save.
Java Programming • CSE-3-506-T UNIT 5
UNIT 5 — EXTRA CHECK
One More Pass
1. Which JOptionPane method would you use to ask a yes/no question?
2. What does a MouseAdapter save you from writing, compared to implementing
MouseListener directly?
3. How do you attach behaviour to a JMenuItem, compared to a JButton?
Java Programming • CSE-3-506-T UNIT 5
UNIT 6
Java Database Connectivity and
Applications
5 hours • Course Content
→ What JDBC is & why it exists
→ JDBC architecture & drivers
→ Connecting to MySQL
→ Executing SQL from Java
→ A simple database application
B R I D G I N G JAVA A N D S Q L
What Is JDBC?
▸ JDBC (Java Database Connectivity) is a standard API that lets a Java program talk to a relational
database — send SQL, get results back as Java objects.
▸ In C, you'd link against a database-specific client library (e.g. MySQL's libmysqlclient) with its own
C API and manual memory management for every result row.
▸ JDBC gives you ONE consistent set of interfaces (Connection, Statement, ResultSet) no matter
which database you connect to — swap MySQL for PostgreSQL by changing only the driver and
connection URL.
Java Programming • CSE-3-506-T UNIT 6
JDBC Architecture
Java Application JDBC Driver Manager JDBC Driver Database
your code, using the JDBC API picks the right driver for the database-specific translator MySQL, PostgreSQL, Oracle…
URL (e.g. MySQL Connector/J)
→ → →
Your code only ever talks to the JDBC interfaces — the driver underneath handles the database-specific
network protocol, similar to how a printer driver hides hardware differences from an application.
Java Programming • CSE-3-506-T UNIT 6
DRIVERS
JDBC Driver Types — Brief Overview
▸ Type 1: JDBC-ODBC Bridge — obsolete, removed from modern Java.
▸ Type 2: Native-API driver — calls the database's native client library directly.
▸ Type 3: Network-protocol driver — talks to a middleware server, which talks to the database.
▸ Type 4: Thin driver — pure Java, talks directly to the database over its network protocol. This is
what you'll use in practice (e.g. mysql-connector-j).
Java Programming • CSE-3-506-T UNIT 6
PRACTICE NOW
✎
Set Up Your Database Environment
✓ Install MySQL locally (or use one already provided in your lab) and create a small database, e.g.
school.
✓ Create one table, students(id INT, name VARCHAR(50), marks INT), and insert 2-3 rows using a
SQL client.
✓ Download the MySQL Connector/J JAR and add it to your project's classpath — this is the Type
4 driver from the previous slide.
Java Programming • CSE-3-506-T UNIT 6
The Five Steps of Every JDBC Program
1. Load Driver 2. Connect 3. Statement 4. Execute 5. Close
[Link](...) — [Link] [Link]( executeQuery() / close the ResultSet,
optional on modern
drivers
→ nection(url, user, pass) → ) → executeUpdate() → Statement, Connection
Keep this five-step shape in your head — every JDBC program you write this unit follows exactly this pattern.
Java Programming • CSE-3-506-T UNIT 6
Step 1 & 2 — Connecting to MySQL
import [Link];
import [Link];
public class ConnectDB {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String password = "yourpassword";
try (Connection conn = [Link](url, user, password)) {
[Link]("Connected successfully!");
} catch (Exception e) {
[Link]("Connection failed: " + [Link]());
}
}
▸ The URL follows the pattern jdbc:<database-type>://<host>:<port>/<database-name>.
}
▸ try-with-resources (Unit 4) closes the Connection automatically — crucial for JDBC, since open connections are a
limited, expensive resource.
▸ getConnection throws SQLException, a checked exception — the compiler forces you to handle it.
Java Programming • CSE-3-506-T UNIT 6
PRACTICE NOW
✎
Connect to Your Database
✓ Write [Link] exactly as shown, filling in your own credentials.
✓ Run it and confirm “Connected successfully!” prints — if not, read the SQLException message
carefully; wrong host, port or password are the usual causes.
✓ Deliberately mistype the password and observe what exception message you get.
Java Programming • CSE-3-506-T UNIT 6
Statement vs. PreparedStatement
Statement (raw SQL) PreparedStatement (parameterised)
• String query = "SELECT * FROM students • PreparedStatement ps =
WHERE id = " + userInput; // building SQL with [Link]("SELECT * FROM
raw concatenation students WHERE id = ?"); [Link](1,
userInput);
• Vulnerable to SQL injection if userInput comes
from an untrusted source. • The driver escapes the value safely — SQL
injection is prevented by design.
• Simple to write for fixed, hard-coded queries.
• Also faster when the same query runs
repeatedly with different parameters, since the
database can reuse the compiled plan.
Java Programming • CSE-3-506-T UNIT 6
Executing a SELECT Query
import [Link].*;
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT id, name, marks FROM students");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int marks = [Link]("marks");
[Link](id + " - " + name + " - " + marks);
}
[Link]();
▸ executeQuery() is used for SELECT; it returns a ResultSet, a cursor over the returned rows.
[Link]();
▸ [Link]() moves the cursor forward one row and returns false when there are no more rows — the same read()-
until-false pattern you saw with file streams in Unit 4.
▸ [Link]("id") and [Link]("name") read a column by name (or by 1-based position).
Java Programming • CSE-3-506-T UNIT 6
PRACTICE NOW
✎
Running a SELECT Query
✓ Extend [Link] to run SELECT * FROM students and print every row using a while
([Link]()) loop.
✓ Add a WHERE clause to filter students scoring above 50.
✓ Rewrite the query using a PreparedStatement with a ? placeholder for the marks threshold.
Java Programming • CSE-3-506-T UNIT 6
Executing INSERT / UPDATE / DELETE
String sql = "INSERT INTO students (id, name, marks) VALUES
(?, ?, ?)";
PreparedStatement ps = [Link](sql);
[Link](1, 4);
[Link](2, "Kiran");
[Link](3, 91);
▸ int rowsAffected = [Link]();
executeUpdate() is used for INSERT, UPDATE and DELETE — it returns the number of rows affected, not a ResultSet.
▸ [Link](rowsAffected + " row(s) inserted");
Parameter positions in a PreparedStatement are 1-based, matching each ? in the SQL string left to right.
Java Programming • CSE-3-506-T UNIT 6
PRACTICE NOW
✎
INSERT and UPDATE Practice
✓ Write a program that inserts a new student record using a PreparedStatement.
✓ Write a second program that updates one student's marks by id.
✓ Query the table again afterwards to confirm both changes took effect.
Java Programming • CSE-3-506-T UNIT 6
GOOD HABITS
Closing Resources Properly
▸ Every JDBC object you open — ResultSet, Statement, Connection — holds onto real resources
(memory, network sockets, database-side cursors).
▸ Close them in reverse order of opening, or better: wrap each one in try-with-resources so it's
closed automatically even if an exception occurs.
▸ Leaked connections are one of the most common bugs in real database applications — the
database eventually refuses new connections once its limit is reached.
Java Programming • CSE-3-506-T UNIT 6
A Complete Small Application
public class StudentApp {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
try (Connection conn = [Link](url, "root", "pass");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT name, marks FROM students ORDER
BY marks DESC")) {
[Link]("Student Rankings:");
int rank = 1;
while ([Link]()) {
[Link](rank++ + ". " + [Link]("name") + " - " +
[Link]("marks"));
}
} catch (SQLException e) {
[Link]("Database error: " + [Link]());
▸ All three resources — Connection, Statement, ResultSet — are declared in one try-with-resources statement and
}
close automatically in reverse order.
}
▸ This is the pattern a real (small) database-driven application follows: connect, query, process rows, done.
}
Java Programming • CSE-3-506-T UNIT 6
PRACTICE NOW
✎
Capstone: Student Ranking App
✓ Build the StudentApp shown above against your own students table.
✓ Extend it to also print the class average, computed in Java after reading all rows.
✓ Stretch goal: wrap the whole thing in a simple Swing GUI (Unit 5) with a JButton that runs the
query and shows results in a JTextArea.
Java Programming • CSE-3-506-T UNIT 6
UNIT 6 CHECK
Before You Move On…
1. List, in order, the five steps every JDBC program follows.
2. Why is a PreparedStatement generally safer than building SQL with string concatenation?
3. Which method executes a SELECT, and which executes an INSERT/UPDATE/DELETE?
4. What does [Link]() return once there are no more rows?
5. Why should Connection, Statement and ResultSet be closed with try-with-resources?
Java Programming • CSE-3-506-T UNIT 6
D A TA I N T E G R I T Y
Transactions — All or Nothing
▸ By default, JDBC auto-commits every statement immediately — fine for single queries, risky for a
sequence that must all succeed together.
▸ [Link](false); turns auto-commit off, letting you group several statements into one
transaction.
▸ [Link](); saves all changes since the last commit. [Link](); undoes them if
something went wrong.
▸ Classic example: transferring money between two accounts — debit one, credit the other; both
must succeed, or neither should.
Java Programming • CSE-3-506-T UNIT 6
A Simple Transaction
[Link](false);
try {
[Link]("UPDATE accounts SET balance = balance - 500 WHERE id =
1");
[Link]("UPDATE accounts SET balance = balance + 500 WHERE id =
2");
[Link]();
[Link]("Transfer successful");
} catch (SQLException e) {
[Link]();
[Link]("Transfer failed, rolled back: " + [Link]());
▸ }If the second update
finally { failed for any reason, rollback() undoes the first one too — the account balances never end up
inconsistent.
[Link](true);
▸ }This is the same all-or-nothing guarantee databases are designed to provide; JDBC just gives you the API to use it
from Java.
Java Programming • CSE-3-506-T UNIT 6
PRACTICE NOW
✎
Transaction Practice
✓ Create a small accounts table with id and balance columns and two rows.
✓ Write the transfer program shown above and confirm both balances update together.
✓ Deliberately break the second update (e.g. bad column name) and confirm rollback() prevents
a half-applied transfer.
Java Programming • CSE-3-506-T UNIT 6
PERFORMANCE
Batch Updates — Sending Many Statements at
Once
▸ Calling executeUpdate() in a loop sends one round-trip to the database per call — slow for bulk
inserts.
▸ addBatch() queues up statements; executeBatch() sends them all together in one round-trip.
▸ [Link](1, name); [Link](2, marks); [Link](); — repeat for each row, then
[Link](); once at the end.
Java Programming • CSE-3-506-T UNIT 6
PRACTICE NOW
✎
Batch Update Practice
✓ Insert 5 new student records using individual executeUpdate() calls in a loop and note it works
but issues 5 round-trips.
✓ Rewrite the same insert using addBatch()/executeBatch() with a single PreparedStatement.
Java Programming • CSE-3-506-T UNIT 6
M E T A D A TA
ResultSetMetaData — Discovering a Table's
Shape
▸ Sometimes you don't know the columns of a query result in advance (e.g. a generic report tool).
▸ ResultSetMetaData meta = [Link](); int cols = [Link]();
▸ for (int i = 1; i <= cols; i++) [Link]([Link](i));
▸ Useful for building generic table viewers — exactly what a database GUI tool does internally.
Java Programming • CSE-3-506-T UNIT 6
PRACTICE NOW
✎
Metadata Practice
✓ Run any SELECT query and print the column names and count using ResultSetMetaData before
printing the row data.
✓ Combine this with your earlier Swing knowledge (optional stretch): print query results into a
JTextArea, formatted using the column names you discovered.
Java Programming • CSE-3-506-T UNIT 6
UNIT 6 — EXTRA CHECK
One More Pass
1. What does [Link](false) let you do that you couldn't do by default?
2. Why is executeBatch() usually faster than calling executeUpdate() in a loop?
3. What object would you use to discover a ResultSet's column names at run time?
Java Programming • CSE-3-506-T UNIT 6
WRAPPING UP
From Console Programs to Database-
Backed Applications
COURSE RECAP
Learning Outcomes — Revisited
▸ Explain the fundamentals, features, and object-oriented concepts of Java. — Unit 1 & 2
▸ Develop Java programs using classes, objects, methods, arrays, strings, and inheritance. — Units
1–3
▸ Apply exception handling, file handling, and collection framework concepts. — Units 3–4
▸ Develop basic GUI applications using Swing components and event handling. — Unit 5
▸ Create simple database-driven applications using JDBC. — Unit 6
Java Programming • CSE-3-506-T
I F YOU R E ME MB E R FI VE T HI N G S
The Big Mental Shifts, In One Slide
▸ Everything lives inside a class — there is no code outside one.
▸ Objects are created with new and live on the heap; the garbage collector reclaims them for you.
▸ Compare content with .equals(), never == , for Strings and most objects.
▸ Checked exceptions are enforced by the compiler — you cannot silently ignore an IOException or
SQLException.
▸ GUI and database code is event-driven and resource-managed — always close what you open,
ideally with try-with-resources.
Java Programming • CSE-3-506-T
KEEP LEARNING
e-Resources for Further Study
▸ Oracle Java Documentation — [Link]/javase/tutorial/
▸ W3Schools Java Tutorial — [Link]/java/
▸ GeeksforGeeks Java Programming — [Link]/java/
▸ TutorialsPoint Java Tutorial — [Link]/java/[Link]
▸ NPTEL — Programming in Java — [Link]/noc24_cs43/preview
Java Programming • CSE-3-506-T
S T U D Y S T R AT E G Y
Exam Preparation Tips
▸ Re-run every Practice Now exercise from memory, without looking at the slide — typing it
yourself is what makes the syntax stick.
▸ For each unit, write your own one-paragraph summary in plain English before checking it against
these slides.
▸ Practice tracing code by hand: given a snippet, predict its exact output, including exception
messages — this is the most common style of theory-exam question.
▸ Revisit every Unit Check quiz slide and answer out loud, then verify against the corresponding
section.
Java Programming • CSE-3-506-T
CAPSTONE OPTIONS
Mini-Project Ideas — Bring It All Together
▸ Student Result Manager
▸ Classes/objects (Unit 2) + a Vector of students (Unit 3) + file backup (Unit 4).
▸ Simple GUI Calculator
▸ Swing components, layout managers, and event handling (Unit 5) alone.
▸ Library / Inventory Desktop App
▸ Swing front-end (Unit 5) talking to a MySQL table through JDBC (Unit 6), with exception handling
(Unit 4) around every database call.
Java Programming • CSE-3-506-T
CAPSTONE OPTIONS
Mini-Project: Suggested Build Order
▸ 1. Design your classes and their fields/methods first — get the console version working end-to-
end.
▸ 2. Add file-based persistence (save/load) so data survives between runs.
▸ 3. Wrap the whole thing in a Swing GUI, reusing the same underlying classes and methods.
▸ 4. Only once the GUI version works, swap file persistence for a real JDBC-backed database.
▸ Building in this order means each step only introduces ONE new kind of problem at a time.
Java Programming • CSE-3-506-T
Good luck with Java!
You already know how to think like a programmer. Java just gives that thinking a new home —
inside classes, on the heap, and (soon) across a network and a database.
Java Programming • CSE-3-506-T • Diploma in Computer Engineering, Semester 5