JAVA
Java is a high-level, general-purpose, class-based
programming language used to develop backend services, enterprise applications,
desktop software, developer tools and many other software systems.
Java is widely used because of its platform independence,
object-oriented programming capabilities, extensive libraries and mature
development ecosystem.
Java source code is compiled into bytecode, which can run on
different operating systems through a compatible Java Virtual Machine (JVM).
Java supports variables, data types, conditions, loops,
methods, classes, objects, inheritance, interfaces, exception handling,
collections, file handling and multithreading.
This tutorial covers fundamental programming concepts,
advanced Java concepts, Java 26 features, practical examples, exercises and
projects.
What You Will Learn
- Java
fundamentals and syntax
- Variables,
data types, operators and control statements
- Methods,
arrays and strings
- Object-Oriented
Programming (OOP)
- The
four pillars of OOP
- Interfaces,
packages and access modifiers
- Exception
handling and collections
- File
handling and modern Java features
- Algorithms
and Big-O notation
- Multithreading
and concurrency
- SQL
and JDBC
- Git,
Maven, testing and debugging
- REST
APIs and Spring Boot
- New
features introduced in Java 26
- Practical
programming exercises and projects
Contents
1.
Introduction
to Java
2.
Setup
and execution
3.
Program
structure
4.
Variables
and data types
5.
Operators
6.
Conditions
7.
Loops
8.
User
input
9.
Methods
and Arrays
10.
Strings
11.
OOP
fundamentals
12.
Four
OOP pillars
13.
Interfaces
and access modifiers
14.
Exceptions
15.
Collections
and generics
16.
File
handling
17.
Modern
Java
18.
Algorithms
and Big-O
19.
Concurrency
basics
20.
SQL
and JDBC
21.
Git,
testing and Maven
22.
REST
and Spring Boot
23.
Exercises
24.
Projects
25.
Java
26 new features
1.
Introduction to Java
Java is a
general-purpose programming language used to develop a wide range of
applications.
Where Java Is Used
- Backend
services and REST APIs
- Banking
and enterprise systems
- Desktop
applications
- Developer
tools and automation
- Android-related
development
- Data-processing
systems
- Network
applications
Advantages of Java
1.
Platform independence: Java bytecode can run on different systems with a compatible
JVM.
2.
Object-oriented programming: Classes and objects help organize software.
3.
Type safety:
The compiler detects many type-related errors before execution.
4.
Rich libraries:
Java provides APIs for collections, files, networking, databases and more.
5.
Mature ecosystem: Java has widely used frameworks and development tools.
Java
programs still require careful design, testing, debugging and security
practices.
How Java Works
Java source
code is saved in a .java file. The compiler converts the source code into
bytecode, commonly stored in a .class file. The JVM executes the bytecode.
Java Source
Code
|
Java
Compiler (javac)
|
Bytecode
(.class)
|
Java Virtual
Machine (JVM)
|
Program
Execution
First Java Program
public class
Main {
public static void main(String[] args) {
System.out.println("Hello, Java
26!");
}
}
Output:
Hello, Java
26!
Check
Yourself: Explain
Java in your own words and name two applications that could be developed using
it.
2. Setup and Execution
2.1 JDK, JVM and JRE
JDK —
Java Development Kit:
Contains development tools, including the Java compiler.
JVM —
Java Virtual Machine:
Executes Java bytecode.
JRE —
Java Runtime Environment: Refers to the runtime components needed to run Java applications. Modern
JDK distributions include the runtime.
IDE —
Integrated Development Environment: Software for writing, running, testing and debugging code.
Common Java
development tools include IntelliJ IDEA, Eclipse and Visual Studio Code with
Java extensions.
2.2 Install Java 26
Install a
JDK 26 distribution suitable for your operating system.
Verify the
installation:
java
-version
javac
-version
Both
commands should report a Java 26 version if JDK 26 is installed and configured
correctly.
2.3 Compile and Run a Program
Save this
code in a file named Main.java.
public class
Main {
public static void main(String[] args) {
System.out.println("Java is
working!");
}
}
Open a
terminal in the folder containing the file.
Compile:
javac
Main.java
Run:
java Main
Output:
Java is
working!
Common Problems
- If javac is not recognized,
check the JDK installation and PATH configuration.
- If the main class cannot be
found, check the current directory, class name and package.
- If a public class is named Main,
the source file should normally be named Main.java.
3. Program Structure
A simple
Java application commonly contains a class and a main method.
public class
Main {
public static void main(String[] args) {
System.out.println("Welcome to
Java!");
}
}
Explanation
- public is an access modifier.
- class declares a class.
- Main is the class name.
- static means the method belongs
to the class rather than an instance.
- void means the method returns no
value.
- main is the conventional entry
point for this type of application.
- String[] args receives
command-line arguments.
- System.out.println() displays
text and adds a newline.
Printing Output
System.out.print("Hello
");
System.out.println("Java");
System.out.printf("Score:
%d%n", 95);
Output:
Hello Java
Score: 95
print() does
not automatically add a newline. println() does. printf() formats output.
Common
format specifiers include %d for integers, %f for floating-point numbers and %s
for strings.
Comments
//
Single-line comment
/*
Multi-line comment
*/
Comments
explain the code and are ignored by the compiler.
Practice: Print your name, your learning goal
and a three-line introduction.
4. Variables and Data Types
A variable
is a named storage location that holds a value. Its type determines what kind
of value it can represent.
int age =
20;
double price
= 1250.50;
char grade =
'A';
boolean
learning = true;
String name
= "Sam";
4.1 Primitive Data Types
|
Type |
Purpose |
Example |
|
byte |
Small
whole numbers |
byte n =
10; |
|
short |
Whole
numbers |
short n =
1000; |
|
int |
Common
whole numbers |
int n =
50000; |
|
long |
Large
whole numbers |
long n =
900000L; |
|
float |
Floating-point
values |
float n =
2.5F; |
|
double |
Floating-point
values |
double n =
2.5; |
|
char |
One UTF-16
code unit |
char c =
'A'; |
|
boolean |
True or
false |
boolean
active = true; |
String is a
reference type, not a primitive type.
4.2 Declaration, Initialization and Reassignment
int
score; // Declaration
score =
80; // Assignment
score =
90; // Reassignment
A local variable
must be initialized before it is read.
4.3 Constants
final double
TAX_RATE = 0.15;
final
prevents reassignment of the variable after initialization. Constant names are
often written in uppercase with underscores.
4.4 Type Conversion
int count =
7;
double exact
= count;
double value
= 9.8;
int whole =
(int) value;
System.out.println(exact);
// 7.0
System.out.println(whole);
// 9
Widening
conversions can convert an int to a double. A narrowing cast from double to int
discards the fractional part.
Integer
division also removes the fractional part:
System.out.println(7
/ 2); // 3
System.out.println(7.0
/ 2); // 3.5
Practice: Create variables for a product name,
quantity, price and availability. Calculate the total price.
5. Operators
Operators
perform calculations, comparisons and logical operations.
5.1 Arithmetic Operators
int a = 10;
int b = 3;
System.out.println(a
+ b); // 13
System.out.println(a
- b); // 7
System.out.println(a
* b); // 30
System.out.println(a
/ b); // 3
System.out.println(a
% b); // 1
The %
operator returns the remainder.
5.2 Comparison Operators
int age =
20;
System.out.println(age
== 20); // true
System.out.println(age
!= 20); // false
System.out.println(age
> 18); // true
System.out.println(age
<= 18); // false
Comparison
operators produce Boolean results.
5.3 Logical Operators
- && — AND
- || — OR
- ! — NOT
int age =
25;
boolean
eligible = age >= 18 && age <= 35;
System.out.println(eligible);
// true
5.4 Assignment and Increment Operators
int number =
10;
number += 5;
number -= 2;
number *= 2;
number++;
System.out.println(number);
// 27
Other useful
operators include --, /=, %=, and the conditional operator ?:.
int mark =
75;
String
result = mark >= 50 ? "Pass" : "Fail";
System.out.println(result);
Use equals()
to compare string contents. For object references, == normally checks whether
two references identify the same object.
Practice: Calculate a discount and determine
whether a number is even or odd.
6. Conditions
Conditional
statements allow a program to make decisions.
6.1 If, Else If and Else
int mark =
72;
if (mark
>= 75) {
System.out.println("A");
} else if
(mark >= 65) {
System.out.println("B");
} else if
(mark >= 50) {
System.out.println("C");
} else {
System.out.println("Try again");
}
Output:
B
Conditions
are evaluated from top to bottom. The first true branch executes.
6.2 Switch Statement
int day = 2;
switch (day)
{
case 1 ->
System.out.println("Monday");
case 2 ->
System.out.println("Tuesday");
default ->
System.out.println("Other day");
}
Output:
Tuesday
Arrow-style
switch labels became a permanent language feature in Java 14.
6.3 Switch Expressions
A switch
expression can return a value.
int day = 2;
String name
= switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
default -> "Unknown";
};
System.out.println(name);
Output:
Tuesday
Practice: Create a calculator that supports
addition, subtraction, multiplication and division. Handle invalid operators
and division by zero.
7. Loops
Loops
execute a block of code repeatedly.
7.1 For Loop
for (int i =
1; i <= 5; i++) {
System.out.println(i);
}
Output:
1
2
3
4
5
Use a for
loop when the repetition is controlled by a counter.
7.2 While Loop
int i = 1;
while (i
<= 5) {
System.out.println(i);
i++;
}
A while loop
checks its condition before each iteration. It may execute zero times.
7.3 Do-While Loop
int i = 1;
do {
System.out.println(i);
i++;
} while (i
<= 3);
A do-while
loop executes its body at least once.
7.4 Break and Continue
break exits
the nearest loop. continue skips to the next iteration.
for (int i =
1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
Output:
1
2
4
5
Practice:
1.
Print
even numbers from 2 to 100.
2.
Calculate
the sum from 1 to n.
3.
Print
a multiplication table.
4.
Identify
and fix an infinite loop.
8. User Input
The Scanner
class can read input from the keyboard.
import
java.util.Scanner;
public class
Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter age:
");
int age = input.nextInt();
System.out.println("Next year:
" + (age + 1));
input.close();
}
}
Example
output:
Enter age:
20
Next year:
21
Useful
methods:
- nextInt() — reads an integer.
- nextDouble() — reads a double.
- next() — reads one token.
- nextLine() — reads a line of
text.
The nextInt and nextLine Issue
nextInt()
does not consume the newline after the number. If you immediately call
nextLine(), it may read that leftover newline.
int age =
input.nextInt();
input.nextLine();
System.out.print("Enter
your full name: ");
String name
= input.nextLine();
Practice: Ask for a product name, quantity and
price, then print a receipt.
9. Methods
A method is
a named block of code that performs a task. Methods reduce repetition and
improve readability and testability.
public class
Main {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(4, 6);
System.out.println(result);
}
}
Output:
10
Parameters and Arguments
Parameters
are variables declared in the method definition. Arguments are values supplied
when the method is called.
Return Values
return sends
a result back to the caller. void indicates that the method does not return a
value.
Method Overloading
Overloading
means defining methods with the same name but different parameter lists.
static int
add(int a, int b) {
return a + b;
}
static
double add(double a, double b) {
return a + b;
}
Static Methods
A static
method belongs to the class and can be called without creating an instance.
static
double rectangleArea(double width, double height) {
return width * height;
}
Practice: Write methods to check even numbers,
find the largest of three numbers and calculate a discount.
10. Arrays
An array
stores a fixed-length sequence of values of one type. Indexes begin at zero.
int[] marks
= {75, 82, 68};
System.out.println(marks[0]);
// 75
marks[1] =
90;
System.out.println(marks.length);
// 3
10.1 Calculating the Total
int[] marks
= {75, 82, 68};
int total =
0;
for (int
mark : marks) {
total += mark;
}
System.out.println(total);
// 225
The enhanced
for loop is useful when the index is not needed.
10.2 Multidimensional Arrays
int[][] grid
= {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]);
// 6
An invalid
index causes ArrayIndexOutOfBoundsException.
Practice: Find the minimum, maximum, average
and second-largest value. Handle empty arrays and duplicate values.
11. Strings
String
represents text and is immutable. Operations that appear to modify a string
create another string rather than changing the original.
String text
= "Java";
System.out.println(text.length()); // 4
System.out.println(text.toUpperCase()); // JAVA
System.out.println(text.contains("av")); // true
System.out.println(text.substring(1,
3)); // av
substring(start,
end) includes the starting index and excludes the ending index.
11.1 Comparing Strings
String a =
new String("hello");
String b =
new String("hello");
System.out.println(a
== b); // false
System.out.println(a.equals(b));
// true
Use equals()
for content comparison and equalsIgnoreCase() for case-insensitive comparison.
11.2 StringBuilder
StringBuilder
is useful when repeatedly modifying text.
StringBuilder
message = new StringBuilder();
message.append("Hello");
message.append("
Java");
System.out.println(message);
// Hello Java
Practice: Count vowels, reverse a string and
check whether a string is a palindrome.
12. OOP Fundamentals
Object-Oriented
Programming organizes software around objects that combine data and behaviour.
- A class is a blueprint.
- An object is an instance
of a class.
- A field stores state.
- A method defines
behaviour.
- A constructor initializes
an object.
class
Product {
String name;
double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
void display() {
System.out.println(name + ":
" + price);
}
}
public class
Main {
public static void main(String[] args) {
Product product = new
Product("Pen", 50.0);
product.display();
}
}
Output:
Pen: 50.0
The
constructor has the same name as the class and no return type. this.name refers
to the current object's field.
Instance
members belong to objects; static members belong to the class.
Practice: Create Student, BankAccount and
Expense classes with fields, constructors and methods.
13. The Four Pillars of OOP
13.1 Encapsulation
Encapsulation
protects internal state and controls how other code accesses it.
class
BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance;
}
}
The private
field prevents unrelated classes from changing the balance directly.
13.2 Inheritance
Inheritance
allows a subclass to extend a superclass.
class Animal
{
void speak() {
System.out.println("Animal
sound");
}
}
class Dog
extends Animal {
@Override
void speak() {
System.out.println("Woof");
}
}
Java
supports single inheritance of classes. A class can implement multiple
interfaces.
13.3 Polymorphism
Polymorphism
allows a variable of a common parent type to refer to a subclass object.
Animal pet =
new Dog();
pet.speak();
Output:
Woof
Overridden
instance methods are selected according to the actual object type at runtime.
13.4 Abstraction
Abstraction
exposes essential behaviour while hiding implementation details.
abstract
class Shape {
abstract double area();
}
class Circle
extends Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
Practice: Create a Payable interface with cash
and card payment implementations.
14. Interfaces, Packages
and Access Modifiers
An interface
defines a contract that implementing classes agree to follow.
interface
Payable {
double amountDue();
}
class
Invoice implements Payable {
private final double amount;
Invoice(double amount) {
this.amount = amount;
}
@Override
public double amountDue() {
return amount;
}
}
An interface
may also define default, static and private methods, subject to Java's language
rules.
An abstract
class can contain fields, constructors, implemented methods and abstract
methods.
14.1 Access Modifiers
- private: accessible within the
declaring class.
- Package-private: accessible
within the same package.
- protected: accessible within the
same package and through qualifying subclass access.
- public: accessible wherever the
declaring type and member are accessible.
14.2 Packages
Packages
organize related classes.
package
com.example.model;
An import
statement allows a source file to refer to types from another package by simple
name.
import
java.util.ArrayList;
Practice: Place a model class and a service
class in separate packages and connect them through an interface.
15. Exception Handling
An exception
is an event that interrupts normal program flow.
public class
Main {
public static void main(String[] args) {
try {
int value =
Integer.parseInt("123");
System.out.println(value);
} catch (NumberFormatException e) {
System.out.println("Enter a
valid number.");
} finally {
System.out.println("Finished.");
}
}
}
Output:
123
Finished.
Exception Keywords
- try: Contains code that may
throw an exception.
- catch: Handles a matching
exception.
- finally: Contains cleanup code
that normally runs after the try/catch process.
- throw: Explicitly throws an
exception.
- throws: Declares exceptions a
method may pass to its caller.
Checked
exceptions generally must be caught or declared. Unchecked exceptions include
subclasses of RuntimeException.
Try-With-Resources
Use
try-with-resources for resources such as files and database connections that
implement AutoCloseable.
import
java.io.BufferedReader;
import
java.io.FileReader;
import
java.io.IOException;
public class
Main {
public static void main(String[] args) {
try (BufferedReader reader =
new BufferedReader(new
FileReader("notes.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
System.out.println("Unable to
read the file.");
}
}
}
Avoid
silently ignoring exceptions or catching overly broad exception types without a
good reason.
Practice: Handle invalid numeric input, a
missing file and a failed database operation.
16. Collections and
Generics
Collections
provide flexible data structures for storing groups of objects.
16.1 List
A List
stores an ordered sequence and allows duplicates.
import
java.util.ArrayList;
import
java.util.List;
public class
Main {
public static void main(String[] args) {
List<String> names = new
ArrayList<>();
names.add("Amal");
names.add("Nila");
System.out.println(names.get(0));
System.out.println(names.size());
}
}
Output:
Amal
2
16.2 Set
A Set stores
unique elements.
import
java.util.HashSet;
import
java.util.Set;
Set<String>
languages = new HashSet<>();
languages.add("Java");
languages.add("Java");
System.out.println(languages.size());
// 1
16.3 Map
A Map stores
key-value pairs.
import
java.util.HashMap;
import
java.util.Map;
Map<String,
Integer> stock = new HashMap<>();
stock.put("Pen",
20);
stock.put("Book",
10);
System.out.println(stock.get("Pen"));
// 20
Collection Comparison
- List: ordered sequence;
duplicates are allowed.
- Set: unique elements.
- Map: key-value pairs; keys are
unique.
ArrayList is
a common list implementation. HashSet is a common set implementation. HashMap
is a common map implementation.
Generics
Generics
specify the types of elements a collection can store.
List<String>
names = new ArrayList<>();
This
improves compile-time type safety and reduces unnecessary casting.
Practice: Store expenses in a List, categories
in a Set and category totals in a Map.
17. File Handling
File
handling allows a program to save information beyond the lifetime of the
program.
Modern Java
commonly uses the java.nio.file API.
import
java.io.IOException;
import
java.nio.file.Files;
import
java.nio.file.Path;
public class
Main {
public static void main(String[] args)
throws IOException {
Path path =
Path.of("notes.txt");
Files.writeString(
path,
"Learning Java\nPractice
daily."
);
String content =
Files.readString(path);
System.out.println(content);
}
}
Output:
Learning
Java
Practice
daily.
Path.of(),
Files.writeString() and Files.readString() were introduced in Java 11.
Real
applications should handle permissions, encoding, file sizes, errors and
untrusted paths appropriately.
Practice: Save expense records to a file and
load them when the program starts.
18. Modern Java Features
Modern Java
includes language and library features that help developers write concise and
maintainable code.
18.1 Lambda Expressions
Lambdas
provide a concise way to represent behaviour where a functional interface is
expected.
import
java.util.List;
public class
Main {
public static void main(String[] args) {
List<String> names =
List.of("Nila", "Amal", "Kavi");
names.forEach(name ->
System.out.println(name));
}
}
Lambda
expressions became a permanent feature in Java 8.
18.2 Streams
Streams
support declarative processing of data.
import
java.util.List;
public class
Main {
public static void main(String[] args) {
List<Integer> numbers =
List.of(2, 5, 8, 11);
List<Integer> even =
numbers.stream()
.filter(n -> n % 2 == 0)
.toList();
System.out.println(even);
}
}
Output:
[2, 8]
A stream
pipeline commonly contains a source, intermediate operations such as filter()
and a terminal operation such as toList().
Stream.toList()
was introduced in Java 16. The returned list is unmodifiable.
18.3 Optional
Optional
represents a value that may be absent.
import
java.util.Optional;
Optional<String>
nickname = Optional.of("Java learner");
nickname.ifPresent(System.out::println);
Output:
Java learner
18.4 Records
Records
provide a concise way to define data-focused classes.
record
Point(int x, int y) {}
public class
Main {
public static void main(String[] args) {
Point point = new Point(2, 3);
System.out.println(point.x());
System.out.println(point.y());
}
}
Output:
2
3
Records
became a permanent feature in Java 16.
18.5 Text Blocks
Text blocks
simplify multiline strings.
String
message = """
Welcome to Java.
Learn step by step.
Build useful projects.
""";
System.out.println(message);
Text blocks
became permanent in Java 15.
18.6 Local Variable Type Inference
The var
keyword was introduced in Java 10 for local variables with initializers.
var name =
"Java";
var age =
20;
System.out.println(name);
System.out.println(age);
The compiler
determines the types from the initializers. Java remains statically typed; var
is not a dynamic type.
18.7 Pattern Matching
Pattern
matching can combine a type check with the declaration of a variable.
Object value
= "Java";
if (value
instanceof String text) {
System.out.println(text.toUpperCase());
}
Output:
JAVA
Pattern
matching for instanceof became permanent in Java 16.
Practice: Filter expenses greater than 1,000
using streams and calculate their total.
19. Algorithms and Big-O
Notation
An algorithm
is a sequence of steps used to solve a problem.
19.1 Recursion
Recursion
occurs when a method calls itself. A base case prevents endless recursion.
public class
Main {
static int factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException(
"n must be
non-negative"
);
}
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
Output:
120
19.2 Linear Search
Linear
search checks elements one by one and works on unsorted data.
static int
linearSearch(int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i] == target) {
return i;
}
}
return -1;
}
19.3 Binary Search
Binary
search repeatedly halves the search range. The input must be sorted.
19.4 Big-O
- O(1): Constant growth.
- O(log n): Logarithmic growth.
- O(n): Linear growth.
- O(n log n): Common efficient
sorting growth.
- O(n²): Often associated with
nested loops.
Big-O
describes how resource requirements grow with input size, not exact execution
time.
Practice: Implement linear search, find the
largest value and compare a single loop with nested loops.
20. Concurrency Basics
Concurrency
allows tasks to make progress during overlapping periods. Java supports
threads, executors and higher-level concurrency APIs.
20.1 Creating a Thread
public class
Main {
public static void main(String[] args) {
Thread worker = new Thread(
() ->
System.out.println("Work running")
);
worker.start();
}
}
Output:
Work running
start()
starts a new thread. Calling run() directly is an ordinary method call and does
not itself start a new thread.
20.2 Important Concepts
- Threads and thread lifecycle
- Race conditions
- Synchronization
- Thread safety
- Executors and thread pools
- Concurrent collections
- Futures and asynchronous tasks
- Virtual threads
- Structured concurrency
Virtual
threads became a permanent feature in Java 21.
Structured
concurrency remains a preview API in Java 26. It helps manage related
concurrent tasks as a unit, improving cancellation, error handling and task
lifecycle management.
Practice: Explain why two threads incrementing
the same unsynchronized counter can lose updates.
21. SQL and JDBC
A relational
database stores structured data in tables. SQL creates, reads, updates and
deletes data. JDBC is Java's standard API for communicating with relational
databases.
21.1 Create an Expenses Table
CREATE TABLE
expenses (
id INTEGER PRIMARY KEY,
description VARCHAR(100) NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
expense_date DATE NOT NULL
);
21.2 Insert and Read Data
INSERT INTO
expenses
(id, description, amount, expense_date)
VALUES
(1, 'Transport', 450.00, DATE
'2026-10-27');
SELECT
description, amount
FROM
expenses;
21.3 CRUD Operations
- Create: INSERT
- Read: SELECT
- Update: UPDATE
- Delete: DELETE
21.4 PreparedStatement
Use
parameters for user-provided values rather than concatenating untrusted input
into SQL.
String sql =
"SELECT description, amount FROM
expenses WHERE amount > ?";
// Assuming
connection is a configured JDBC Connection:
//
// try
(PreparedStatement ps = connection.prepareStatement(sql)) {
// ps.setBigDecimal(1, new
BigDecimal("100.00"));
//
// try (ResultSet rs = ps.executeQuery()) {
// while (rs.next()) {
//
System.out.println(rs.getString("description"));
// }
// }
// }
This example
shows the query pattern. A working application also needs a database driver, a
configured connection and appropriate error handling.
Use
transactions when multiple database operations must succeed or fail together.
Practice: Connect an expense tracker to a
relational database and implement CRUD operations.
22. Git, Testing and Maven
22.1 Git
Git tracks
changes to source code.
git init
git status
git add .
git commit
-m "Add expense tracker basics"
git log
GitHub can
host remote repositories for collaboration and portfolio projects.
Never commit
passwords, tokens or API keys.
22.2 Unit Testing
A unit test
checks a small unit of behaviour. JUnit is a widely used testing framework for
Java.
import
static org.junit.jupiter.api.Assertions.assertEquals;
import
org.junit.jupiter.api.Test;
class
CalculatorTest {
@Test
void addsTwoNumbers() {
assertEquals(7, 3 + 4);
}
}
Add the
appropriate JUnit dependency and project configuration before running this
test.
Test normal
cases, boundary conditions and invalid inputs.
22.3 Debugging
1.
Reproduce
the problem.
2.
Read
the error message and stack trace.
3.
Inspect
the relevant line.
4.
Use
breakpoints to examine variables.
5.
Fix
the root cause.
6.
Add
a test to prevent regression.
22.4 Maven
Maven
manages project builds and dependencies through pom.xml.
mvn test
mvn package
Maven helps
teams compile, test and package projects consistently.
Practice: Create a Maven project, add a unit
test and commit the changes to Git.
23. REST APIs and Spring
Boot
A backend
API exposes operations over a network, often using HTTP and JSON. Spring Boot
simplifies the development of Java applications.
23.1 HTTP Methods
- GET: Retrieve a resource.
- POST: Create a resource or
trigger an operation.
- PUT: Replace a resource
representation.
- PATCH: Partially update a
resource.
- DELETE: Remove a resource.
23.2 Common Status Codes
- 200 OK
- 201 Created
- 400 Bad Request
- 401 Unauthorized
- 403 Forbidden
- 404 Not Found
- 500 Internal Server Error
23.3 Typical Application Layers
Client
|
v
Controller
|
v
Service
|
v
Repository
|
v
Database
Controller: Receives HTTP requests and returns
responses.
Service: Contains application and business
rules.
Repository: Handles data access.
DTO: Defines the structure of data
exchanged through the API.
Validation: Checks incoming data.
Authentication: Identifies the user.
Authorization: Determines which operations the user
may perform.
Learn Core
Java, OOP, collections, exceptions, SQL and HTTP before going deeply into
Spring Boot.
Practice: Build an Expense REST API with
create, list, retrieve, update and delete endpoints, a relational database,
validation and automated tests.
24. Practice Exercises
Beginner Exercises
1.
Print
your name and introduction.
2.
Calculate
the total cost of three items.
3.
Determine
whether a number is positive, negative or zero.
4.
Check
whether a number is even or odd.
5.
Calculate
the sum from 1 to n.
6.
Print
a multiplication table.
7.
Find
the average of an array of marks.
8.
Count
vowels and words in a sentence.
Intermediate Exercises
9.
Write
a method that returns the largest of three values.
10.
Create
a Student class with a constructor and grade-calculation method.
11.
Build
a BankAccount with a private balance and validated deposit and withdrawal
methods.
12.
Use
ArrayList to store expenses.
13.
Group
expenses by category using a Map.
14.
Save
records to a file and load them later.
15.
Handle
invalid input with exceptions.
16.
Implement
linear search and binary search.
17.
Write
unit tests for calculation and validation methods.
Advanced Exercises
18.
Connect
Java to a relational database using JDBC.
19.
Create
a Maven project with dependencies and automated tests.
20.
Build
a REST API with Spring Boot.
21.
Add
request validation and global exception handling.
22.
Persist
data in a database.
23.
Write
API integration tests.
24.
Document
and deploy the application safely.
25. Project Roadmap
Project 1: Console Calculator
Requirements:
- Accept two numbers and an
operator.
- Use separate methods for
operations.
- Handle invalid input and
division by zero.
- Add tests for calculation
methods.
- Create a README with examples
and limitations.
Project 2: Student Grade Manager
Requirements:
- Create student-related classes.
- Store multiple students in a
collection.
- Calculate averages and grades.
- Validate marks and test edge
cases.
- Document the program.
Project 3: Shop Expense Tracker
Requirements:
- Add, list, edit and delete
expenses.
- Store date, description,
category and amount.
- Show daily, weekly and monthly
totals.
- Save records to a file.
- Upgrade file storage to a
relational database.
- Add tests and documentation.
Project 4: Expense REST API
Requirements:
- Build REST endpoints with Spring
Boot.
- Connect to a relational
database.
- Validate incoming data.
- Return suitable HTTP status
codes.
- Add automated tests and API
documentation.
- Configure deployment safely.
For every
project, maintain a Git repository, README, test cases and clear explanations
of the design decisions.
26. Java 26 New Features
Java 26 was
released on 17 March 2026. It includes language previews, library improvements,
security updates and runtime performance improvements.
Important
distinction: not every new Java 26 feature is a permanent language feature.
Preview and incubator features can change before becoming permanent.
26.1 Primitive Types in Patterns, instanceof and switch
Status: Fourth preview in Java 26.
This feature
extends pattern matching so primitive types can be used in pattern contexts,
including instanceof and switch.
Example:
public class
Main {
public static void main(String[] args) {
Object value = 42;
if (value instanceof int number) {
System.out.println(number);
}
}
}
Expected
output:
42
This is a
Java 26 preview example, not a permanent feature. Preview features must be
enabled when compiling and running.
javac
--release 26 --enable-preview Main.java
java
--enable-preview Main
Preview
syntax and behaviour may change in a future Java release.
26.2 HTTP/3 Support for the HTTP Client API
Status: New HTTP/3 support in Java 26.
Java's HTTP
Client API has been updated to support the HTTP/3 protocol. Applications can
use the API to communicate with compatible HTTP servers.
Basic HTTP
Client example:
import
java.net.URI;
import
java.net.http.HttpClient;
import
java.net.http.HttpRequest;
import
java.net.http.HttpResponse;
public class
Main {
public static void main(String[] args)
throws Exception {
HttpClient client =
HttpClient.newHttpClient();
HttpRequest request =
HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.GET()
.build();
HttpResponse<String> response =
client.send(
request,
HttpResponse.BodyHandlers.ofString()
);
System.out.println(response.statusCode());
}
}
The example
demonstrates an HTTP request. It does not guarantee HTTP/3 will be negotiated;
that depends on server support, network conditions and client configuration.
26.3 Lazy Constants
Status: Second preview in Java 26.
Lazy
constants provide an API for values that can be initialized when needed and
then remain unmodifiable. They offer flexibility in initialization timing while
allowing the JVM to treat them as constants.
Potential
benefits include:
- Delaying expensive
initialization.
- Avoiding work for values that
are never used.
- Improving application startup in
suitable cases.
- Supporting immutable data
designs.
Lazy
constants are a preview API in Java 26 and should not be confused with the
permanent final keyword.
26.4 Structured Concurrency
Status: Sixth preview in Java 26.
Structured
concurrency provides an API for managing related tasks running in different
threads as one unit of work.
Potential
benefits include:
- Better task lifecycle
management.
- Easier cancellation of related
tasks.
- Clearer error handling.
- Improved observability of
concurrent operations.
Structured
concurrency remains a preview API in Java 26.
26.5 Vector API
Status: Eleventh incubator in Java 26.
The Vector
API expresses vector computations that can use supported CPU vector
instructions.
Potential
applications include:
- Scientific computing.
- Numerical calculations.
- Data processing.
- Performance-sensitive
mathematical operations.
It is an
incubator API rather than a permanent Java SE API.
26.6 PEM Encodings of Cryptographic Objects
Status: Second preview in Java 26.
Java 26
provides a preview API for encoding and decoding cryptographic objects, such as
keys, certificates and certificate revocation lists, using the widely used PEM
format.
This can
help applications exchange cryptographic material in standard formats.
Developers should understand certificate validation, private-key protection and
secure key management before using these APIs.
26.7 G1 Garbage Collector Improvements
Java 26
improves G1 garbage collector throughput by reducing synchronization between
application threads and garbage-collection threads.
The
practical effect depends on the workload and application configuration. It does
not guarantee that every Java application will run faster.
26.8 Ahead-of-Time Object Caching
Java 26
improves ahead-of-time object caching so that cached objects can be used with
different garbage collectors, including ZGC.
Potential
benefits include reduced startup and warmup time for suitable applications.
26.9 Unicode 17.0 Support
Java 26
updates its Unicode support to Unicode 17.0. Unicode defines how text
characters are represented and processed across different writing systems.
26.10 Virtual Thread Improvements
Java 26
improves virtual-thread behaviour when a virtual thread waits for another
thread to complete class initialization. In most cases, the waiting virtual
thread can unmount from its carrier thread, allowing that platform thread to be
used by other work.
This can
improve resource utilization in certain concurrent workloads.
26.11 Additional Library and Security Improvements
Java 26 also
includes updates such as:
- A new UUID API capability for
creating type 7 UUIDs.
- Additional time and duration
APIs.
- Improvements to HTTP Client
behaviour.
- Updates to cryptographic and
security APIs.
- Warnings intended to prepare
developers for stronger guarantees around final fields.
The exact
behaviour and compatibility implications should be checked in the official
release notes.
Java 26 Feature Summary
|
Feature |
Status
in Java 26 |
|
Primitive
types in patterns, instanceof and switch |
Fourth
preview |
|
HTTP/3 for
HTTP Client API |
New
support |
|
Lazy
constants |
Second
preview |
|
Structured
concurrency |
Sixth
preview |
|
Vector API |
Eleventh
incubator |
|
PEM
cryptographic encodings |
Second
preview |
|
G1 garbage
collector improvements |
Runtime
enhancement |
|
Ahead-of-time
object caching |
Runtime
enhancement |
|
Unicode
17.0 |
Library/runtime
update |
|
Virtual-thread
class-initialization improvement |
Runtime
enhancement |
