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

MITS Java Programming Ebook v2

The document is a comprehensive ebook on Java programming, covering topics from basic to advanced levels, including object-oriented programming, collections, and Spring Boot. It provides detailed instructions on setting up the Java development environment, writing and running Java programs, and understanding fundamental concepts like variables, data types, and control flow. The ebook is designed for learners at all levels, with practical examples and step-by-step guides for installation and coding practices.

Uploaded by

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

MITS Java Programming Ebook v2

The document is a comprehensive ebook on Java programming, covering topics from basic to advanced levels, including object-oriented programming, collections, and Spring Boot. It provides detailed instructions on setting up the Java development environment, writing and running Java programs, and understanding fundamental concepts like variables, data types, and control flow. The ebook is designed for learners at all levels, with practical examples and step-by-step guides for installation and coding practices.

Uploaded by

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

MITS Academy — Java Programming — Complete Ebook

MITS ACADEMY
Java Programming — Complete Ebook

Basic to Advanced | OOP | Collections | Spring Boot | Projects | MITS Academy


[Link]

Page 1 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

Chapter 1: Introduction to Java & Environment Setup


1.1 What is Java and Why Learn It?
Java is one of the most widely-used programming languages in the world, powering everything
from Android mobile apps to enterprise banking software, e-commerce platforms, and cloud
services. Created by James Gosling at Sun Microsystems in 1995, Java was designed with one
powerful philosophy: "Write Once, Run Anywhere" (WORA). This means you write your Java
program once, and it can run on any device — Windows, Mac, Linux, Android — without
modification.
Java achieves this through the Java Virtual Machine (JVM). When you write Java code, the
compiler converts it into bytecode — a platform-independent intermediate format. The JVM on
each platform then reads that bytecode and executes it. Think of the JVM as a universal
translator: your code speaks one language (bytecode) and the JVM translates it into whatever
language the local machine understands.
Why Java is so valuable in the real world: Java is the primary language for Android
development (3 billion+ devices). Major corporations like Google, Amazon, Netflix, LinkedIn,
and Uber use Java for their backend systems. Spring Boot (a Java framework) is the most
popular framework for building REST APIs and microservices. Java is strongly typed, compiled,
and object-oriented — qualities that make large codebases manageable and maintainable.

1.2 Java Platform Components


Before installing Java, you need to understand three important terms that beginners often
confuse:
• JDK (Java Development Kit): This is what you install on your computer to write and
compile Java programs. It includes the Java compiler (javac), the JVM, and thousands of
built-in libraries. Install the JDK if you want to develop Java programs.
• JRE (Java Runtime Environment): This is what end-users install to run Java programs. It
includes the JVM and standard libraries but NOT the compiler. Developers do not need
to install this separately — it comes with the JDK.
• JVM (Java Virtual Machine): The engine that actually runs your Java bytecode. It reads
the .class files produced by the compiler and executes them on your specific hardware
and operating system.

1.3 Installing the JDK — Step by Step


Follow these steps carefully to set up your Java development environment:
Step 1: Download the JDK. Visit [Link] (Eclipse Temurin — free, open source,
recommended). Choose "Java 17 LTS" (LTS = Long Term Support, most stable). Click your
operating system (Windows/Mac/Linux). Download the .msi installer (Windows) or .pkg (Mac).
Step 2: Install the JDK. Run the downloaded installer. Accept all defaults. On Windows, the JDK
will be installed in C:\Program Files\Eclipse Adoptium\jdk-17\. On Mac, it goes to
/Library/Java/JavaVirtualMachines/.
Step 3: Set the JAVA_HOME environment variable (Windows). Right-click "This PC" →
Properties → Advanced System Settings → Environment Variables. Under "System Variables",

Page 2 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

click "New". Variable name: JAVA_HOME. Variable value: C:\Program Files\Eclipse Adoptium\
jdk-17 (or wherever your JDK was installed). Click OK.
Step 4: Add Java to your PATH. In the same Environment Variables window, find "Path" under
System Variables, click Edit. Click "New" and add: %JAVA_HOME%\bin. Click OK on all
windows.
Step 5: Verify the installation. Open Command Prompt (Windows) or Terminal (Mac/Linux).
Type the following commands:
java -version
# Expected output: openjdk version "17.0.x" ...

javac -version
# Expected output: javac 17.0.x
If you see version numbers, your Java is installed correctly. If you get "java is not recognized",
double-check your PATH variable.

1.4 Setting Up VS Code for Java


VS Code is a free, lightweight editor that works excellently for Java development:
Step 1: Download VS Code from [Link] and install it.
Step 2: Open VS Code, go to the Extensions panel (Ctrl+Shift+X), and search for "Extension
Pack for Java" by Microsoft. Install it. This single pack includes: Language Support for Java
(code completion, error detection), Debugger for Java, Java Test Runner, Maven for Java, and
Project Manager for Java.
Step 3: Create your first project. Open VS Code, press Ctrl+Shift+P, type "Java: Create Java
Project", press Enter. Choose "No build tools". Select a folder (e.g., C:\JavaProjects). Name
your project "HelloWorld". VS Code creates a src/ folder with [Link] inside.

1.5 Your First Java Program — Line by Line


Every Java programmer's first program is Hello World. But rather than just typing it, let's
understand every single character:
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Breaking down every part:
• public: An access modifier. "public" means this class is accessible from anywhere. We will
cover access modifiers in Chapter 5.
• class HelloWorld: In Java, everything lives inside a class. The class name MUST match
the filename exactly — this file must be named [Link] (capital H, capital W).
• The opening brace {: Marks the start of the class body. Everything belonging to this class
goes between { and }.
• public static void main(String[] args): This is the main method — the entry point of your
program. The JVM looks for exactly this signature to know where to start running your
program.
• public: The JVM needs to call this method, so it must be public.
• static: The JVM calls main() without creating an object first, so it must be static.
• void: This method does not return any value.

Page 3 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

• main: The name the JVM looks for — this exact name is required.
• String[] args: An array of Strings for command-line arguments. We will use this in Chapter
3.
• [Link]("Hello, World!"): Prints text to the console. System is a built-in class.
out is an output stream object inside System. println() is a method that prints text
followed by a newline.
To run the program: In VS Code, right-click the file → "Run Java". Or in Terminal: navigate to
the file and type:
cd C:\JavaProjects\HelloWorld\src
javac [Link] # Compiles to [Link]
java HelloWorld # Runs the program
# Output: Hello, World!

Chapter 2: Variables, Data Types & Operators


2.1 Variables — Storing Information
A variable is a named container that holds data. Think of it like a labelled box: the label is the
variable name, and whatever is inside the box is the value. In Java, before you can use a
variable, you must declare it — telling Java what type of data it will hold.
Java is a statically-typed language: once you declare a variable as a certain type, it can only
hold that type of data. This prevents many bugs that occur in dynamically-typed languages like
Python or JavaScript.
// Declaring and initializing variables
int age = 25; // integer: whole numbers
double salary = 55000.50; // decimal numbers
String name = "Alice"; // text (String with capital S)
boolean isEmployed = true; // true or false
char grade = 'A'; // single character (use single quotes)

// You can declare first, then assign later


int score; // declared but not initialized
score = 95; // now assigned

// You can declare multiple variables of the same type


int x = 10, y = 20, z = 30;

2.2 Primitive Data Types — The Building Blocks


Java has 8 primitive data types. These are the most basic types, directly supported by the
language. Understanding each one — including its size and range — is essential for writing
memory-efficient programs:
// Integer types (for whole numbers)
byte smallNum = 100; // 8 bits, range: -128 to 127
short mediumNum = 30000; // 16 bits, range: -32,768 to 32,767
int regularNum = 2_000_000; // 32 bits, range: about -2 billion to 2 billion
long bigNum = 9_000_000_000L; // 64 bits, very large. Note the L suffix!

// Floating point types (for decimal numbers)


float price = 19.99f; // 32 bits, 7 decimal digits precision. Note the
f suffix!

Page 4 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

double precisePrice = 19.9999; // 64 bits, 15 decimal digits precision. DEFAULT


for decimals.

// Character type
char letter = 'J'; // 16 bits, stores a single Unicode character

// Boolean type
boolean isActive = false; // 1 bit logically, stores only true or false
Key rule: When you write a decimal number without a suffix, Java treats it as double by default.
When you write a large integer without L, Java treats it as int. If the number exceeds int range,
you MUST add L. The underscore in 2_000_000 is just for readability — Java ignores it.

2.3 String — Working with Text


String is not a primitive — it is a class (an object type). But it is so fundamental that Java gives it
special treatment. A String is an immutable sequence of characters. Immutable means once
created, it cannot be changed — any operation that seems to modify a String actually creates a
new one.
// Creating strings
String firstName = "John";
String lastName = "Doe";

// String concatenation with + operator


String fullName = firstName + " " + lastName;
[Link](fullName); // John Doe

// String length
[Link]([Link]()); // 4

// String methods — these are incredibly useful


String message = " Hello, Java World! ";

[Link]([Link]()); // "Hello, Java World!" (removes


whitespace)
[Link]([Link]()); // " HELLO, JAVA WORLD! "
[Link]([Link]()); // " hello, java world! "
[Link]([Link]().replace("Java", "Python")); // "Hello, Python
World!"

// Checking string content


String email = "user@[Link]";
[Link]([Link]("@")); // true
[Link]([Link]("user")); // true
[Link]([Link](".com")); // true
[Link]([Link]("@")); // 4 (position of @
character)

// Extracting parts of a string


String word = "Programming";
[Link]([Link](0, 7)); // "Program" (from index 0 to 6)
[Link]([Link](0)); // 'P' (character at index 0)

// Splitting a string
String csv = "Alice,25,Engineer";
String[] parts = [Link](",");
[Link](parts[0]); // Alice
[Link](parts[1]); // 25
[Link](parts[2]); // Engineer

Page 5 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

// String comparison — NEVER use == for strings!


String s1 = "hello";
String s2 = "hello";
[Link]([Link](s2)); // true (compares content)
[Link]([Link]("HELLO")); // true
// s1 == s2 might work sometimes but is UNRELIABLE — always use .equals()

2.4 Type Casting — Converting Between Types


Sometimes you need to convert a value from one type to another. Java has two kinds of
casting:
// Widening conversion (automatic - no data loss)
int myInt = 100;
long myLong = myInt; // int fits in long automatically
double myDouble = myInt; // int fits in double automatically

// Narrowing conversion (manual - may lose data)


double pi = 3.14159;
int truncated = (int) pi; // You must explicitly cast. The decimal is LOST.
[Link](truncated); // 3 (not 3.14159!)

// Practical example: calculating average


int total = 95 + 87 + 91;
int count = 3;
double average = (double) total / count; // Cast to double BEFORE dividing
[Link](average); // 91.0 (correct)
// Without cast: total / count = 273 / 3 = 91 (integer division, decimal lost)

// String to number conversion


String numStr = "42";
int parsed = [Link](numStr); // "42" -> 42
double parsedD = [Link]("3.14"); // "3.14" -> 3.14

// Number to String conversion


int num = 100;
String str = [Link](num); // 100 -> "100"
String str2 = [Link](num); // also works

2.5 Operators — Performing Calculations and Logic


// Arithmetic operators
int a = 17, b = 5;
[Link](a + b); // 22 (addition)
[Link](a - b); // 12 (subtraction)
[Link](a * b); // 85 (multiplication)
[Link](a / b); // 3 (integer division — decimal truncated!)
[Link](a % b); // 2 (modulus — the REMAINDER of 17/5)
[Link]([Link](a, 2)); // 289.0 (17 squared, returns double)

// The modulus operator % is extremely useful:


// Check if a number is even: num % 2 == 0
// Get last digit of a number: num % 10
// Wrap around a range: index % arrayLength

// Compound assignment operators (shortcuts)


int count = 10;
count += 5; // same as count = count + 5; -> 15
count -= 3; // same as count = count - 3; -> 12
count *= 2; // same as count = count * 2; -> 24
count /= 4; // same as count = count / 4; -> 6

Page 6 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

count %= 4; // same as count = count % 4; -> 2

// Increment and decrement


int x = 5;
x++; // x becomes 6 (post-increment: use x, then increment)
x--; // x becomes 5 (post-decrement)
++x; // x becomes 6 (pre-increment: increment first, then use)

// Comparison operators (always return boolean)


[Link](10 > 5); // true
[Link](10 < 5); // false
[Link](10 >= 10); // true
[Link](10 <= 9); // false
[Link](10 == 10); // true
[Link](10 != 5); // true

// Logical operators
boolean hasTicket = true;
boolean isVIP = false;
[Link](hasTicket && isVIP); // false (AND: both must be true)
[Link](hasTicket || isVIP); // true (OR: at least one must be
true)
[Link](!hasTicket); // false (NOT: reverses the boolean)

Chapter 3: Control Flow — if/else, switch, Loops


3.1 The if/else Statement
The if statement is the foundation of decision-making in programming. It lets your program
choose different paths based on conditions. Think of it as the fork in a road: depending on a
condition (true or false), your program goes left or right.
// Basic if statement
int temperature = 35;
if (temperature > 30) {
[Link]("It is hot today!");
}

// if-else: one of two paths


int score = 65;
if (score >= 60) {
[Link]("You passed!");
} else {
[Link]("You failed. Please try again.");
}

// if-else if-else: multiple conditions


int marks = 78;
String grade;
if (marks >= 90) {
grade = "A+";
} else if (marks >= 80) {
grade = "A";
} else if (marks >= 70) {
grade = "B";
} else if (marks >= 60) {
grade = "C";

Page 7 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

} else {
grade = "F";
}
[Link]("Grade: " + grade); // Grade: B

// Nested if statements (checking multiple things)


boolean hasID = true;
int userAge = 22;
if (hasID) {
if (userAge >= 18) {
[Link]("Access granted.");
} else {
[Link]("You are too young.");
}
} else {
[Link]("Please show your ID.");
}

3.2 The Ternary Operator — Compact if/else


// Syntax: condition ? valueIfTrue : valueIfFalse
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
[Link](status); // Adult

// Useful for simple assignments


int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link]("Maximum: " + max); // Maximum: 20

// Real-world: showing user-friendly messages


int itemCount = 1;
String label = (itemCount == 1) ? "item" : "items";
[Link]("You have " + itemCount + " " + label + " in your cart.");
// Output: You have 1 item in your cart.

3.3 The switch Statement


// Traditional switch — good for checking one variable against many values
int dayNumber = 3;
String dayName;
switch (dayNumber) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
case 6: dayName = "Saturday"; break;
case 7: dayName = "Sunday"; break;
default: dayName = "Invalid day";
}
[Link](dayName); // Wednesday

// IMPORTANT: Without break, execution "falls through" to the next case!


// This is a common bug — always include break unless fall-through is
intentional.

// Modern switch expression (Java 14+) — cleaner syntax


String season = "Summer";
String activity = switch (season) {
case "Spring" -> "Plant flowers";

Page 8 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

case "Summer" -> "Go swimming";


case "Autumn", "Fall" -> "Rake leaves"; // multiple cases
case "Winter" -> "Build snowmen";
default -> "Stay indoors";
};
[Link](activity); // Go swimming

3.4 The for Loop


Loops let you repeat a block of code multiple times without rewriting it. The for loop is perfect
when you know exactly how many times you want to repeat something.
// Basic for loop structure:
// for (initialization; condition; update) { body }
for (int i = 1; i <= 5; i++) {
[Link]("Iteration: " + i);
}
// Output: Iteration: 1, 2, 3, 4, 5

// Counting down
for (int i = 10; i >= 1; i--) {
[Link](i + " ");
}
// Output: 10 9 8 7 6 5 4 3 2 1

// Looping through arrays (the enhanced for-each loop)


String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
for (String fruit : fruits) {
[Link]("Fruit: " + fruit);
}

// Nested loops — multiplication table


for (int row = 1; row <= 5; row++) {
for (int col = 1; col <= 5; col++) {
[Link]("%4d", row * col); // printf for formatted output
}
[Link](); // new line after each row
}
// Output:
// 1 2 3 4 5
// 2 4 6 8 10
// 3 6 9 12 15
// 4 8 12 16 20
// 5 10 15 20 25

3.5 The while and do-while Loops


// while loop: check condition BEFORE each iteration
// Use when you don't know in advance how many iterations you need
int userGuess = 0;
int secretNumber = 42;
int attempts = 0;
// Simulating: keep asking until correct
while (userGuess != secretNumber) {
userGuess = 40 + attempts; // simulating user input
attempts++;
if (attempts > 10) break; // safety net
}
[Link]("Found in " + attempts + " attempts!");

// do-while loop: check condition AFTER each iteration

Page 9 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

// The body ALWAYS runs at least once


int number = 1;
do {
[Link]("Number: " + number);
number++;
} while (number <= 3);
// Output: Number: 1, Number: 2, Number: 3

// Practical: input validation (always ask at least once)


// do {
// [Link]("Enter a positive number: ");
// number = [Link]();
// } while (number <= 0);

3.6 break, continue, and Reading User Input


import [Link];

public class UserInputDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// break: exit the loop immediately


for (int i = 1; i <= 10; i++) {
if (i == 5) {
[Link]("Stopping at 5!");
break; // exits the for loop entirely
}
[Link](i);
}
// Output: 1 2 3 4 Stopping at 5!

// continue: skip the rest of this iteration, go to next


for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
[Link](i + " ");
}
// Output: 1 3 5 7 9

// Reading user input with Scanner


[Link]("Enter your name: ");
String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Hello " + name + "! You are " + age + " years
old.");

[Link]();
}
}

Page 10 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

Chapter 4: Methods — Reusable Blocks of Code


4.1 What are Methods and Why Use Them?
A method is a named block of code that performs a specific task. You write it once and call it as
many times as needed. Methods are the foundation of organized, readable, maintainable code.
Without methods, programs would be one long sequence of instructions — difficult to
understand and impossible to maintain.
Think of methods as specialized workers in a factory. The main() method is the factory manager
— it orchestrates the work. Other methods are specialists: one worker calculates taxes, another
validates emails, another saves to the database. Each does exactly one thing and does it well.

4.2 Defining and Calling Methods


public class MethodDemo {

// Method with no parameters and no return value


public static void printWelcome() {
[Link]("========================");
[Link](" Welcome to MITS Java ");
[Link]("========================");
}

// Method with parameters and a return value


// Syntax: accessModifier returnType methodName(paramType paramName, ...) {
}
public static double calculateCircleArea(double radius) {
return [Link] * radius * radius;
}

// Method with multiple parameters


public static int add(int a, int b) {
return a + b;
}

// Method with multiple return paths


public static String getGrade(int marks) {
if (marks >= 90) return "A+";
if (marks >= 80) return "A";
if (marks >= 70) return "B";
if (marks >= 60) return "C";
return "F";
}

public static void main(String[] args) {


// Calling methods
printWelcome();

double area = calculateCircleArea(7.5);


[Link]("Circle area: %.2f%n", area);

int sum = add(15, 27);


[Link]("Sum: " + sum);

[Link]("Grade for 85: " + getGrade(85));


}
}

Page 11 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

4.3 Method Overloading


Method overloading allows you to define multiple methods with the same name but different
parameters. Java determines which method to call based on the arguments you provide. This
makes your API cleaner — instead of having calculateAreaCircle(), calculateAreaRectangle(),
calculateAreaTriangle(), you just have area() with different parameters.
public class Calculator {

// Three methods all named "area" — overloaded


public static double area(double radius) {
// Circle area
return [Link] * radius * radius;
}

public static double area(double length, double width) {


// Rectangle area
return length * width;
}

public static double area(double base, double height, String shape) {


// Triangle area (extra parameter to distinguish from rectangle)
return 0.5 * base * height;
}

public static void main(String[] args) {


[Link]("Circle area: %.2f%n", area(5.0));
[Link]("Rectangle area: %.2f%n", area(4.0, 6.0));
[Link]("Triangle area: %.2f%n", area(3.0, 8.0, "triangle"));
}
}

4.4 Variable Scope — Where Variables Live


public class ScopeDemo {

// Class-level variable (field) — accessible throughout the class


static int classVariable = 100;

public static void demonstrateScope() {


// Method-level variable — only exists inside this method
int methodVariable = 50;
[Link](classVariable); // OK — class variable accessible
[Link](methodVariable); // OK — same method

if (true) {
// Block-level variable — only exists inside this if block
int blockVariable = 25;
[Link](blockVariable); // OK
}
// [Link](blockVariable); // ERROR! blockVariable out of
scope
}

public static void main(String[] args) {


demonstrateScope();
[Link](classVariable); // OK
// [Link](methodVariable); // ERROR! Not in scope here
}
}

Page 12 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

Chapter 5: Object-Oriented Programming (OOP)


5.1 The OOP Philosophy
Object-Oriented Programming is a way of organizing code by modeling real-world entities as
"objects." Each object has characteristics (data, called fields or attributes) and behaviors
(actions, called methods). OOP solves the problem of complexity: as programs grow larger,
procedural code becomes an unmanageable tangle. OOP lets you organize code into modular,
self-contained units.
The four pillars of OOP are: (1) Encapsulation — bundling data and methods together, hiding
internal details. (2) Inheritance — creating new classes based on existing ones. (3)
Polymorphism — the same method name behaving differently in different contexts. (4)
Abstraction — exposing only what is necessary, hiding complexity.

5.2 Classes and Objects


A class is a blueprint or template. An object is a specific instance created from that blueprint.
Think of a class as the architectural plan for a house, and objects as the actual houses built
from that plan. Many houses can be built from the same plan, each with its own address, color,
and residents.
// Class definition — the blueprint
public class Student {
// Fields (instance variables) — data each Student object holds
String name;
int age;
double gpa;
String course;

// Constructor — called when creating a new object with 'new'


// Same name as the class, no return type
public Student(String name, int age, double gpa, String course) {
// 'this' refers to the current object being created
[Link] = name;
[Link] = age;
[Link] = gpa;
[Link] = course;
}

// Methods — behaviors of a Student


public void study() {
[Link](name + " is studying " + course);
}

public boolean isHonourRoll() {


return gpa >= 3.5;
}

public String getInfo() {


return [Link]("Student: %s | Age: %d | GPA: %.1f | Course: %s",
name, age, gpa, course);
}

// toString() — called automatically when printing an object

Page 13 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

@Override
public String toString() {
return getInfo();
}
}

// Using the class — creating objects


public class Main {
public static void main(String[] args) {
// Creating Student objects with 'new'
Student alice = new Student("Alice", 20, 3.8, "Java Programming");
Student bob = new Student("Bob", 22, 3.2, "Data Science");

// Calling methods on objects


[Link](); // Alice is studying Java Programming
[Link]([Link]()); // true
[Link](bob); // calls toString() automatically

// Each object has its own independent data


[Link] = 3.9; // only alice's GPA changes
[Link]("Alice GPA: " + [Link]); // 3.9
[Link]("Bob GPA: " + [Link]); // 3.2 (unchanged)
}
}

5.3 Encapsulation — Protecting Your Data


Encapsulation means making your class's fields private (hidden) and providing public getter and
setter methods to access and modify them. This prevents outside code from setting invalid
values — for example, a bank account should never have a negative balance, and a student's
age should not be set to -5.
public class BankAccount {
// Private fields — cannot be accessed directly from outside
private String accountHolder;
private double balance;
private String accountNumber;

public BankAccount(String holder, String number, double initialDeposit) {


[Link] = holder;
[Link] = number;
if (initialDeposit < 0) {
throw new IllegalArgumentException("Initial deposit cannot be
negative");
}
[Link] = initialDeposit;
}

// Getter — read-only access to private field


public double getBalance() {
return balance;
}

public String getAccountHolder() {


return accountHolder;
}

// deposit — validates input before changing balance


public void deposit(double amount) {
if (amount <= 0) {
[Link]("Deposit amount must be positive.");

Page 14 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

return;
}
balance += amount;
[Link]("Deposited: ₹%.2f | New Balance: ₹%.2f%n", amount,
balance);
}

// withdraw — validates before changing balance


public void withdraw(double amount) {
if (amount <= 0) {
[Link]("Withdrawal amount must be positive.");
return;
}
if (amount > balance) {
[Link]("Insufficient funds!");
return;
}
balance -= amount;
[Link]("Withdrawn: ₹%.2f | Remaining: ₹%.2f%n", amount,
balance);
}

public void printStatement() {


[Link]("--- Account Statement ---");
[Link]("Account: " + accountNumber);
[Link]("Holder: " + accountHolder);
[Link]("Balance: ₹%.2f%n", balance);
}
}

// Main usage
BankAccount acc = new BankAccount("Ravi Kumar", "ACC001", 10000.0);
[Link](5000); // Deposited: ₹5000.00 | New Balance: ₹15000.00
[Link](3000); // Withdrawn: ₹3000.00 | Remaining: ₹12000.00
[Link](20000); // Insufficient funds!
[Link]();
// [Link] = -999; // COMPILE ERROR! balance is private

5.4 Inheritance — Building on Existing Classes


Inheritance allows a class (child/subclass) to inherit fields and methods from another class
(parent/superclass). This promotes code reuse — you define common behavior once in the
parent and share it across all children. It also models real-world hierarchies: every Dog is an
Animal, every Car is a Vehicle, every Manager is an Employee.
// Parent class (superclass)
public class Animal {
protected String name;
protected int age;

public Animal(String name, int age) {


[Link] = name;
[Link] = age;
}

public void eat() {


[Link](name + " is eating.");
}

public void breathe() {


[Link](name + " is breathing.");

Page 15 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

public String toString() {


return name + " (age " + age + ")";
}
}

// Child class (subclass) — inherits from Animal


public class Dog extends Animal {
private String breed;

public Dog(String name, int age, String breed) {


super(name, age); // Calls Animal's constructor — MUST be first line
[Link] = breed;
}

// Method specific to Dog


public void bark() {
[Link](name + " says: Woof! Woof!");
}

public void fetch() {


[Link](name + " fetches the ball!");
}

// Override toString() from Animal


@Override
public String toString() {
return [Link]() + " | Breed: " + breed;
}
}

public class Cat extends Animal {


private boolean isIndoor;

public Cat(String name, int age, boolean isIndoor) {


super(name, age);
[Link] = isIndoor;
}

public void meow() {


[Link](name + " says: Meow!");
}

public void purr() {


[Link](name + " is purring...");
}
}

// Usage
Dog rex = new Dog("Rex", 3, "German Shepherd");
[Link](); // Inherited from Animal: Rex is eating.
[Link](); // Inherited from Animal
[Link](); // Dog-specific: Rex says: Woof! Woof!
[Link](rex); // Rex (age 3) | Breed: German Shepherd

Cat kitty = new Cat("Kitty", 2, true);


[Link](); // Inherited
[Link](); // Cat-specific

Page 16 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

5.5 Polymorphism and Abstract Classes


// Abstract class: cannot be instantiated, defines a template
public abstract class Shape {
protected String color;

public Shape(String color) {


[Link] = color;
}

// Abstract method: subclasses MUST implement this


public abstract double area();
public abstract double perimeter();

// Concrete method: shared by all shapes


public void describe() {
[Link]("%s %s: area=%.2f, perimeter=%.2f%n",
color, getClass().getSimpleName(), area(), perimeter());
}
}

public class Circle extends Shape {


private double radius;

public Circle(String color, double radius) {


super(color);
[Link] = radius;
}

@Override
public double area() { return [Link] * radius * radius; }

@Override
public double perimeter() { return 2 * [Link] * radius; }
}

public class Rectangle extends Shape {


private double length, width;

public Rectangle(String color, double length, double width) {


super(color);
[Link] = length;
[Link] = width;
}

@Override
public double area() { return length * width; }

@Override
public double perimeter() { return 2 * (length + width); }
}

// Polymorphism: treating different objects through a common type


Shape[] shapes = {
new Circle("Red", 5),
new Rectangle("Blue", 4, 6),
new Circle("Green", 3)
};

for (Shape shape : shapes) {


[Link](); // calls the RIGHT area/perimeter for each shape type

Page 17 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

}
// Red Circle: area=78.54, perimeter=31.42
// Blue Rectangle: area=24.00, perimeter=20.00
// Green Circle: area=28.27, perimeter=18.85

5.6 Interfaces — Defining Contracts


// Interface: a pure contract — only method signatures, no implementation
// (Java 8+ allows default methods, but core purpose is defining behavior)
public interface Payable {
double calculatePay(); // must be implemented by any class that
implements this interface
void printPaySlip();
}

public interface Trainable {


void train(String skill);
boolean hasSkill(String skill);
}

// A class can implement MULTIPLE interfaces (unlike inheritance, single parent


only)
public class Employee implements Payable, Trainable {
private String name;
private double hourlyRate;
private int hoursWorked;
private List<String> skills = new ArrayList<>();

public Employee(String name, double hourlyRate, int hoursWorked) {


[Link] = name;
[Link] = hourlyRate;
[Link] = hoursWorked;
}

@Override
public double calculatePay() {
return hourlyRate * hoursWorked;
}

@Override
public void printPaySlip() {
[Link]("--- Pay Slip for %s ---%n", name);
[Link]("Hours: %d | Rate: ₹%.2f/hr | Total: ₹%.2f%n",
hoursWorked, hourlyRate, calculatePay());
}

@Override
public void train(String skill) {
[Link](skill);
[Link](name + " learned: " + skill);
}

@Override
public boolean hasSkill(String skill) {
return [Link](skill);
}
}

Employee emp = new Employee("Priya", 250.0, 160);


[Link]("Java");
[Link]("Spring Boot");

Page 18 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

[Link]([Link]("Java")); // true
[Link]();

Chapter 6: Exception Handling


6.1 What are Exceptions?
An exception is an unexpected event that disrupts the normal flow of a program. Without
exception handling, a single error causes your entire program to crash. Exception handling lets
you anticipate errors, handle them gracefully, show helpful messages to users, and keep the
program running.
Common exceptions: ArithmeticException (dividing by zero), NullPointerException (calling a
method on null), ArrayIndexOutOfBoundsException (accessing array beyond its size),
NumberFormatException (parsing "abc" as an integer), FileNotFoundException (trying to read a
missing file).

6.2 try-catch-finally
public class ExceptionDemo {
public static void main(String[] args) {

// Basic try-catch
try {
int result = 10 / 0; // This throws ArithmeticException
[Link](result); // Never reached
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero!");
[Link]("Details: " + [Link]()); // / by zero
}

// Multiple catch blocks


String[] names = {"Alice", "Bob"};
try {
[Link](names[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of bounds: " + [Link]());
} catch (Exception e) {
// Catch-all for any other exception
[Link]("Unexpected error: " + [Link]());
}

// finally block: ALWAYS runs, whether exception occurred or not


// Used for cleanup: closing files, database connections, etc.
try {
int[] numbers = {1, 2, 3};
[Link](numbers[1]); // OK
} catch (Exception e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("This always runs — cleanup code goes here.");
}

// Catching NullPointerException
String name = null;
try {

Page 19 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

[Link]([Link]()); // NullPointerException!
} catch (NullPointerException e) {
[Link]("Name is null — please provide a valid name.");
}
}
}

6.3 Custom Exceptions


// Define custom exception classes for domain-specific errors
public class InsufficientFundsException extends Exception {
private double amount;

public InsufficientFundsException(double amount) {


super("Insufficient funds. Attempted to withdraw: ₹" + amount);
[Link] = amount;
}

public double getAmount() { return amount; }


}

public class InvalidAgeException extends RuntimeException {


public InvalidAgeException(String message) {
super(message);
}
}

// Using custom exceptions


public class Bank {
private double balance = 5000.0;

// Method declares it can throw InsufficientFundsException


public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount);
}
balance -= amount;
[Link]("Withdrawn ₹%.2f | Balance: ₹%.2f%n", amount,
balance);
}

public static void main(String[] args) {


Bank bank = new Bank();
try {
[Link](2000); // OK
[Link](5000); // Throws InsufficientFundsException
} catch (InsufficientFundsException e) {
[Link]("Transaction failed: " + [Link]());
}
}
}

Page 20 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

Chapter 7: Java Collections Framework


7.1 Overview of Collections
Java's Collections Framework provides ready-made data structures so you don't have to build
them from scratch. The main interfaces are: List (ordered, allows duplicates), Set (unordered,
no duplicates), Map (key-value pairs), Queue (FIFO — first in, first out). Each interface has
multiple implementations with different performance characteristics.

7.2 ArrayList — Dynamic Array


import [Link];
import [Link];

public class ArrayListDemo {


public static void main(String[] args) {
// ArrayList: dynamic size, ordered, allows duplicates
ArrayList<String> students = new ArrayList<>();

// Adding elements
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
[Link](1, "David"); // Insert at index 1
[Link](students); // [Alice, David, Bob, Charlie]

// Accessing elements
[Link]([Link](0)); // Alice (by index)
[Link]([Link]()); // 4
[Link]([Link]("Bob")); // true
[Link]([Link]("Charlie")); // 3

// Removing elements
[Link]("Bob"); // remove by value
[Link](0); // remove by index
[Link](students); // [David, Charlie]

// Iterating
for (String student : students) {
[Link]("Student: " + student);
}

// Sorting
ArrayList<Integer> numbers = new ArrayList<>();
[Link](5); [Link](2); [Link](8); [Link](1);
[Link](numbers); // ascending: [1, 2, 5, 8]
[Link](numbers, [Link]()); // descending
[Link](numbers); // [8, 5, 2, 1]

// Converting array to ArrayList


String[] arr = {"X", "Y", "Z"};
ArrayList<String> list = new ArrayList<>([Link](arr));
}
}

7.3 HashMap — Key-Value Storage


import [Link];
import [Link];

Page 21 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

public class HashMapDemo {


public static void main(String[] args) {
// HashMap: stores key-value pairs, fast lookup by key
HashMap<String, Integer> studentMarks = new HashMap<>();

// Adding entries
[Link]("Alice", 92);
[Link]("Bob", 85);
[Link]("Charlie", 78);
[Link]("Alice", 95); // Updates existing key

// Accessing values
[Link]([Link]("Alice")); // 95
[Link]([Link]("David")); // null (key doesn't
exist)
[Link]([Link]("David", 0)); // 0 (safe)

// Checking existence
[Link]([Link]("Bob")); // true
[Link]([Link](78)); // true

// Iterating over a HashMap


for ([Link]<String, Integer> entry : [Link]()) {
[Link]("%s scored %d%n", [Link](),
[Link]());
}

// Real-world example: word frequency counter


String text = "the quick brown fox jumps over the lazy dog the fox";
HashMap<String, Integer> wordCount = new HashMap<>();
for (String word : [Link](" ")) {
[Link](word, [Link](word, 0) + 1);
}
[Link](wordCount);
// {the=3, quick=1, brown=1, fox=2, jumps=1, over=1, lazy=1, dog=1}
}
}

7.4 LinkedList, HashSet, and Stack


import [Link].*;

// HashSet — unique values only, very fast contains() check


HashSet<String> uniqueCities = new HashSet<>();
[Link]("Mumbai");
[Link]("Delhi");
[Link]("Mumbai"); // Duplicate — ignored
[Link]([Link]()); // 2

// LinkedList — efficient insertions/deletions, also works as Queue/Deque


LinkedList<String> queue = new LinkedList<>();
[Link]("Task 1"); // add to end
[Link]("Task 2");
[Link]("Task 3");
[Link]([Link]()); // remove and return front: "Task 1"
[Link]([Link]()); // look at front without removing: "Task 2"

// Stack — LIFO (Last In, First Out): like a stack of plates


Stack<Integer> stack = new Stack<>();
[Link](10);

Page 22 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

[Link](20);
[Link](30);
[Link]([Link]()); // 30 (last in, first out)
[Link]([Link]()); // 20 (look without removing)

Chapter 8: File Input/Output


8.1 Reading and Writing Text Files
import [Link].*;
import [Link].*;
import [Link];

public class FileDemo {

// Writing to a file
public static void writeFile(String filename, String content) throws
IOException {
// BufferedWriter: efficient writing, wraps FileWriter
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(filename))) {
[Link](content);
[Link](); // platform-independent newline
}
// try-with-resources: automatically closes the writer even if
exception occurs
[Link]("File written: " + filename);
}

// Reading from a file line by line


public static void readFile(String filename) throws IOException {
try (BufferedReader reader = new BufferedReader(new
FileReader(filename))) {
String line;
int lineNum = 1;
while ((line = [Link]()) != null) {
[Link]("%3d: %s%n", lineNum++, line);
}
}
}

// Using modern NIO (Java 11+) — simpler API


public static void modernFileOps() throws IOException {
Path path = [Link]("[Link]");

// Write all lines at once


List<String> lines = [Link]("Line 1", "Line 2", "Line 3");
[Link](path, lines);

// Read all lines at once


List<String> readLines = [Link](path);
[Link]([Link]::println);

// Read entire file as one String


String content = [Link](path);

// Check if file exists

Page 23 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

[Link]([Link](path)); // true

// Delete file
[Link](path);
}

public static void main(String[] args) {


try {
writeFile("[Link]", "Alice - 92
Bob - 85
Charlie - 78");
readFile("[Link]");
modernFileOps();
} catch (IOException e) {
[Link]("File error: " + [Link]());
}
}
}

8.2 Working with CSV Files


import [Link].*;
import [Link].*;

public class CSVHandler {

// Writing a CSV file


public static void writeCSV(String filename) throws IOException {
try (PrintWriter pw = new PrintWriter(new FileWriter(filename))) {
[Link]("Name,Age,City,Score"); // header row
[Link]("Alice,22,Mumbai,92");
[Link]("Bob,25,Delhi,85");
[Link]("Charlie,20,Pune,78");
}
[Link]("CSV written.");
}

// Reading a CSV file and creating objects


public static List<String[]> readCSV(String filename) throws IOException {
List<String[]> data = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filename)))
{
String line;
boolean isHeader = true;
while ((line = [Link]()) != null) {
if (isHeader) { isHeader = false; continue; } // skip header
[Link]([Link](","));
}
}
return data;
}

public static void main(String[] args) throws IOException {


writeCSV("[Link]");
List<String[]> rows = readCSV("[Link]");
for (String[] row : rows) {
[Link]("Name: %s | Age: %s | City: %s | Score: %s%n",
row[0], row[1], row[2], row[3]);
}
}
}

Page 24 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

Chapter 9: Generics & Functional Programming (Java


8+)
9.1 Generics — Type-Safe Reusable Code
Generics allow you to write a class or method that works with any type, while still being type-
safe. Without generics, you would need separate ArrayListOfStrings, ArrayListOfIntegers, etc.
With generics, one ArrayList<T> works for all types.
// Generic class — T is a type parameter (placeholder)
public class Pair<T, U> {
private T first;
private U second;

public Pair(T first, U second) {


[Link] = first;
[Link] = second;
}

public T getFirst() { return first; }


public U getSecond() { return second; }

@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}

// Using the generic class with different types


Pair<String, Integer> studentScore = new Pair<>("Alice", 95);
Pair<String, String> cityCountry = new Pair<>("Mumbai", "India");
Pair<Integer, Boolean> result = new Pair<>(42, true);

[Link](studentScore); // (Alice, 95)


[Link](cityCountry); // (Mumbai, India)

// Generic method
public static <T extends Comparable<T>> T findMax(T[] array) {
T max = array[0];
for (T item : array) {
if ([Link](max) > 0) max = item;
}
return max;
}

Integer[] nums = {3, 7, 1, 9, 4};


String[] words = {"banana", "apple", "cherry"};
[Link](findMax(nums)); // 9
[Link](findMax(words)); // cherry

9.2 Lambda Expressions & Functional Interfaces


Java 8 introduced lambda expressions — a concise way to write anonymous functions
(functions without a name). Lambdas let you pass behavior as data, enabling functional

Page 25 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

programming style. They work with functional interfaces — interfaces with exactly one abstract
method.
import [Link].*;
import [Link].*;

public class LambdaDemo {


public static void main(String[] args) {

// Before lambdas: anonymous inner class


Runnable oldStyle = new Runnable() {
@Override
public void run() {
[Link]("Running the old way...");
}
};

// With lambda: concise version


Runnable newStyle = () -> [Link]("Running with lambda!");
[Link]();

// Lambda with parameters


// Comparator: used for sorting, takes two items and returns -/0/+
List<String> names = [Link]("Charlie", "Alice", "Bob");
[Link]((a, b) -> [Link](b)); // sort alphabetically
[Link](names); // [Alice, Bob, Charlie]

// Built-in functional interfaces


// Predicate<T>: takes T, returns boolean (for filtering)
Predicate<Integer> isEven = n -> n % 2 == 0;
[Link]([Link](4)); // true
[Link]([Link](7)); // false

// Function<T, R>: takes T, returns R (for transforming)


Function<String, Integer> getLength = s -> [Link]();
[Link]([Link]("Hello")); // 5

// Consumer<T>: takes T, returns nothing (for side effects)


Consumer<String> printer = s -> [Link](">> " + s);
[Link]("Hello World"); // >> Hello World

// Supplier<T>: takes nothing, returns T (for providing values)


Supplier<String> greeting = () -> "Good Morning!";
[Link]([Link]()); // Good Morning!
}
}

9.3 Stream API — Processing Collections Elegantly


import [Link].*;
import [Link].*;

public class StreamDemo {


public static void main(String[] args) {

List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// filter — keep only even numbers


List<Integer> evens = [Link]()
.filter(n -> n % 2 == 0)
.collect([Link]());

Page 26 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

[Link]("Evens: " + evens); // [2, 4, 6, 8, 10]

// map — transform each element


List<Integer> squares = [Link]()
.map(n -> n * n)
.collect([Link]());
[Link]("Squares: " + squares);

// reduce — combine all elements into one result


int sum = [Link]()
.reduce(0, Integer::sum);
[Link]("Sum: " + sum); // 55

// Chaining multiple operations


int sumOfSquaresOfEvens = [Link]()
.filter(n -> n % 2 == 0) // keep evens: [2,4,6,8,10]
.map(n -> n * n) // square them: [4,16,36,64,100]
.reduce(0, Integer::sum); // sum: 220
[Link]("Sum of squares of evens: " + sumOfSquaresOfEvens);

// Working with objects


List<String> students = [Link]("Alice", "Bob", "Charlie",
"Anna", "David");

// Find all names starting with 'A', sorted, as uppercase


List<String> result = [Link]()
.filter(name -> [Link]("A"))
.sorted()
.map(String::toUpperCase)
.collect([Link]());
[Link](result); // [ALICE, ANNA]

// Statistics
OptionalDouble avg = [Link]()
.mapToInt(Integer::intValue)
.average();
[Link]("Average: " + [Link]()); // 5.5

// Counting
long count = [Link]()
.filter(s -> [Link]() > 4)
.count();
[Link]("Names longer than 4 chars: " + count);
}
}

Chapter 10: Multithreading & Concurrency


10.1 What is Multithreading?
A thread is a lightweight sub-process — the smallest unit of execution within a program. By
default, every Java program has one thread: the main thread. Multithreading allows multiple
threads to run simultaneously, making programs faster and more responsive. For example, a
web server handles thousands of requests simultaneously — each request gets its own thread.

Page 27 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

10.2 Creating Threads


// Method 1: Extending Thread class
public class CounterThread extends Thread {
private String name;
private int count;

public CounterThread(String name, int count) {


[Link] = name;
[Link] = count;
}

@Override
public void run() {
for (int i = 1; i <= count; i++) {
[Link](name + ": " + i);
try {
[Link](100); // pause 100ms (simulates work)
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}

// Method 2: Implementing Runnable interface (preferred)


public class Task implements Runnable {
private String taskName;

public Task(String taskName) {


[Link] = taskName;
}

@Override
public void run() {
[Link]("Starting: " + taskName);
// Simulate work
for (int i = 0; i < 3; i++) {
[Link](taskName + " step " + (i+1));
}
[Link]("Completed: " + taskName);
}
}

public class ThreadDemo {


public static void main(String[] args) throws InterruptedException {
// Method 1
CounterThread t1 = new CounterThread("Thread-A", 5);
CounterThread t2 = new CounterThread("Thread-B", 5);
[Link](); // starts the thread (DO NOT call run() directly!)
[Link](); // both threads run concurrently

// Method 2
Thread worker1 = new Thread(new Task("Download"));
Thread worker2 = new Thread(new Task("Upload"));
[Link]();
[Link]();

// Lambda as Runnable (Java 8+)


Thread quickTask = new Thread(() -> [Link]("Quick task
done!"));

Page 28 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

[Link]();

// Wait for threads to finish before continuing


[Link]();
[Link]();
[Link]("All threads completed!");
}
}

10.3 Thread Safety and synchronized


// Problem: multiple threads modifying shared data causes race conditions
public class Counter {
private int count = 0;

// Without synchronized: multiple threads can corrupt the value


// With synchronized: only one thread executes this method at a time
public synchronized void increment() {
count++;
}

public synchronized int getCount() {


return count;
}
}

// Using ExecutorService — recommended modern approach


import [Link].*;

ExecutorService executor = [Link](4); // 4 worker threads

for (int i = 0; i < 10; i++) {


final int taskId = i;
[Link](() -> {
[Link]("Task " + taskId + " executed by " +
[Link]().getName());
});
}

[Link](); // no new tasks


[Link](10, [Link]); // wait for all to finish

Chapter 11: Spring Boot — Building REST APIs


11.1 What is Spring Boot?
Spring Boot is the most popular Java framework for building web applications and REST APIs. It
takes the powerful but complex Spring Framework and makes it easy to use with auto-
configuration and sensible defaults. You can create a production-ready REST API in minutes.
Spring Boot powers the backends of companies like Airbnb, LinkedIn, and countless Indian
startups and enterprises.

Page 29 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

11.2 Setting Up a Spring Boot Project


Visit [Link] Choose: Project: Maven, Language: Java, Spring Boot: 3.x.x, Group:
[Link], Artifact: student-api. Add Dependencies: Spring Web, Spring Data JPA, H2
Database (in-memory). Click "Generate" to download a zip. Extract and open in VS Code or
IntelliJ IDEA.

11.3 Creating a REST Controller


// [Link] — Model class (represents data)
package [Link];

public class Student {


private Long id;
private String name;
private int age;
private String course;
private double gpa;

// Constructors, getters, setters (or use Lombok @Data)


public Student() {}

public Student(Long id, String name, int age, String course, double gpa) {
[Link] = id;
[Link] = name;
[Link] = age;
[Link] = course;
[Link] = gpa;
}

// Getters and setters...


public Long getId() { return id; }
public void setId(Long id) { [Link] = id; }
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
public int getAge() { return age; }
public void setAge(int age) { [Link] = age; }
public String getCourse() { return course; }
public void setCourse(String course) { [Link] = course; }
public double getGpa() { return gpa; }
public void setGpa(double gpa) { [Link] = gpa; }
}
// [Link] — REST API endpoints
package [Link];

import [Link];
import [Link].*;
import [Link].*;

@RestController // Marks this as a REST API controller


@RequestMapping("/api/students") // Base URL for all endpoints
public class StudentController {

// In-memory list (replace with database in production)


private List<Student> students = new ArrayList<>([Link](
new Student(1L, "Alice", 20, "Java", 3.8),
new Student(2L, "Bob", 22, "Python", 3.5),
new Student(3L, "Charlie", 21, "DSA", 3.2)
));
private Long nextId = 4L;

Page 30 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

// GET /api/students — retrieve all students


@GetMapping
public List<Student> getAllStudents() {
return students;
}

// GET /api/students/{id} — get one student by ID


@GetMapping("/{id}")
public ResponseEntity<Student> getStudentById(@PathVariable Long id) {
return [Link]()
.filter(s -> [Link]().equals(id))
.findFirst()
.map(ResponseEntity::ok)
.orElse([Link]().build());
}

// POST /api/students — create a new student


@PostMapping
public Student createStudent(@RequestBody Student student) {
[Link](nextId++);
[Link](student);
return student;
}

// PUT /api/students/{id} — update an existing student


@PutMapping("/{id}")
public ResponseEntity<Student> updateStudent(@PathVariable Long id,
@RequestBody Student updated)
{
for (Student s : students) {
if ([Link]().equals(id)) {
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
return [Link](s);
}
}
return [Link]().build();
}

// DELETE /api/students/{id} — remove a student


@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {
boolean removed = [Link](s -> [Link]().equals(id));
return removed ? [Link]().build()
: [Link]().build();
}
}
Run the application with: mvn spring-boot:run or clicking Run in your IDE. Test the API using
Postman or curl:
# GET all students
curl [Link]

# GET student with ID 1


curl [Link]

# POST new student


curl -X POST [Link] \

Page 31 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

-H "Content-Type: application/json" \
-d '{"name":"Diana","age":23,"course":"Spring Boot","gpa":3.9}'

# DELETE student with ID 2


curl -X DELETE [Link]

Chapter 12: Capstone Projects


Project 1: Student Management System (Console)
Build a complete command-line Student Management System using OOP principles,
Collections, File I/O, and Exception Handling.
import [Link].*;
import [Link].*;

// Student model
class Student {
private static int nextId = 1;
private int id;
private String name;
private int age;
private String course;
private double gpa;

public Student(String name, int age, String course, double gpa) {


[Link] = nextId++;
[Link] = name;
[Link] = age;
[Link] = course;
[Link] = gpa;
}

// Getters
public int getId() { return id; }
public String getName() { return name; }
public double getGpa() { return gpa; }
public String getCourse() { return course; }

@Override
public String toString() {
return [Link]("[%d] %-15s | Age: %2d | Course: %-15s | GPA:
%.1f",
id, name, age, course, gpa);
}
}

// Management System
public class StudentManagementSystem {
private ArrayList<Student> students = new ArrayList<>();
private Scanner sc = new Scanner([Link]);

public void run() {


[Link]("=== MITS Student Management System ===");
boolean running = true;
while (running) {
[Link]("

Page 32 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

1. Add Student");
[Link]("2. View All Students");
[Link]("3. Search by Name");
[Link]("4. View Top Students (GPA > 3.5)");
[Link]("5. Sort by GPA");
[Link]("6. Save to File");
[Link]("0. Exit");
[Link]("Choice: ");

int choice = [Link](); [Link]();

switch (choice) {
case 1 -> addStudent();
case 2 -> viewAll();
case 3 -> searchByName();
case 4 -> topStudents();
case 5 -> sortByGPA();
case 6 -> saveToFile();
case 0 -> running = false;
default -> [Link]("Invalid choice!");
}
}
[Link]("Goodbye!");
}

private void addStudent() {


[Link]("Name: "); String name = [Link]();
[Link]("Age: "); int age = [Link](); [Link]();
[Link]("Course: "); String course = [Link]();
[Link]("GPA: "); double gpa = [Link](); [Link]();
[Link](new Student(name, age, course, gpa));
[Link]("Student added successfully!");
}

private void viewAll() {


if ([Link]()) { [Link]("No students."); return; }
[Link]("--- All Students ---");
[Link]([Link]::println);
}

private void searchByName() {


[Link]("Enter name to search: ");
String query = [Link]().toLowerCase();
[Link]()
.filter(s -> [Link]().toLowerCase().contains(query))
.forEach([Link]::println);
}

private void topStudents() {


[Link]()
.filter(s -> [Link]() >= 3.5)
.sorted((a, b) -> [Link]([Link](), [Link]()))
.forEach([Link]::println);
}

private void sortByGPA() {


[Link]()
.sorted((a, b) -> [Link]([Link](), [Link]()))
.forEach([Link]::println);
}

Page 33 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

private void saveToFile() {


try (PrintWriter pw = new PrintWriter(new FileWriter("[Link]")))
{
[Link](s -> [Link]([Link]()));
[Link]("Saved " + [Link]() + " students to
[Link]");
} catch (IOException e) {
[Link]("Error saving: " + [Link]());
}
}

public static void main(String[] args) {


new StudentManagementSystem().run();
}
}

Project 2: Library Book Management System


import [Link].*;
import [Link];

enum BookStatus { AVAILABLE, BORROWED }

class Book {
private String isbn, title, author;
private BookStatus status = [Link];
private String borrowerName;
private LocalDate dueDate;

public Book(String isbn, String title, String author) {


[Link] = isbn;
[Link] = title;
[Link] = author;
}

public boolean isAvailable() { return status == [Link]; }

public void borrow(String borrower) {


[Link] = [Link];
[Link] = borrower;
[Link] = [Link]().plusDays(14);
}

public void returnBook() {


[Link] = [Link];
[Link] = null;
[Link] = null;
}

public String getIsbn() { return isbn; }


public String getTitle() { return title; }

@Override
public String toString() {
String info = [Link]("[%s] '%s' by %s — %s", isbn, title,
author, status);
if (!isAvailable()) {
info += " (Borrowed by: " + borrowerName + ", Due: " + dueDate +
")";
}
return info;

Page 34 | MITS Academy | [Link]


MITS Academy — Java Programming — Complete Ebook

}
}

public class Library {


private HashMap<String, Book> catalog = new HashMap<>();
private Scanner sc = new Scanner([Link]);

public void addBook(Book book) {


[Link]([Link](), book);
}

public void borrowBook() {


[Link]("Enter ISBN: ");
String isbn = [Link]();
Book book = [Link](isbn);
if (book == null) { [Link]("Book not found!"); return; }
if (![Link]()) { [Link]("Already borrowed!");
return; }
[Link]("Your name: ");
String borrower = [Link]();
[Link](borrower);
[Link]("Borrowed! Due in 14 days: " +
[Link]().plusDays(14));
}

public void showAll() {


[Link]().forEach([Link]::println);
}

public static void main(String[] args) {


Library lib = new Library();
[Link](new Book("ISBN001", "Clean Code", "Robert C. Martin"));
[Link](new Book("ISBN002", "Effective Java", "Joshua Bloch"));
[Link](new Book("ISBN003", "Head First Java", "Kathy Sierra"));
[Link]();
[Link]();
[Link]();
}
}

What to Learn Next


• Spring Boot with JPA/Hibernate: Connect your REST API to a real MySQL or PostgreSQL
database
• Spring Security with JWT: Add authentication and authorization to your APIs
• Microservices with Spring Cloud: Build distributed systems with multiple independent
services
• Docker & Kubernetes: Package and deploy your Java applications in containers
• Design Patterns: Learn Singleton, Factory, Builder, Observer, Strategy patterns
• JUnit & Mockito: Write automated tests for your Java code
• Apache Kafka: Build event-driven systems for high-throughput data processing
• Android Development: Use your Java skills to build mobile apps

Page 35 | MITS Academy | [Link]

You might also like