0% found this document useful (0 votes)
4 views312 pages

Java

The document provides an overview of Java, including its features, components (JDK, JRE, JVM), and basic programming concepts such as variables, data types, and control statements. It emphasizes Java's object-oriented nature, platform independence, and applications in various domains like web and mobile development. Additionally, it outlines the structure of a Java program and the compilation and execution process.

Uploaded by

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

Java

The document provides an overview of Java, including its features, components (JDK, JRE, JVM), and basic programming concepts such as variables, data types, and control statements. It emphasizes Java's object-oriented nature, platform independence, and applications in various domains like web and mobile development. Additionally, it outlines the structure of a Java program and the compilation and execution process.

Uploaded by

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

JAVA

Basics of Java
 Introduction to Java
 Features of Java (platform independent, object-oriented)
 JDK, JRE, JVM
 Structure of a Java program
 Variables, data types, operators
 Input/output in Java
 Control statements (if, switch, loops)

2. Object-Oriented Programming (OOP)


 Classes and Objects
 Constructors
 Encapsulation
 Inheritance
 Polymorphism (overloading & overriding)
 Abstraction (abstract class & interfaces)

1
Introduction to Java

2
5
What is Java?
Java is a high-level, object-oriented programming language developed by Sun
Microsystems in 1995.
Later, it was acquired by Oracle Corporation.
Java is widely used for:
• Desktop applications
• Web applications
• Mobile apps (Android)
• Enterprise software
• Banking systems
• Cloud applications

Java follows the principle:


“Write Once, Run Anywhere” (WORA)
This means a Java program can run on any operating system if Java is installed.

Java என் பது ஒரு powerful programming language.


ஒருமுறை program எழுதினால் அது Windows, Linux, Mac பபான் ை
பல operating systems-ல் run ஆகும் .
3
Features of Java

4
6
1. Simple – Easy to learn
2. Object-Oriented – Based on classes and objects
3. Platform Independent – Runs on any OS
4. Secure – Safer than many languages
5. Robust – Handles errors effectively
6. Multithreaded – Can perform multiple tasks simultaneously

5
Components of Java

6
6
1. JVM (Java Virtual Machine)
• Executes Java bytecode
• Makes Java platform independent
2. JRE (Java Runtime Environment)
• Provides libraries and JVM to run Java programs
3. JDK (Java Development Kit)
7
• Complete package for Java development
• Includes JRE + compiler + tools

First Java Program


class Hello {
public static void main(String[] args) {
[Link]("Hello World");
}
}
Output
Hello World

Explanation of Program
class Hello
• Defines a class named Hello
public static void main(String[] args)
• Main method where execution starts
[Link]()
• Used to print output

Compilation and Execution Process

8
9
5
Step 1: Write Program

10
Save file as:
[Link]
Step 2: Compile
javac [Link]
Step 3: Run
java Hello

Applications of Java

11
6
• Web applications
• Android applications
• Banking software
• E-commerce systems
12
• Scientific applications
• Cloud computing

Advantages of Java

• Easy to learn
• Large community support
• High demand in jobs
• Powerful frameworks like Spring Boot

• பேறல ோய் ப்பு அதிகம்


• Web development மை் றும் Android development-க்கு பயன் படும்
• Beginners கை் க ஏை் ை language

Summary
Java is:
• Simple
• Secure
• Platform independent
• Object-oriented
• Widely used in industry
It is one of the best programming languages for beginners and professional
software development.
Features of Java

13
14
6
Java has many powerful features that make it one of the most popular
programming languages.

1. Platform Independent

Java is called platform independent because Java programs can run on any
operating system.
Normally, programs written in other languages must be rewritten for different
operating systems.
But Java converts source code into bytecode, which runs on the JVM (Java
Virtual Machine).
Process
Java Program → Bytecode → JVM → Any Operating System

15
16
5
Example
A Java program written on:
• Windows
can also run on:
• Linux
• macOS
without changing the code.

Java program ஒரு operating system-ல் எழுதப்பட்டாலும் , மை் ை operating


systems-றலயும் run ஆகும் .
இதனால் தான் Java-றே:
“Write Once, Run Anywhere”
என் று அறைக்கிைார்கள் .

2. Object-Oriented

Java is an Object-Oriented Programming Language (OOP).

17
It organizes programs using:
• Classes
• Objects
This makes programs:
• Reusable
• Secure
• Easy to maintain
Main OOP Concepts

18
19
5
a) Encapsulation
Binding data and methods together inside a class.
b) Inheritance
One class can acquire properties of another class.
c) Polymorphism
One method can perform different tasks.
d) Abstraction
Hiding internal details and showing only essential features.
Example
class Student {
int id;
String name;
}
Here:
• Student → class
• id, name → data members

20
Java-வில் programs classes மை் றும் objects பயன் படுத்தி
உருோக்கப்படுகின் ைன.
இதனால் code reuse செய் யலாம் மை் றும் சபரிய applications
உருோக்க எளிதாக இருக்கும் .

Other Important Features of Java

21
22
5
Simple
Easy syntax and easy to learn.
Secure
Java provides strong security features.
Robust
Handles errors effectively using exception handling.
Multithreaded
Can perform multiple tasks simultaneously.
Portable
Programs can move easily from one system to another.
23
Distributed
Supports network-based applications.

Summary Table
Feature Meaning
Platform Independent Run on any OS
Object-Oriented Uses classes and objects
Secure Safe execution
Robust Reliable error handling
Multithreaded Multiple tasks together
Portable Easy to transfer

Short Definition (Exam Point)


Platform Independent
Java programs can run on any operating system because of JVM.
Object-Oriented
Java uses classes and objects to organize programs and support code reuse.
JDK, JRE, and JVM in Java

24
25
6
These are the main components required to develop and run Java programs.

1. JVM (Java Virtual Machine)

JVM is a virtual machine that executes Java bytecode.


It converts bytecode into machine code so the computer can understand and run the
program.
Main Functions
• Runs Java programs
• Makes Java platform independent
• Manages memory
Process
Bytecode → JVM → Machine Code

26
JVM என் பது Java program-ஐ run செய் யும் virtual machine ஆகும் .
இது bytecode-ஐ machine code-ஆக மாை் றுகிைது.

2. JRE (Java Runtime Environment)

JRE provides the environment needed to run Java applications.


It contains:
• JVM
• Java libraries
• Supporting files
Formula
JRE = JVM + Libraries + Runtime Files
Use
If you only want to run Java programs, JRE is enough.

Java programs run ஆக பதறேயான சூைறல JRE ேைங் குகிைது.


இதில் :
• JVM
• Libraries
• Runtime files
இருக்கும் .

3. JDK (Java Development Kit)

JDK is a complete package used for developing Java applications.


It contains:
• JRE
• Compiler (javac)
• Debugging tools

27
• Development utilities
Formula
JDK = JRE + Development Tools
Use
If you want to:
• write code
• compile programs
• run programs
you need JDK.

Java program உருோக்க developer பயன் படுத்துேது JDK.


இதில் :
• JRE
• Compiler
• Development tools
இருக்கும் .

Relationship Between JDK, JRE, and JVM

28
7

29
JDK
└── JRE
└── JVM

Working Process of Java

30
6
Step 1
Write Java program:
[Link]
Step 2
Compile using JDK compiler:

31
javac [Link]
Compiler creates:
[Link]
Step 3
JVM executes the .class file.

Comparison Table
Component Full Form Purpose
JVM Java Virtual Machine Runs Java bytecode
JRE Java Runtime Environment Provides runtime environment
JDK Java Development Kit Used to develop Java programs

Simple Real-Life Example

Think of Java like cooking:


• JDK → Kitchen with all cooking tools
• JRE → Ready kitchen to heat food
• JVM → Stove that actually cooks food

• JDK → முழு development kit


• JRE → run செய் யும் environment
• JVM → program execute செய் யும் engine

Exam Point Definitions


JVM
JVM is a virtual machine that executes Java bytecode.
JRE
JRE provides the runtime environment to run Java applications.
JDK
32
JDK is a software package used to develop Java programs.

Structure of a Java Program

33
6
A Java program is written using:
• Class
• Main method
• Statements
• Objects and methods
Every Java program follows a specific structure.

Basic Structure of Java Program


class Hello {
public static void main(String[] args) {
[Link]("Hello World");
}
}

Explanation of Each Part


1. Class Declaration
class Hello

• class keyword is used to create a class.


• Hello is the class name.

34
class என் பது class உருோக்க பயன் படும் keyword.
Hello என் பது class சபயர்.

2. Main Method
public static void main(String[] args)

This is the main method where program execution starts.


Breakdown
Keyword Meaning
public Accessible from anywhere
static Can run without object
void Returns nothing
main Main function
String[] args Command-line arguments

Program execution ஆரம் பிக்கும் இடம் main() method ஆகும் .

3. Opening and Closing Braces


{
}

Braces define the beginning and end of:


• class
• methods
• blocks

Braces { } code block-ஐ குறிக்கும் .

4. Statement

35
[Link]("Hello World");

Used to display output on the screen.


Parts
Part Meaning
System Standard system
out Output stream
println() Prints line

Screen-ல் output காட்ட பயன் படும் statement.

Program Execution Flow

36
6
Source Code (.java)

Compiler (javac)

37
Bytecode (.class)

JVM

Output

Example with Comments


// Program to print Hello World

class Hello {

// Main method
public static void main(String[] args) {

// Print statement
[Link]("Hello World");

}
}

Important Rules in Java Program


1. File Name = Class Name
If class name is:
Hello
then file name must be:
[Link]

2. Java is Case Sensitive


hello
and
Hello
are different.

3. Every Statement Ends with Semicolon


;
38
Simple Diagram of Structure

39
7
Class
└── Main Method
└── Statements

Summary
Part Purpose
class Defines class
main() Starting point
braces Define blocks
[Link]() Prints output
semicolon Ends statement

Exam Point Definition


Structure of Java Program
A Java program consists of:
• class declaration
• main method
• statements
• braces and semicolons
The execution of a Java program starts from the main() method.

40
Variables, Data Types, and Operators in Java

41
6
These are the basic building blocks of every Java program.

1. Variables

A variable is a container used to store data values.


Syntax
datatype variableName = value;
Example
int age = 20;
Here:
• int → data type
• age → variable name
• 20 → value

Variable என் பது data-ஐ store செய் யும் container ஆகும் .


42
Rules for Naming Variables

• Must begin with letter, _, or $


• Cannot start with number
• Cannot use Java keywords
• Case-sensitive
Valid Examples
int total;
String name;
float salary;
Invalid Example
int 1num;

Types of Variables

43
5
44
Type Description
Local Variable Declared inside method
Instance Variable Declared inside class
Static Variable Shared by all objects

2. Data Types

Data type specifies:


• what type of value a variable can store
• memory size

Types of Data Types

45
6
A) Primitive Data Types
Data Type Size Example
byte 1 byte byte a = 10;
short 2 bytes short b = 200;
int 4 bytes int c = 500;

46
Data Type Size Example
long 8 bytes long d = 1000L;
float 4 bytes float e = 5.5f;
double 8 bytes double f = 10.25;
char 2 bytes char g = 'A';
boolean 1 bit boolean h = true;

B) Non-Primitive Data Types


• String
• Arrays
• Classes
• Interfaces
Example
String name = "Arun";

Data type என் பது variable எந்த ேறக data-ஐ store செய் யும் என் பறத
குறிப் பிடும் .

3. Operators

Operators are symbols used to perform operations on variables and values.

Types of Operators

47
48
6
A) Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Example
int a = 10;
int b = 5;

[Link](a + b);
Output:
15

49
B) Relational Operators
Operator Meaning
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Example
[Link](10 > 5);
Output:
true

C) Logical Operators
Operator Meaning
&& AND
`
! NOT
Example
[Link](true && false);
Output:
false

D) Assignment Operators
Operator Example
= a = 10
+= a += 5

50
Operator Example
-= a -= 2

E) Increment and Decrement


Operator Meaning
++ Increase by 1
-- Decrease by 1
Example
int x = 5;
x++;
[Link](x);
Output:
6

Complete Example Program


class Demo {
public static void main(String[] args) {

int a = 10;
int b = 5;

int sum = a + b;

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


}
}
Output:
Sum = 15

Summary Table
Topic Meaning
Variable Stores value

51
Topic Meaning
Data Type Defines type of data
Operator Performs operations

Exam Point Definitions


Variable
A variable is a container used to store data.
Data Type
A data type specifies the type of value stored in a variable.
Operator
An operator is a symbol used to perform operations on data.
Input and Output in Java

52
7
Input and Output are used for interaction between:
• user
• program
53
1. Output in Java

Output means displaying data on the screen.


Java provides:
[Link]()
for printing output.

Methods Used for Output


Method Purpose
print() Prints without new line
println() Prints with new line
printf() Formatted output

A) print()
Example
[Link]("Hello ");
[Link]("World");
Output
Hello World

print() next line-க்கு செல் லாது.

B) println()
Example
[Link]("Hello");
[Link]("World");
Output
Hello
World
54
println() output print செய் த பிைகு next line-க்கு செல் கிைது.

C) printf()
Example
int age = 20;

[Link]("Age = %d", age);


Output
Age = 20

2. Input in Java

Input means taking data from the user.


The most commonly used class is:
Scanner
from:
[Link] package

Importing Scanner Class


import [Link];

Creating Scanner Object


Scanner sc = new Scanner([Link]);
Explanation
Part Meaning
Scanner Class name
sc Object name
[Link] Standard input

55
Taking Integer Input

56
5
Example
import [Link];

class Demo {
public static void main(String[] args) {
57
Scanner sc = new Scanner([Link]);

[Link]("Enter number: ");

int num = [Link]();

[Link]("Number = " + num);


}
}
Output
Enter number: 5
Number = 5

Taking Different Types of Input


Method Used For
nextInt() Integer
nextFloat() Float
nextDouble() Double
next() Single word
nextLine() Full sentence
nextBoolean() Boolean

Example for String Input


import [Link];

class Demo {
public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter name: ");

String name = [Link]();

[Link]("Name = " + name);


58
}
}

Input and Output Flow

59
6
User → Input → Program → Output → Screen

Complete Example Program


import [Link];

class Addition {
public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int a, b, sum;

[Link]("Enter first number: ");


a = [Link]();

[Link]("Enter second number: ");


b = [Link]();

sum = a + b;

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


}
}

60
Output
Enter first number: 10
Enter second number: 20
Sum = 30

Important Points

• Scanner is used for input.


• [Link]() is used for output.
• import [Link]; is necessary.

• Input எடுக்க Scanner பயன் படுத்தப்படுகிைது.


• Output காட்ட [Link]() பயன் படுத்தப்படுகிைது.

Summary Table
Concept Purpose
[Link]() Output
[Link]() Output with new line
Scanner Input from user
[Link] Standard input

Exam Point Definitions


Input
Input is the process of accepting data from the user.
Output
Output is the process of displaying results to the user.
Scanner
Scanner is a class used to take input from the keyboard.

61
Control Statements in Java

62
63
6
Control statements are used to control the flow of program execution.
They help programs:
• make decisions
• repeat tasks
• choose different paths

Types of Control Statements


Type Purpose
Selection Statements Decision making
Looping Statements Repetition
Jump Statements Transfer control

1. IF Statement

if statement is used to execute a block of code only when a condition is true.

Syntax

64
if(condition) {
// code
}

Example
int age = 20;

if(age >= 18) {


[Link]("Eligible to vote");
}
Output
Eligible to vote

Condition true ஆக இருந்தால் மட்டும் code execute ஆகும் .

2. IF-ELSE Statement
Syntax
if(condition) {
// true block
}
else {
// false block
}

Example
int num = 5;

if(num % 2 == 0) {
[Link]("Even");
}
else {
[Link]("Odd");
}
Output
Odd

65
3. ELSE-IF Ladder
Example
int marks = 85;

if(marks >= 90) {


[Link]("Grade A");
}
else if(marks >= 75) {
[Link]("Grade B");
}
else {
[Link]("Grade C");
}
Output
Grade B

4. SWITCH Statement

switch is used to select one block among many options.

Syntax
switch(expression) {

case value1:
// code
break;

case value2:
// code
break;

default:
// code
}

Example
66
int day = 2;

switch(day) {

case 1:
[Link]("Monday");
break;

case 2:
[Link]("Tuesday");
break;

default:
[Link]("Invalid");
}
Output
Tuesday

பல options-ல் ஒரு block execute செய் ய switch


பயன் படுத்தப் படுகிைது.

5. Loops in Java

67
5

68
Loops are used to repeat a block of code multiple times.

Types of Loops
Loop Usage
for loop Known number of repetitions
while loop Condition-based repetition
do-while loop Executes at least once

A) FOR Loop
Syntax
for(initialization; condition; increment) {
// code
}

Example
for(int i = 1; i <= 5; i++) {
[Link](i);
}
Output
1
2
3
4
5

for loop ஒரு குறிப்பிட்ட எண்ணிக்றகக்கு code repeat செய் ய


பயன் படும் .

B) WHILE Loop
Syntax

69
while(condition) {
// code
}

Example
int i = 1;

while(i <= 3) {
[Link](i);
i++;
}
Output
1
2
3

C) DO-WHILE Loop
Syntax
do {
// code
}
while(condition);

Example
int i = 1;

do {
[Link](i);
i++;
}
while(i <= 3);
Output
1
2
3

70
Difference Between While and Do-While
While Do-While
Checks condition first Executes first
May not run Runs at least once

Loop Control Statements

71
72
6
break
Stops loop immediately.
Example
break;

continue
Skips current iteration.
Example
continue;

73
Complete Example Program
class Demo {
public static void main(String[] args) {

for(int i = 1; i <= 5; i++) {

if(i == 3)
continue;

[Link](i);
}
}
}
Output
1
2
4
5

Summary Table
Statement Purpose
if Checks condition
if-else Two-way decision
switch Multiple choices
for Fixed repetition
while Condition loop
do-while Executes at least once

Exam Point Definitions


IF Statement
Used to execute code when condition is true.
SWITCH Statement
Used to select one block from multiple choices.

74
LOOP
A loop repeatedly executes a block of code until a condition becomes false.
Classes and Objects in Java

75
76
5
Classes and Objects are the foundation of Object-Oriented Programming (OOP)
in Java.

1. Class

A class is a blueprint or template used to create objects.


A class contains:
• variables (data)
• methods (functions)

Syntax of Class
class ClassName {

// variables

// methods
}

Example
class Student {

int id;
String name;
}
Explanation
Part Meaning
Student Class name
id, name Data members

Class என் பது object உருோக்க பயன் படும் blueprint ஆகும் .

77
2. Object

An object is an instance of a class.


Objects are used to:
• access variables
• call methods

Syntax for Creating Object


ClassName objectName = new ClassName();

Example
Student s1 = new Student();
Explanation
Part Meaning
Student Class name
s1 Object name
new Allocates memory

Object என் பது class-இன் instance ஆகும் .

Accessing Class Members


Example
class Student {

int id;
String name;
}

class Demo {

public static void main(String[] args) {

78
Student s1 = new Student();

[Link] = 101;
[Link] = "Arun";

[Link]([Link]);
[Link]([Link]);
}
}
Output
101
Arun

Real-Life Example

79
80
7
Class Object
Car blueprint Actual car
Student design Individual student
Mobile design Real mobile phone
81
• Class → மாதிரி (template)
• Object → உண்றமயான சபாருள்

Class with Method


Example
class Student {

int id;
String name;

void display() {

[Link](id);
[Link](name);
}
}

class Demo {

public static void main(String[] args) {

Student s1 = new Student();

[Link] = 101;
[Link] = "Arun";

[Link]();
}
}
Output
101
Arun

Multiple Objects
Example
class Student {

82
int id;
String name;
}

class Demo {

public static void main(String[] args) {

Student s1 = new Student();


Student s2 = new Student();

[Link] = 101;
[Link] = "Arun";

[Link] = 102;
[Link] = "Kumar";

[Link]([Link]);
[Link]([Link]);
}
}
Output
Arun
Kumar

Memory Representation

83
84
6
Class → Blueprint
Object → Memory allocation in heap

Difference Between Class and Object


Class Object
Blueprint Instance
Logical entity Physical entity
No memory allocated Memory allocated
Defines properties Uses properties

Important Points

• One class can create many objects.


• new keyword creates object.
• Objects access class members using dot (.) operator.

85
• ஒரு class மூலம் பல objects உருோக்கலாம் .
• new keyword object உருோக்க பயன் படும் .

Summary
Concept Meaning
Class Blueprint/template
Object Instance of class
new Creates object
Dot operator Access members

Exam Point Definitions


Class
A class is a blueprint used to create objects.
Object
An object is an instance of a class that contains data and methods.

Constructors in Java

86
87
6
A constructor is a special method used to initialize objects in Java.
When an object is created, the constructor is automatically called.

Definition

A constructor is a special method that initializes the object.

Object உருோகும் பபாது automatically call ஆகி values initialize


செய் யும் method தான் constructor.
88
Rules of Constructor
Rule Description
Constructor name Same as class name
Return type No return type
Automatically called Yes
Used for Initializing objects

Syntax of Constructor
class ClassName {

ClassName() {

// constructor body
}
}

Example of Constructor
class Student {

Student() {

[Link]("Constructor Called");
}

public static void main(String[] args) {

Student s1 = new Student();


}
}
Output
Constructor Called

Types of Constructors

89
90
6
Type Description
Default Constructor No parameters
Parameterized Constructor Accepts parameters

1. Default Constructor

A constructor without parameters is called a default constructor.

Example
class Demo {

Demo() {

[Link]("Default Constructor");
}

public static void main(String[] args) {

Demo d = new Demo();

91
}
}
Output
Default Constructor

Parameters இல் லாத constructor → default constructor.

2. Parameterized Constructor

A constructor that accepts parameters is called a parameterized constructor.

Example
class Student {

int id;
String name;

Student(int i, String n) {

id = i;
name = n;
}

void display() {

[Link](id + " " + name);


}

public static void main(String[] args) {

Student s1 = new Student(101, "Arun");

[Link]();
}
}
Output
101 Arun

92
Parameters உடன் values pass செய் யும் constructor → parameterized
constructor.

Constructor Overloading

93
6

Using multiple constructors with different parameters is called constructor


overloading.

Example
class Demo {

Demo() {

[Link]("No Arguments");
}

Demo(int a) {

[Link](a);
}

public static void main(String[] args) {


94
Demo d1 = new Demo();

Demo d2 = new Demo(10);


}
}
Output
No Arguments
10

Constructor vs Method
Constructor Method
Same name as class Any name
No return type Has return type
Called automatically Called manually
Initializes object Performs operation

Important Points

• Constructor initializes objects.


• Constructor is automatically called.
• Constructor can be overloaded.
• Constructor cannot return values.

• Object உருோகும் பபாது constructor call ஆகும் .


• Values initialize செய் ய constructor பயன் படும் .

Real-Life Example

95
96
5
Think of constructor like:
• filling details while creating a student record
• setting initial values during object creation

Memory Flow
Object Creation

Constructor Called

Variables Initialized

Complete Example Program


class Employee {

int id;
String name;

Employee(int i, String n) {

id = i;
name = n;
97
}

void display() {

[Link](id + " " + name);


}

public static void main(String[] args) {

Employee e1 = new Employee(1, "Kumar");

[Link]();
}
}
Output
1 Kumar

Summary Table
Concept Meaning
Constructor Initializes object
Default Constructor No parameters
Parameterized Constructor With parameters
Constructor Overloading Multiple constructors

Exam Point Definitions


Constructor
A constructor is a special method used to initialize objects.
Default Constructor
A constructor without parameters is called a default constructor.
Parameterized Constructor
A constructor with parameters is called a parameterized constructor.
Encapsulation in Java

98
99
7
Encapsulation is one of the important concepts of Object-Oriented Programming
(OOP).

Definition of Encapsulation

Encapsulation means:
Wrapping data and methods into a single unit.
It is used for:
• data hiding

100
• security
• controlled access

Data மை் றும் methods-ஐ ஒபர unit-ஆக பெர்ப்பது encapsulation ஆகும் .


இதன் முக்கிய பநாக்கம் :
• data hiding
• பாதுகாப்பு
• controlled access

How Encapsulation is Achieved


Encapsulation is achieved using:
• private variables
• public getter and setter methods

Components of Encapsulation
Component Purpose
private variable Hide data
setter method Set value
getter method Get value

Example of Encapsulation
class Student {

private int id;

public void setId(int i) {


id = i;
}

public int getId() {


return id;
101
}
}

class Demo {

public static void main(String[] args) {

Student s = new Student();

[Link](101);

[Link]([Link]());
}
}
Output
101

Explanation of Program
1. Private Variable
private int id;

The variable cannot be accessed directly outside the class.

private variable class-க்கு சேளிபய direct-ஆ access செய் ய முடியாது.

2. Setter Method
public void setId(int i)

Used to assign value to private variable.

Private variable-க்கு value set செய் ய பயன் படும் .

3. Getter Method
public int getId()
102
Used to retrieve value from private variable.

Private variable value-ஐ சபை பயன் படும் .

Why Use Encapsulation?

103
104
6
Advantages
Advantage Description
Data Hiding Protects data
Security Prevents unauthorized access
Flexibility Easy to modify code
Reusability Better code organization

Without Encapsulation
Example

105
class Student {

int id;
}
Here:
• data can be changed directly
• security is low

With Encapsulation
Example
class Student {

private int id;

public void setId(int i) {


id = i;
}

public int getId() {


return id;
}
}
Here:
• data is protected
• access is controlled

Real-Life Example

106
107
7

ATM machine is a good example of encapsulation:


• internal process is hidden
• users access through buttons

ATM machine பபால:


• internal details மறைக்கப் படும்
• user controlled access மட்டும் சபறுோர்

Complete Example Program


class Employee {

private String name;

public void setName(String n) {

name = n;
}
108
public String getName() {

return name;
}

public static void main(String[] args) {

Employee e = new Employee();

[Link]("Kumar");

[Link]([Link]());
}
}
Output
Kumar

Flow of Encapsulation
Private Data

Setter Method

Getter Method

User Access

Important Points

• Variables are declared private


• Access is provided through methods
• Encapsulation improves security

• Data-ஐ private-ஆ declare செய் போம்


• Getter மை் றும் Setter மூலம் access செய் போம்

109
Summary Table
Concept Meaning
Encapsulation Wrapping data and methods
private Hides data
getter Retrieves value
setter Sets value

Exam Point Definitions


Encapsulation
Encapsulation is the process of wrapping data and methods into a single unit.
Getter Method
A getter method is used to access private data.
Setter Method
A setter method is used to assign value to private data.
Inheritance
Inheritance in Java

110
7
Inheritance is one of the most important concepts in Object-Oriented
Programming (OOP).

Definition of Inheritance

111
Inheritance is the process by which one class acquires the properties and methods
of another class.
• Existing class → Parent class / Super class
• New class → Child class / Sub class

ஒரு class மை் சைாரு class-இன் properties மை் றும் methods-ஐ சபறுேது
inheritance ஆகும் .

Why Use Inheritance?


Advantages
Advantage Description
Code Reusability Reuse existing code
Saves Time Less coding
Easy Maintenance Better organization
Extensibility Add new features easily

Syntax of Inheritance
class ChildClass extends ParentClass {

}
Explanation
Keyword Meaning
extends Used for inheritance
ParentClass Base class
ChildClass Derived class

Simple Example of Inheritance

112
class Animal {

void sound() {

[Link]("Animal makes sound");


}
}

class Dog extends Animal {

void bark() {

[Link]("Dog barks");
}
}

class Demo {

public static void main(String[] args) {

Dog d = new Dog();

[Link]();
[Link]();
}
}
Output
Animal makes sound
Dog barks

Explanation of Program
Parent Class
class Animal
Contains common properties/methods.

Child Class
class Dog extends Animal
Dog inherits features from Animal.

113
Working Flow

114
7
Parent Class

Child Class

Inherited Methods

Types of Inheritance in Java

115
116
117
6
Type Description
Single Inheritance One parent → one child
Multilevel Inheritance Chain of inheritance
Hierarchical Inheritance One parent → many children

1. Single Inheritance
class A {

void show() {
[Link]("Class A");
}
}

class B extends A {

void display() {
[Link]("Class B");
}
}

118
2. Multilevel Inheritance
class A {

void show() {
[Link]("Class A");
}
}

class B extends A {

void display() {
[Link]("Class B");
}
}

class C extends B {

void print() {
[Link]("Class C");
}
}

3. Hierarchical Inheritance
class A {

void show() {
[Link]("Class A");
}
}

class B extends A {

class C extends A {

Important Keyword: super

119
super keyword refers to parent class object.
Used for:
• calling parent constructor
• accessing parent methods

Example
class Animal {

void sound() {
[Link]("Animal sound");
}
}

class Dog extends Animal {

void sound() {

[Link]();

[Link]("Dog barks");
}
}

Constructor in Inheritance
class Animal {

Animal() {
[Link]("Animal Constructor");
}
}

class Dog extends Animal {

Dog() {
[Link]("Dog Constructor");
}
}
Output
120
Animal Constructor
Dog Constructor

Real-Life Example

121
6

122
Parent Class Child Class
Vehicle Car
Animal Dog
Person Student

Child class parent class-இன் features-ஐ சபறும் .

Important Points

• Java uses extends keyword for inheritance.


• Child class can access parent methods.
• Inheritance supports code reuse.

• extends keyword inheritance-க்கு பயன் படுத்தப்படுகிைது.


• Parent class features child class-க்கு கிறடக்கும் .

Difference Between Parent and Child Class


Parent Class Child Class
Base class Derived class
Provides features Uses features
Super class Sub class

Summary Table
Concept Meaning
Inheritance Acquiring properties
extends Inheritance keyword
Parent class Base class

123
Concept Meaning
Child class Derived class
super Refers parent class

Exam Point Definitions


Inheritance
Inheritance is the process by which one class acquires the properties and methods
of another class.
Parent Class
A class whose properties are inherited by another class.
Child Class
A class that inherits properties from another class.

Polymorphism in Java

124
6
Polymorphism is one of the important concepts of Object-Oriented
Programming (OOP).

125
Definition of Polymorphism

Polymorphism means:
“One name, many forms”
The same method can perform different tasks.

ஒபர method சபயர் பல விதமாக செயல் படுேது polymorphism


ஆகும் .

Types of Polymorphism

126
6

127
Type Description
Method Overloading Same method name, different parameters
Method Overriding Child class changes parent method

1. Method Overloading

Method overloading means:


• same method name
• different parameters
It is also called:
Compile-Time Polymorphism

Rules for Overloading


Rule Description
Method name Same
Parameters Different
Return type May change

Example of Method Overloading


class Add {

void sum(int a, int b) {

[Link](a + b);
}

void sum(int a, int b, int c) {

[Link](a + b + c);
}

public static void main(String[] args) {

128
Add obj = new Add();

[Link](10, 20);

[Link](10, 20, 30);


}
}
Output
30
60

Explanation

Both methods have:


• same name → sum()
• different parameters

ஒபர method சபயர் பல parameters-உடன் பயன் படுத்தப்படுகிைது.

Constructor Overloading
Example
class Demo {

Demo() {

[Link]("No Arguments");
}

Demo(int a) {

[Link](a);
}
}

129
2. Method Overriding

130
7

Method overriding occurs when:


• child class provides its own implementation
• for parent class method
It is also called:
Runtime Polymorphism

Rules for Overriding


Rule Description
Method name Same
Parameters Same
Inheritance Required

Example of Method Overriding


class Animal {

void sound() {

[Link]("Animal makes sound");


}
131
}

class Dog extends Animal {

void sound() {

[Link]("Dog barks");
}

public static void main(String[] args) {

Dog d = new Dog();

[Link]();
}
}
Output
Dog barks

Explanation

Dog class changes the sound() method of Animal.

Child class parent method-ஐ மாை் றுேது overriding.

Using super Keyword


Example
class Animal {

void sound() {

[Link]("Animal sound");
}
}

class Dog extends Animal {

132
void sound() {

[Link]();

[Link]("Dog bark");
}
}

Difference Between Overloading and Overriding

133
6
Method Overloading Method Overriding
Same method name Same method name
Different parameters Same parameters
No inheritance needed Inheritance required
Compile-time polymorphism Runtime polymorphism

Real-Life Example

134
135
6

Example:
• A person behaves differently:
o at school
o at home
o at office
Same person → different behavior.

ஒபர சபயர் பல செயல் கறள செய் ேது polymorphism.

Important Points

• Overloading increases readability.


• Overriding provides specific implementation.
• Overriding requires inheritance.

136
• Overloading → same method different parameters
• Overriding → child class method modification

Complete Example Program


class Shape {

void draw() {

[Link]("Drawing Shape");
}
}

class Circle extends Shape {

void draw() {

[Link]("Drawing Circle");
}

public static void main(String[] args) {

Circle c = new Circle();

[Link]();
}
}
Output
Drawing Circle

Summary Table
Concept Meaning
Polymorphism One name, many forms
Overloading Same method, different parameters
Overriding Child modifies parent method

Exam Point Definitions

137
Polymorphism
Polymorphism allows methods to perform different tasks using the same name.
Method Overloading
Method overloading means same method name with different parameters.
Method Overriding
Method overriding means redefining parent class method in child class.
Abstraction in Java

138
8

139
Abstraction is one of the core concepts of Object-Oriented Programming
(OOP).

Definition of Abstraction

Abstraction means:
Hiding implementation details and showing only essential features.
The user only sees:
• what the object does
The user does not see:
• how it works internally

Internal implementation details-ஐ மறைத்து, முக்கியமான features


மட்டும் காட்டுேது abstraction ஆகும் .

Real-Life Example

140
141
142
6
ATM Machine
You:
• insert card
• enter PIN
• withdraw money
But you do not know:
• internal bank processing
This is abstraction.

Ways to Achieve Abstraction in Java


Method Description
Abstract Class Partial abstraction
Interface Complete abstraction

143
1. Abstract Class

144
7

A class declared with the abstract keyword is called an abstract class.


It may contain:
• abstract methods
• normal methods

Abstract Method
A method without body is called abstract method.
Syntax
abstract void methodName();

Example of Abstract Class


abstract class Animal {

145
abstract void sound();
}

class Dog extends Animal {

void sound() {

[Link]("Dog barks");
}

public static void main(String[] args) {

Dog d = new Dog();

[Link]();
}
}
Output
Dog barks

Explanation
Part Meaning
abstract class Animal Abstract class
abstract void sound() Abstract method
Dog extends Animal Child class
sound() Method implementation

Important Rules of Abstract Class


Rule Description
Cannot create object Direct object creation not allowed
Can contain methods Both abstract and normal
Must use abstract keyword Required

2. Interface
146
147
6

An interface is used to achieve complete abstraction.


Interface contains:
• abstract methods
• constants

Syntax of Interface
interface InterfaceName {

void methodName();
}

Example of Interface
interface Animal {

void sound();
}

class Dog implements Animal {

148
public void sound() {

[Link]("Dog barks");
}

public static void main(String[] args) {

Dog d = new Dog();

[Link]();
}
}
Output
Dog barks

Explanation
Part Meaning
interface Animal Interface declaration
implements Used to inherit interface
sound() Implemented method

Important Rules of Interface


Rule Description
Methods are public & abstract By default
Variables are final & static By default
Cannot create objects Directly

Difference Between Abstract Class and Interface

149
150
5
Abstract Class Interface
Uses abstract keyword Uses interface keyword
Can contain normal methods Mostly abstract methods
Supports constructors No constructors
Partial abstraction Complete abstraction

Real-Life Comparison
Concept Example
Abstract Class Vehicle
Interface Rules followed by vehicles

Complete Example Program


abstract class Shape {

abstract void draw();


}

class Circle extends Shape {

void draw() {
151
[Link]("Drawing Circle");
}

public static void main(String[] args) {

Circle c = new Circle();

[Link]();
}
}
Output
Drawing Circle

Advantages of Abstraction

152
153
5
154
Advantage Description
Security Hides internal details
Simplicity Easy to use
Flexibility Easy to modify
Reusability Better design

Important Points

• Abstraction hides internal details.


• Achieved using abstract class and interface.
• Interface supports complete abstraction.

• Internal details மறைக்க abstraction பயன் படும் .


• Abstract class மை் றும் interface மூலம் abstraction சபைலாம் .

Summary Table
Concept Meaning
Abstraction Hiding implementation
Abstract Class Partial abstraction
Interface Complete abstraction
abstract Abstract keyword
implements Interface inheritance

Exam Point Definitions


Abstraction
Abstraction is the process of hiding implementation details and showing only
essential features.
Abstract Class

155
A class declared with abstract keyword is called abstract class.
Interface
An interface is used to achieve complete abstraction in Java.

. Core Java Concepts


Arrays and Strings in Java

156
157
6
Arrays and Strings are important concepts in Java used to store and manipulate
data.

1. Arrays in Java

An array is a collection of similar data types stored in contiguous memory


locations.
Using arrays:
• multiple values can be stored in one variable

ஒபர ேறக data-கறள ஒன் ைாக store செய் ய பயன் படும் structure
தான் array.

Why Use Arrays?


Without array:
int a = 10;
int b = 20;
int c = 30;
158
With array:
int arr[] = {10, 20, 30};

Declaration of Array
Syntax
datatype arrayName[];
or
datatype[] arrayName;

Creating Array
Syntax
arrayName = new datatype[size];

Example of Array
class Demo {

public static void main(String[] args) {

int arr[] = {10, 20, 30, 40};

[Link](arr[0]);
[Link](arr[1]);
}
}
Output
10
20

Array Index

159
160
6

Array index starts from:


0
Example:
arr[0] → first element
arr[1] → second element

161
Traversing Array Using Loop
Example
class Demo {

public static void main(String[] args) {

int arr[] = {10, 20, 30, 40};

for(int i = 0; i < [Link]; i++) {

[Link](arr[i]);
}
}
}
Output
10
20
30
40

Types of Arrays

162
6
Type Description
One-Dimensional Array Single row
Two-Dimensional Array Rows and columns
Multidimensional Array Multiple dimensions

163
Two-Dimensional Array
Example
class Demo {

public static void main(String[] args) {

int arr[][] = {
{1, 2},
{3, 4}
};

[Link](arr[0][1]);
}
}
Output
2

2. Strings in Java

164
165
6

A String is a sequence of characters.


Strings are represented using:
String
class.

Declaration of String
String name = "Arun";

Example Program
class Demo {

public static void main(String[] args) {

String name = "Java";

[Link](name);

166
}
}
Output
Java

Important String Methods

167
5
Method Purpose
length() Returns length
toUpperCase() Converts to uppercase
toLowerCase() Converts to lowercase
charAt() Returns character
equals() Compares strings
substring() Extracts part of string

Example of String Methods


class Demo {

168
public static void main(String[] args) {

String s = "Java Programming";

[Link]([Link]());

[Link]([Link]());

[Link]([Link](2));
}
}
Output
16
JAVA PROGRAMMING
v

String Comparison
Example
class Demo {

public static void main(String[] args) {

String s1 = "Java";
String s2 = "Java";

[Link]([Link](s2));
}
}
Output
true

Difference Between Array and String

169
170
6
Array String
Stores similar data Stores characters
Fixed size Sequence of characters
Uses index Uses string methods

Real-Life Example

171
172
6
Concept Example
Array Student marks
String Student name

Important Points

• Arrays store multiple values.


• Strings store text.
• Array index starts from 0.
• String is immutable in Java.

• Array பல values store செய் யும் .


• String text store செய் யும் .
• Array index 0-ல் சதாடங் கும் .

Complete Example Program


class Demo {

public static void main(String[] args) {

int marks[] = {80, 90, 70};


173
String name = "Arun";

[Link](name);

for(int i = 0; i < [Link]; i++) {

[Link](marks[i]);
}
}
}
Output
Arun
80
90
70

Summary Table
Concept Meaning
Array Collection of similar data
String Sequence of characters
Index Position of element
length() Array/String length

Exam Point Definitions


Array
An array is a collection of similar data types stored in contiguous memory
locations.
String
A string is a sequence of characters represented using String class.
Wrapper Classes in Java

174
175
6
Wrapper classes are used to convert primitive data types into objects.

Definition of Wrapper Class

A wrapper class is a class that wraps primitive data types into objects.
Java provides wrapper classes for all primitive data types.

Primitive data types-ஐ object-ஆக மாை் ை பயன் படும் classes தான்


wrapper classes.

Why Use Wrapper Classes?

Wrapper classes are needed because:


• collections store objects only
• objects provide useful methods
176
• conversion becomes easier

Wrapper classes பயன் படுத்துேது:


• primitive values-ஐ object-ஆக மாை் ை
• collections-ல் பயன் படுத்த
• conversion எளிதாக்க

Primitive Data Types and Wrapper Classes

177
178
6
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Example of Wrapper Class


class Demo {

public static void main(String[] args) {

int a = 10;

Integer obj = [Link](a);

[Link](obj);
}
}
Output
10

Autoboxing

179
180
7

Automatic conversion of primitive type into wrapper object is called autoboxing.

Example
class Demo {

public static void main(String[] args) {

int a = 100;

Integer obj = a;

[Link](obj);
}
}
Output
100

Primitive value automatically object-ஆக மாறுேது autoboxing.

Unboxing
181
182
6

Automatic conversion of wrapper object into primitive type is called unboxing.

Example
class Demo {

public static void main(String[] args) {

Integer obj = 50;

int a = obj;

[Link](a);
}
}
Output
50

183
Wrapper object primitive value-ஆக மாறுேது unboxing.

Common Methods of Wrapper Classes

184
7
Method Purpose
valueOf() Converts primitive to object
parseInt() Converts String to int
toString() Converts value to String
intValue() Converts object to int

Example: String to Integer


class Demo {

public static void main(String[] args) {

String s = "200";

int num = [Link](s);

[Link](num);
185
}
}
Output
200

Example: Integer to String


class Demo {

public static void main(String[] args) {

int num = 500;

String s = [Link](num);

[Link](s);
}
}
Output
500

Real-Life Analogy

186
187
5

Think of wrapper class like:


• wrapping a gift box around an item
Primitive value gets wrapped inside an object.

Primitive value-ஐ object-ஆக wrap செய் ேது wrapper class.

Advantages of Wrapper Classes


Advantage Description
Object Conversion Primitive → Object
Collection Support Used in collections
Utility Methods Useful conversion methods

188
Advantage Description
Easy Parsing String conversions

Important Points

• Wrapper classes belong to [Link] package.


• Wrapper classes are immutable.
• Used heavily in collections and frameworks.

• Wrapper classes primitive data-ஐ object-ஆக மாை் றும் .


• Collections-ல் மிகவும் பயன் படும் .

Complete Example Program


class Demo {

public static void main(String[] args) {

int a = 10;

Integer obj = a;

int b = obj;

[Link](a);
[Link](obj);
[Link](b);
}
}
Output
10
10
10

Summary Table

189
Concept Meaning
Wrapper Class Primitive wrapped as object
Autoboxing Primitive → Object
Unboxing Object → Primitive
parseInt() String → int

Exam Point Definitions


Wrapper Class
A wrapper class converts primitive data type into object.
Autoboxing
Automatic conversion of primitive type into wrapper object.
Unboxing
Automatic conversion of wrapper object into primitive type.
Exception Handling in Java

190
191
7
Exception handling is used to handle runtime errors and prevent abnormal program
termination.

What is an Exception?

An exception is an unwanted event that occurs during program execution.


Examples:
• division by zero
• array index error
• invalid input

Program run ஆகும் பபாது ஏை் படும் runtime error தான் exception.

Why Exception Handling?

Without exception handling:


192
• program terminates suddenly
With exception handling:
• program continues execution safely

Exception Handling Keywords

193
194
6
Keyword Purpose
try Contains risky code
catch Handles exception
finally Executes always
throw Explicitly throws exception
throws Declares exception

1. try Block

The try block contains code that may generate exception.


195
Syntax
try {

// risky code
}

2. catch Block

The catch block handles the exception.

Syntax
catch(ExceptionType e) {

// handling code
}

Example of try-catch
class Demo {

public static void main(String[] args) {

try {

int a = 10 / 0;

[Link](a);
}

catch(ArithmeticException e) {

[Link]("Cannot divide by zero");


}
}
}
Output
Cannot divide by zero
196
Explanation
Part Meaning
try Risky code
ArithmeticException Exception type
catch Handles error

3. finally Block

197
6

The finally block always executes:


• whether exception occurs or not
Used for:

198
• closing files
• cleanup operations

Syntax
finally {

// cleanup code
}

Example of finally
class Demo {

public static void main(String[] args) {

try {

int a = 10 / 0;
}

catch(ArithmeticException e) {

[Link]("Exception handled");
}

finally {

[Link]("Finally block executed");


}
}
}
Output
Exception handled
Finally block executed

Exception ேந்தாலும் ேராவிட்டாலும் finally block execute ஆகும் .

199
4. throw Keyword

200
5

201
throw keyword is used to explicitly throw an exception.

Syntax
throw new ExceptionType("message");

Example of throw
class Demo {

public static void main(String[] args) {

int age = 15;

if(age < 18) {

throw new ArithmeticException("Not eligible");


}

else {

[Link]("Eligible");
}
}
}
Output
Exception in thread "main" [Link]: Not eligible

Exception-ஐ manually உருோக்க throw பயன் படுத்தப்படுகிைது.

5. throws Keyword

throws keyword declares exceptions that may occur in method.

Example

202
class Demo {

static void check() throws ArithmeticException {

throw new ArithmeticException("Error");


}

public static void main(String[] args) {

check();
}
}

Types of Exceptions

203
6

204
Type Description
Checked Exception Checked at compile time
Unchecked Exception Occurs at runtime

Common Exceptions in Java


Exception Cause
ArithmeticException Divide by zero
ArrayIndexOutOfBoundsException Invalid array index
NullPointerException Null object access
NumberFormatException Invalid number conversion

Multiple catch Blocks


Example
class Demo {

public static void main(String[] args) {

try {

int arr[] = new int[5];

arr[10] = 50;
}

catch(ArrayIndexOutOfBoundsException e) {

[Link]("Array index error");


}

catch(Exception e) {

[Link]("General exception");
}
}
}

205
Output
Array index error

Flow of Exception Handling

206
6
try

Exception Occurs

207

catch

finally

Advantages of Exception Handling


Advantage Description
Prevents crash Program continues
Error handling Handles runtime errors
Improves readability Structured error management
Easy debugging Detects problems clearly

Important Points

• try contains risky code.


• catch handles exception.
• finally always executes.
• throw creates exception manually.

• Runtime errors handle செய் ய exception handling பயன் படும் .


• finally block எப் பபாதும் execute ஆகும் .

Complete Example Program


class Demo {

public static void main(String[] args) {

try {

int a = 20 / 0;

[Link](a);
}
208
catch(ArithmeticException e) {

[Link]("Division by zero");
}

finally {

[Link]("Program ended");
}
}
}
Output
Division by zero
Program ended

Summary Table
Keyword Purpose
try Risky code
catch Handles exception
finally Executes always
throw Throws exception
throws Declares exception

Exam Point Definitions


Exception
An exception is a runtime error that disrupts normal program execution.
try
Used to write risky code.
catch
Used to handle exceptions.
finally
A block that always executes after try-catch.
209
throw
Used to explicitly throw an exception.
Packages and Access Modifiers
1. Packages in Java
A package is a collection of related classes and interfaces.
It helps organize code and avoids name conflicts.
Types of Packages
1. Built-in packages
o Provided by Java
o Example: [Link], [Link]
2. User-defined packages
o Created by programmers

Creating a Package
package mypack;

public class Hello {


public void display() {
[Link]("Welcome");
}
}
Save the file inside folder mypack.

Using a Package
import [Link];

public class Test {


public static void main(String[] args) {
Hello h = new Hello();
[Link]();
}
}

Advantages of Packages

210
• Organizes classes
• Avoids naming conflicts
• Provides access protection
• Easier maintenance

Access Modifiers in Java


Access modifiers control the visibility of classes, methods, and variables.
Types of Access Modifiers
Modifier Same Class Same Package Subclass Other Package
private Yes No No No
Default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes

1. Private
Accessible only within the same class.
class Demo {
private int x = 10;

void show() {
[Link](x);
}
}

2. Default (No Modifier)


Accessible only within the same package.
class Demo {
int x = 20;
}

3. Protected
Accessible within package and outside package through inheritance.
211
class Demo {
protected int x = 30;
}

4. Public
Accessible from anywhere.
public class Demo {
public int x = 40;
}

Example Program
package mypack;

public class A {
public int a = 10;
private int b = 20;
protected int c = 30;
int d = 40;

public void display() {


[Link](a);
[Link](b);
[Link](c);
[Link](d);
}
}

Important Points
• private → most restricted
• public → least restricted
• Default modifier is also called package-private
• A class can be either:
o public
o default only

212
விளக்கம் (Tamil Explanation)
Package என்றால் என்ன?
Package என் பது சதாடர்புறடய classes-ஐ ஒன் ைாக organize
செய் ேது.
பயன்கள்
• Code organization
• Same சபயர் conflict தவிர்க்க
• Security மை் றும் access control

Access Modifiers
private
அபத class-ல் மட்டும் access செய் யலாம் .
Default
அபத package-ல் மட்டும் access செய் யலாம் .
protected
அபத package மை் றும் inheritance மூலம் access செய் யலாம் .
public
எங் கிருந்தும் access செய் யலாம் .

நினனவில் ககாள் ள
• private → அதிக பாதுகாப்பு
• public → எல் பலாருக்கும் access
• Default = package-private
Command-Line Arguments in Java
Command-line arguments are values passed to a Java program during execution.
They are stored in the String[] args parameter of the main() method.

Syntax

213
class Test {
public static void main(String[] args) {

}
}
Here:
• String[] args stores command-line inputs.
• Each argument is treated as a string.

Example 1: Display Arguments


class Demo {
public static void main(String[] args) {

[Link]("First Argument: " + args[0]);


[Link]("Second Argument: " + args[1]);
}
}
Compile
javac [Link]
Run
java Demo Hello Java
Output
First Argument: Hello
Second Argument: Java

Example 2: Addition of Two Numbers


class Add {
public static void main(String[] args) {

int a = [Link](args[0]);
int b = [Link](args[1]);

int sum = a + b;

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


}
}
214
Run
java Add 10 20
Output
Sum = 30

Important Methods
1. [Link]()
Converts string to integer.
int n = [Link]("100");

Important Points
• Arguments are separated by spaces.
• All arguments are stored as strings.
• Array index starts from 0.
• Accessing unavailable arguments causes:
ArrayIndexOutOfBoundsException

Example with Loop


class PrintArgs {
public static void main(String[] args) {

for(int i = 0; i < [Link]; i++) {


[Link](args[i]);
}
}
}
Run
java PrintArgs A B C D
Output
A
B
C
D
215
Advantages
• Input can be given during execution
• Useful for automation
• No need to hardcode values

விளக்கம் (Tamil Explanation)


Command-Line Arguments என்றால் என்ன?
Program run செய் யும் பபாது command line மூலம் values அனுப்புேது.

Example
java Demo Hello
இங் பக:
• Hello என் பது command-line argument.

Arguments எங் கு சேமிக்கப் படும் ?


String[] args
இதில் store ஆகும் .

முக்கிய குறிப் புகள்


• எல் லா arguments-மும் string ஆக இருக்கும் .
• Number பயன் படுத்த பேண்டும் என் ைால் :
[Link]()
பயன் படுத்த பேண்டும் .

உதாரணம்
java Add 5 10
Output:

216
15

. Advanced Java
Multithreading in Java
What is Multithreading?
Multithreading is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process.
It helps programs perform multiple tasks at the same time.
Example:
• Playing music while downloading a file
• Typing while spell-check runs

Advantages of Multithreading
• Better CPU utilization
• Faster execution
• Simultaneous task processing
• Improves performance

Thread Life Cycle


A thread passes through different states:
1. New
2. Runnable
3. Running
4. Waiting / Blocked
5. Terminated

Creating Threads in Java


There are two ways:
1. By extending Thread class
2. By implementing Runnable interface
217
1. Extending Thread Class
class MyThread extends Thread {

public void run() {


[Link]("Thread is running");
}

public static void main(String[] args) {

MyThread t = new MyThread();

[Link]();
}
}

Output
Thread is running

Important Methods
Method Description
start() Starts thread
run() Contains thread code
sleep() Pauses thread
join() Waits for thread completion
isAlive() Checks thread status

Example: sleep()
class Demo extends Thread {

public void run() {

for(int i = 1; i <= 5; i++) {

[Link](i);
218
try {
[Link](1000);
}
catch(Exception e) {
[Link](e);
}
}
}

public static void main(String[] args) {

Demo t = new Demo();

[Link]();
}
}

2. Implementing Runnable Interface


class Demo implements Runnable {

public void run() {


[Link]("Runnable thread");
}

public static void main(String[] args) {

Demo d = new Demo();

Thread t = new Thread(d);

[Link]();
}
}

Difference Between Thread and Runnable


Thread Class Runnable Interface
Extends Thread Implements Runnable
Cannot extend another class Can extend another class

219
Thread Class Runnable Interface
Less flexible More flexible

Thread Priority
Each thread has priority from 1 to 10.
[Link](10);
• MIN_PRIORITY = 1
• NORM_PRIORITY = 5
• MAX_PRIORITY = 10

Synchronization
Synchronization prevents multiple threads from accessing shared resources
simultaneously.
synchronized void display() {
[Link]("Safe thread");
}

Example of Multithreading
class A extends Thread {

public void run() {


for(int i=1; i<=3; i++) {
[Link]("A : " + i);
}
}
}

class B extends Thread {

public void run() {


for(int i=1; i<=3; i++) {
[Link]("B : " + i);
}
}
}

220
public class Test {

public static void main(String[] args) {

A t1 = new A();
B t2 = new B();

[Link]();
[Link]();
}
}

Important Points
• start() creates a new thread.
• Directly calling run() does not create a new thread.
• Threads execute independently.
• Multithreading improves performance.

விளக்கம் (Tamil Explanation)


Multithreading என்றால் என்ன?
ஒபர பநரத்தில் பல tasks execute செய் ேது.
ஒே் சோரு task-மும் thread என் று அறைக்கப் படும் .

Thread உருவாக்கும் வழிகள்


1. Thread class extend கேய் வது
class MyThread extends Thread

2. Runnable interface implement கேய் வது


class Demo implements Runnable

முக்கிய Methods

221
Method பயன்

start() Thread start செய் யும்

run() Thread code இருக்கும்

sleep() சில பநரம் pause செய் யும்

join() மை் ை thread முடியும் ேறர wait செய் யும்

Synchronization
ஒபர resource-ஐ multiple threads access செய் யும் பபாது error ேராமல்
பாதுகாக்கும் .

நினனவில் ககாள் ள
• start() பயன் படுத்த பேண்டும்
• run() மட்டும் call செய் தால் புதிய thread உருோகாது
• Multithreading program speed அதிகரிக்கும்
Collections Framework in Java
The Collections Framework is a set of classes and interfaces used to store and
manipulate groups of objects.
It provides:
• Dynamic data storage
• Searching
• Sorting
• Insertion and deletion operations
Java Collections are available in the [Link] package.

Main Interfaces in Collections Framework


Collection
|
|---- List
|---- Set

222
|
Map (separate interface)

1. List Interface
A List stores elements in insertion order and allows duplicates.
Features
• Ordered collection
• Duplicate values allowed
• Index-based access
Common List Classes
• ArrayList
• LinkedList
• Vector

ArrayList Example
import [Link].*;

class Demo {
public static void main(String[] args) {

ArrayList<String> list = new ArrayList<>();

[Link]("Java");
[Link]("Python");
[Link]("Java");

[Link](list);
}
}
Output
[Java, Python, Java]

LinkedList Example
import [Link].*;

223
class Demo {
public static void main(String[] args) {

LinkedList<String> list = new LinkedList<>();

[Link]("A");
[Link]("B");

[Link](list);
}
}

List Methods
Method Description
add() Adds element
remove() Removes element
get() Gets element
set() Updates element
size() Returns size

2. Set Interface
A Set stores unique elements only.
Features
• No duplicates
• Unordered collection
• Faster searching
Common Set Classes
• HashSet
• LinkedHashSet
• TreeSet

HashSet Example

224
import [Link].*;

class Demo {
public static void main(String[] args) {

HashSet<String> set = new HashSet<>();

[Link]("Java");
[Link]("Python");
[Link]("Java");

[Link](set);
}
}
Output
[Java, Python]

TreeSet Example
import [Link].*;

class Demo {
public static void main(String[] args) {

TreeSet<Integer> set = new TreeSet<>();

[Link](30);
[Link](10);
[Link](20);

[Link](set);
}
}
Output
[10, 20, 30]

Set Methods
Method Description
add() Adds element

225
Method Description
remove() Removes element
contains() Checks element
size() Returns size

3. Map Interface
A Map stores data in key-value pairs.
Features
• Keys must be unique
• Values can be duplicated
• Fast data retrieval
Common Map Classes
• HashMap
• LinkedHashMap
• TreeMap

HashMap Example
import [Link].*;

class Demo {
public static void main(String[] args) {

HashMap<Integer, String> map = new HashMap<>();

[Link](1, "Java");
[Link](2, "Python");
[Link](3, "C++");

[Link](map);
}
}
Output
{1=Java, 2=Python, 3=C++}

226
TreeMap Example
import [Link].*;

class Demo {
public static void main(String[] args) {

TreeMap<Integer, String> map = new TreeMap<>();

[Link](3, "C");
[Link](1, "Java");
[Link](2, "Python");

[Link](map);
}
}
Output
{1=Java, 2=Python, 3=C}

Map Methods
Method Description
put() Inserts value
get() Retrieves value
remove() Removes value
containsKey() Checks key
size() Returns size

Difference Between List, Set, and Map


Feature List Set Map
Duplicate Elements Allowed Not Allowed Values only
Order Maintained Yes No Key-value
Index Access Yes No No

227
Feature List Set Map
Key-Value Pair No No Yes

Advantages of Collections Framework


• Dynamic memory allocation
• Built-in methods
• Easy data manipulation
• Improves coding efficiency

விளக்கம் (Tamil Explanation)


Collections Framework என்றால் என்ன?
Objects-ஐ store மை் றும் manage செய் ய பயன் படும் classes மை் றும்
interfaces சதாகுப்பு.

1. List
• Order maintain செய் யும்
• Duplicate values அனுமதிக்கும்
Example
ArrayList<String> list = new ArrayList<>();

2. Set
• Duplicate values அனுமதிக்காது
• Unique values மட்டும் store செய் யும்
Example
HashSet<String> set = new HashSet<>();

3. Map
• Key மை் றும் Value pair ஆக data store செய் யும்
Example
228
HashMap<Integer,String> map = new HashMap<>();

நினனவில் ககாள் ள

Interface முக்கிய பயன்

List Ordered + Duplicate


Set Unique values
Map Key-Value storage
File Handling in Java (I/O Streams)
File handling is used to create, read, write, and modify files.
Java provides the [Link] package for file operations.

What are I/O Streams?


• Input Stream → Reads data from a source
• Output Stream → Writes data to a destination
Input → Program → Output

Types of Streams
Stream Type Purpose
Byte Stream Handles binary data
Character Stream Handles text data

Byte Streams
Uses:
• FileInputStream
• FileOutputStream
These work with bytes.

Character Streams

229
Uses:
• FileReader
• FileWriter
These work with characters/text.

File Class
The File class is used to create and manage files.
import [Link].*;

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

File f = new File("[Link]");

if([Link]()) {
[Link]("File created");
}
else {
[Link]("File already exists");
}
}
}

Writing to a File
Using FileWriter
import [Link].*;

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

FileWriter fw = new FileWriter("[Link]");

[Link]("Welcome to Java");

[Link]();

[Link]("Data written");
}
}
230
Reading from a File
Using FileReader
import [Link].*;

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

FileReader fr = new FileReader("[Link]");

int ch;

while((ch = [Link]()) != -1) {


[Link]((char) ch);
}

[Link]();
}
}

Output
Welcome to Java

FileInputStream Example
import [Link].*;

class Demo {
public static void main(String[] args) throws Exception {

FileInputStream fin = new FileInputStream("[Link]");

int i;

while((i = [Link]()) != -1) {


[Link]((char)i);
}

[Link]();
}
}
231
FileOutputStream Example
import [Link].*;

class Demo {
public static void main(String[] args) throws Exception {

FileOutputStream fout =
new FileOutputStream("[Link]");

String s = "Java Programming";

byte b[] = [Link]();

[Link](b);

[Link]();

[Link]("Data stored");
}
}

Buffered Streams
Buffered streams improve performance.
Classes
• BufferedReader
• BufferedWriter

BufferedReader Example
import [Link].*;

class Demo {
public static void main(String[] args) throws Exception {

BufferedReader br =
new BufferedReader(
new FileReader("[Link]"));

String line;
232
while((line = [Link]()) != null) {
[Link](line);
}

[Link]();
}
}

Important Methods
Method Description
read() Reads data
write() Writes data
close() Closes stream
flush() Clears buffer
createNewFile() Creates file

Exception Handling in File Operations


File handling may produce exceptions like:
• IOException
• FileNotFoundException
Example:
try {
FileReader fr = new FileReader("[Link]");
}
catch(Exception e) {
[Link](e);
}

Advantages of File Handling


• Permanent data storage
• Easy file management
• Supports text and binary data
233
விளக்கம் (Tamil Explanation)
File Handling என்றால் என்ன?
File-ஐ create, read, write, modify செய் ேது.
Java-வில் [Link] package பயன் படுத்தப்படுகிைது.

I/O Streams
Stream சவனல

Input Stream Data read செய் யும்

Output Stream Data write செய் யும்

File உருவாக்குதல்
File f = new File("[Link]");

File-ல் எழுதுதல்
FileWriter fw = new FileWriter("[Link]");

File-ல் படித்தல்
FileReader fr = new FileReader("[Link]");

BufferedReader
பேகமாக file read செய் ய உதவும் .

முக்கிய Methods

Method பயன்

read() Data படிக்கும்

write() Data எழுதும்

234
Method பயன்

close() File close செய் யும்

நினனவில் ககாள் ள
• Byte Stream → binary data
• Character Stream → text data
• close() பயன் படுத்த பேண்டும்
• File handling-ல் exceptions ேரும் ோய் ப்பு உள் ளது
JDBC (Java Database Connectivity)
JDBC is an API used to connect Java applications with databases.
Using JDBC, we can:
• Connect to a database
• Execute SQL queries
• Insert, update, delete records
• Retrieve data
JDBC is available in the [Link] package.

JDBC Architecture
Java Application

JDBC API

JDBC Driver

Database

Types of JDBC Drivers


Type Description
Type 1 JDBC-ODBC Bridge
Type 2 Native API Driver

235
Type Description
Type 3 Network Protocol Driver
Type 4 Thin Driver (Most Used)

Steps to Connect JDBC


1. Import package
2. Load driver
3. Establish connection
4. Create statement
5. Execute query
6. Close connection

1. Import Package
import [Link].*;

2. Load Driver
[Link]("[Link]");

3. Establish Connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/test",
"root",
"password"
);

4. Create Statement
Statement st = [Link]();

5. Execute Query
Insert Example

236
[Link](
"insert into student values(1,'Arun')"
);

Select Example
ResultSet rs = [Link](
"select * from student"
);

6. Close Connection
[Link]();

Complete JDBC Example


import [Link].*;

class Demo {

public static void main(String[] args) {

try {

[Link]("[Link]");

Connection con =
[Link](
"jdbc:mysql://localhost:3306/test",
"root",
"password"
);

Statement st = [Link]();

ResultSet rs =
[Link]("select * from student");

while([Link]()) {

[Link](
[Link](1) + " " +
[Link](2)
237
);
}

[Link]();
}

catch(Exception e) {
[Link](e);
}
}
}

Output Example
1 Arun
2 Ravi

PreparedStatement
Used for dynamic and secure queries.
Advantages:
• Prevents SQL Injection
• Faster execution
• Easy parameter handling

PreparedStatement Example
import [Link].*;

class Demo {

public static void main(String[] args) {

try {

[Link]("[Link]");

Connection con =
[Link](
"jdbc:mysql://localhost:3306/test",
"root",
238
"password"
);

PreparedStatement ps =
[Link](
"insert into student values(?, ?)"
);

[Link](1, 101);
[Link](2, "Kumar");

[Link]();

[Link]("Record inserted");

[Link]();
}

catch(Exception e) {
[Link](e);
}
}
}

Important JDBC Interfaces


Interface Purpose
DriverManager Manages drivers
Connection Establishes connection
Statement Executes SQL query
PreparedStatement Executes parameterized query
ResultSet Stores retrieved data

ResultSet Methods
Method Description
next() Moves to next row

239
Method Description
getInt() Gets integer value
getString() Gets string value

Advantages of JDBC
• Simple database connectivity
• Supports multiple databases
• Platform independent
• Executes SQL directly

விளக்கம் (Tamil Explanation)


JDBC என்றால் என்ன?
Java application-ஐ database-உடன் connect செய் ய பயன் படும் API.

JDBC பயன்பாடுகள்
• Database connect செய் ய
• SQL query execute செய் ய
• Data insert/update/delete செய் ய
• Data retrieve செய் ய

JDBC Steps
Step சவனல

1 Package import
2 Driver load
3 Connection create
4 Statement create
5 Query execute

240
Step சவனல

6 Connection close

Connection Example
Connection con =
[Link](
"url",
"username",
"password"
);

PreparedStatement
Secure query execute செய் ய பயன் படும் .
PreparedStatement ps =
[Link]("insert into student values(?,?)");

முக்கிய Interfaces

Interface பயன்

Connection Database connection


Statement SQL execute
ResultSet Result data store

நினனவில் ககாள் ள
• JDBC → Java + Database connectivity
• PreparedStatement பாதுகாப்பானது
• ResultSet data retrieve செய் ய பயன் படும்
• பேறல முடிந்த பிைகு close() செய் ய பேண்டும்
Networking Basics in Java
Networking means connecting two or more computers/devices to share data and
resources.

241
Java provides networking support through the [Link] package.
Using Java networking, programs can:
• Communicate over the internet
• Transfer files
• Send messages
• Build client-server applications

Types of Networking
1. Client-Server Networking
• Client sends request
• Server processes and responds
Example:
• Web browser → Client
• Web server → Server
Client ←→ Server

2. Peer-to-Peer Networking
All computers act equally.
Example:
• File sharing systems

Important Networking Concepts


Term Meaning
IP Address Unique address of computer
Port Number Communication endpoint
Protocol Rules for communication
Socket Connection between client and server

IP Address
242
An IP address identifies a device in a network.
Example:
[Link]

Port Number
A port identifies a specific service/application.
Examples:
• 80 → HTTP
• 443 → HTTPS

Protocols
TCP
• Connection-oriented
• Reliable communication
UDP
• Faster but less reliable

Socket Programming
A socket is used for communication between client and server.
Java provides:
• Socket
• ServerSocket

Server Program Example


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

class Server {

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

ServerSocket ss = new ServerSocket(5000);


243
[Link]("Server waiting...");

Socket s = [Link]();

[Link]("Client connected");

DataInputStream dis =
new DataInputStream([Link]());

String msg = [Link]();

[Link]("Message: " + msg);

[Link]();
}
}

Client Program Example


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

class Client {

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

Socket s = new Socket("localhost", 5000);

DataOutputStream dos =
new DataOutputStream([Link]());

[Link]("Hello Server");

[Link]();

[Link]();

[Link]();
}
}

Output
244
Server Output
Server waiting...
Client connected
Message: Hello Server

URL Class
The URL class represents a web address.
import [Link].*;

class Demo {

public static void main(String[] args)


throws Exception {

URL u = new URL("[Link]

[Link]([Link]());
[Link]([Link]());
}
}

InetAddress Class
Used to get IP address information.
import [Link].*;

class Demo {

public static void main(String[] args)


throws Exception {

InetAddress ip =
[Link]("localhost");

[Link](ip);
}
}

Important Classes in [Link]

245
Class Purpose
Socket Client-side connection
ServerSocket Server-side connection
URL Represents web address
InetAddress IP address handling

Advantages of Java Networking


• Platform independent
• Easy client-server communication
• Supports distributed applications

விளக்கம் (Tamil Explanation)


Networking என்றால் என்ன?
இரண்டு அல் லது அதை் கு பமை் பட்ட computers/data devices
இறணந்து data share செய் ேது.
Java-வில் [Link] package பயன் படுத்தப்படுகிைது.

Client-Server Model
• Client request அனுப்பும்
• Server response அனுப்பும்

முக்கிய Terms

Term விளக்கம்
IP Address Computer address
Port Service number
Protocol Communication rules
Socket Connection channel

246
Socket Programming
Server
ServerSocket ss = new ServerSocket(5000);
Client
Socket s = new Socket("localhost", 5000);

முக்கிய Classes

Class பயன்
Socket Client connection
ServerSocket Server connection
URL Web address
InetAddress IP details

நினனவில் ககாள் ள
• TCP → Reliable communication
• UDP → Faster communication
• Socket → Client மை் றும் server communication
• [Link] package networking-க்கு பயன் படும்
• 5. Java Enterprise / Modern Java
Servlets and JSP in Java
Servlets and JSP are technologies used for developing dynamic web applications in
Java.
They run on a web server such as:
• Apache Tomcat
• GlassFish

What is a Servlet?
A Servlet is a Java program that handles client requests and generates dynamic
responses.

247
Servlets work on the server side.

Servlet Architecture
Client (Browser)

Web Server

Servlet

Database

Advantages of Servlets
• Platform independent
• Fast performance
• Secure
• Reusable

Servlet Life Cycle


A servlet goes through three stages:
1. init()
2. service()
3. destroy()

Important Servlet Methods


Method Purpose
init() Initializes servlet
service() Handles requests
doGet() Handles GET request
doPost() Handles POST request
destroy() Destroys servlet

248
Simple Servlet Example
import [Link].*;
import [Link].*;
import [Link].*;

public class DemoServlet extends HttpServlet {

public void doGet(


HttpServletRequest req,
HttpServletResponse res)
throws IOException {

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<h1>Hello Servlet</h1>");
}
}

Deployment Descriptor ([Link])


<web-app>

<servlet>
<servlet-name>Demo</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Demo</servlet-name>
<url-pattern>/demo</url-pattern>
</servlet-mapping>

</web-app>

What is JSP?
JSP stands for Java Server Pages.
It is used to create dynamic web pages using HTML and Java code.
JSP is easier than writing complete servlet code.

249
JSP Example
<html>
<body>

<h1>Welcome to JSP</h1>

<%
[Link]("Hello User");
%>

</body>
</html>

JSP Tags
Tag Purpose
<% %> Scriptlet
<%= %> Expression
<%! %> Declaration

JSP Expression Example


<%= "Welcome" %>

Difference Between Servlet and JSP


Servlet JSP
Java code dominant HTML dominant
Harder for UI design Easier for UI design
Better for business logic Better for presentation

Servlet vs JSP Flow


Browser Request

250
Servlet

JSP

Browser Response

Implicit Objects in JSP


Object Purpose
request Client request
response Server response
session Session management
out Output writing

Session Tracking
Used to maintain user data across multiple requests.
Methods:
• Cookies
• URL rewriting
• HttpSession

HttpSession Example
HttpSession session = [Link]();

[Link]("user", "Arun");

Advantages of JSP
• Easy web page development
• Reusable components
• Supports dynamic content

Important Packages
251
Package Purpose
[Link] Servlet classes
[Link] HTTP servlet support
[Link] JSP support

விளக்கம் (Tamil Explanation)


Servlet என்றால் என்ன?
Server side-ல் run ஆகும் Java program.
Client request-ஐ process செய் து response அனுப் பும் .

Servlet Life Cycle


Method சவனல

init() ஆரம் பிக்கும்

service() Request handle செய் யும்

destroy() Servlet முடியும்

JSP என்றால் என்ன?


HTML + Java code பெர்த்து dynamic web page உருோக்க பயன் படும்
technology.

JSP Tags
Tag பயன்
<% %> Java code
<%= %> Output print
<%! %> Variable declaration

Servlet மற் றும் JSP வித்தியாேம்

252
Servlet JSP

Java அதிகம் HTML அதிகம்

UI design கடினம் UI design எளிது

Session Tracking
User data-ஐ multiple requests-ல் maintain செய் ய பயன் படும் .

நினனவில் ககாள் ள
• Servlet → Business logic
• JSP → Presentation/UI
• doGet() மை் றும் doPost() முக்கிய methods
• JSP என் பது servlet ஆக convert செய் யப்படும்
Servlets and JSP in Java
Servlets and JSP are technologies used to create dynamic web applications in Java.
They run on a web server such as:
• Apache Tomcat
• GlassFish

What is a Servlet?
A Servlet is a Java program that runs on the server and handles client requests.
It is mainly used to:
• Process requests
• Generate dynamic responses
• Interact with databases
Servlets are part of the [Link] package.

Servlet Architecture
Browser → Web Server → Servlet → Database

253
Servlet Life Cycle
A servlet goes through three stages:
1. init()
2. service()
3. destroy()

1. init()
Called only once when servlet starts.
public void init() {
// initialization code
}

2. service()
Handles client requests.
public void service(
ServletRequest req,
ServletResponse res
){
// request processing
}

3. destroy()
Called before servlet is removed.
public void destroy() {
// cleanup code
}

Simple Servlet Example


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

public class HelloServlet


extends HttpServlet {

254
public void doGet(
HttpServletRequest req,
HttpServletResponse res
) throws IOException {

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<h1>Hello Servlet</h1>");
}
}

[Link] Configuration
<web-app>

<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

HTTP Methods in Servlet


Method Purpose
doGet() Retrieves data
doPost() Sends data
doPut() Updates data
doDelete() Deletes data

What is JSP?
JSP stands for Java Server Pages.
255
It is used to create dynamic web pages using:
• HTML
• Java code
• JSP tags
JSP simplifies servlet programming.

JSP Example
<html>
<body>

<h1>Welcome to JSP</h1>

<%
[Link]("Current Time: " + new [Link]());
%>

</body>
</html>

JSP Tags
Tag Purpose
<% %> Java code
<%= %> Expression
<%! %> Declaration

JSP Expression Example


<%= "Hello JSP" %>

Difference Between Servlet and JSP


Servlet JSP
Java code dominant HTML dominant
Harder UI design Easier UI design

256
Servlet JSP
Used for business logic Used for presentation
.java file .jsp file

MVC Architecture
Servlets and JSP are commonly used in MVC:
Model → Business Logic
View → JSP
Controller → Servlet

Advantages of Servlets
• Fast performance
• Platform independent
• Secure
• Reusable

Advantages of JSP
• Easy web page creation
• Reduces Java code
• Supports reusable components

விளக்கம் (Tamil Explanation)


Servlet என்றால் என்ன?
Server-ல் run ஆகும் Java program.
Client request-ஐ handle செய் ய பயன் படும் .

Servlet Life Cycle


Method பயன்

init() ஆரம் ப initialization

257
Method பயன்

service() Request process செய் யும்

destroy() Cleanup செய் யும்

JSP என்றால் என்ன?


Java Server Pages.
HTML + Java code பெர்த்து dynamic web page உருோக்க பயன் படும் .

JSP Tags
Tag சவனல
<% %> Java code
<%= %> Output expression

Servlet vs JSP
Servlet JSP
Logic handling UI handling

Java code அதிகம் HTML அதிகம்

நினனவில் ககாள் ள
• Servlet → Controller logic
• JSP → Presentation layer
• doGet() மை் றும் doPost() முக்கிய methods
• JSP web page உருோக்க எளிதானது

REST APIs with Spring Boot


A REST API is used for communication between applications over HTTP.
Spring Boot helps create REST APIs quickly and easily.

258
REST stands for:
• Representational
• State
• Transfer

What is Spring Boot?


Spring Boot is a Java framework built on top of Spring Framework.
It simplifies:
• Web application development
• REST API creation
• Database connectivity
• Dependency management

Advantages of Spring Boot


• Faster development
• Embedded server
• Minimal configuration
• Production-ready applications

REST API Basics


REST APIs use HTTP methods.
Method Purpose
GET Retrieve data
POST Insert data
PUT Update data
DELETE Delete data

Spring Boot REST Architecture


Client → Controller → Service → Repository → Database
259
Creating Spring Boot REST API

1. Create Spring Boot Project


Using:
• Spring Initializr
Add dependencies:
• Spring Web
• Spring Data JPA
• MySQL Driver

2. Main Application Class


import [Link];
import [Link];

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {

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

3. Create REST Controller


import [Link].*;

@RestController
public class HelloController {

@GetMapping("/hello")
public String hello() {

return "Hello Spring Boot";


260
}
}

Output
[Link]
Response:
Hello Spring Boot

Important Annotations
Annotation Purpose
@SpringBootApplication Main class
@RestController REST controller
@GetMapping Handles GET request
@PostMapping Handles POST request
@PutMapping Handles PUT request
@DeleteMapping Handles DELETE request

Example: Returning JSON Data


import [Link].*;

@RestController
public class StudentController {

@GetMapping("/student")
public Student getStudent() {

return new Student(


101,
"Arun"
);
}
}

261
Student Class
class Student {

int id;
String name;

public Student(int id, String name) {

[Link] = id;
[Link] = name;
}

public int getId() {


return id;
}

public String getName() {


return name;
}
}

JSON Output
{
"id": 101,
"name": "Arun"
}

POST Request Example


@PostMapping("/save")
public String saveStudent(
@RequestBody Student s
){

return "Student Saved";


}

Path Variable Example


@GetMapping("/student/{id}")
public String getStudent(
262
@PathVariable int id
){

return "Student ID: " + id;


}

Request Parameter Example


@GetMapping("/add")
public int add(
@RequestParam int a,
@RequestParam int b
){

return a + b;
}

[Link]
[Link]=8081
Changes default port number.

Spring Boot Database Connection


[Link]=
jdbc:mysql://localhost:3306/test

[Link]=root
[Link]=password

REST API Testing Tools


• Postman
• Browser
• cURL

Advantages of REST APIs


• Lightweight
• Fast communication
263
• Platform independent
• Supports JSON/XML

விளக்கம் (Tamil Explanation)


REST API என்றால் என்ன?
Applications ஒன் றுடன் ஒன் று HTTP மூலம் communicate செய் ய
பயன் படும் API.

Spring Boot என்றால் என்ன?


Java framework.
REST API மை் றும் web application உருோக்க எளிதாக்குகிைது.

முக்கிய HTTP Methods


Method சவனல

GET Data retrieve


POST Data insert
PUT Data update
DELETE Data delete

Controller Example
@RestController
public class HelloController

GET Mapping
@GetMapping("/hello")

POST Mapping
@PostMapping("/save")

264
JSON Output
REST API சபாதுோக JSON format-ல் data அனுப்பும் .

முக்கிய Annotations
Annotation பயன்
@RestController REST controller
@GetMapping GET request
@PostMapping POST request

நினனவில் ககாள் ள
• Spring Boot → REST API development
• REST → HTTP communication
• JSON அதிகமாக பயன் படுத்தப் படுகிைது
• Postman மூலம் API test செய் யலாம்
Microservices Basics
Microservices architecture is a software development approach where an
application is divided into small independent services.
Each service:
• Performs a specific task
• Runs independently
• Communicates using APIs
Microservices are commonly built using:
• Spring Boot
• Spring Cloud
• Docker

Monolithic vs Microservices
Monolithic Architecture
All modules are combined into one application.
265
Single Application
├── User Module
├── Payment Module
└── Product Module
Problems
• Difficult to scale
• Hard maintenance
• Entire application redeployment needed

Microservices Architecture
Each module is a separate service.
User Service
Payment Service
Product Service
Each service works independently.

Features of Microservices
• Small independent services
• Separate deployment
• API communication
• Independent database
• Easy scalability

Microservices Architecture
Client

API Gateway

Microservices
├── User Service
├── Order Service
└── Payment Service

Important Components
266
Component Purpose
API Gateway Entry point for requests
Service Registry Service discovery
Load Balancer Distributes traffic
Config Server Central configuration
Database Separate storage

Communication Between Services


Microservices communicate using:
• REST APIs
• HTTP
• Messaging systems
Example:
• JSON data exchange

Example REST API in Microservice


@RestController
public class UserController {

@GetMapping("/user")
public String user() {

return "User Service";


}
}

API Gateway
An API Gateway handles all incoming requests.
Popular gateway:
• Spring Cloud Gateway
Benefits:

267
• Security
• Routing
• Authentication

Service Discovery
Used to locate services dynamically.
Popular tool:
• Netflix Eureka

Database Per Service


Each microservice usually has its own database.
Example:
User Service → User DB
Order Service → Order DB

Advantages of Microservices
• Easy deployment
• Independent scaling
• Better fault isolation
• Faster development
• Technology flexibility

Challenges of Microservices
• Complex architecture
• Network communication issues
• Data consistency problems
• Monitoring difficulty

Spring Boot in Microservices


Spring Boot is widely used because:
268
• Easy REST API creation
• Embedded server
• Fast setup

Spring Cloud
Spring Cloud provides:
• Service discovery
• API gateway
• Distributed configuration
• Load balancing

Docker in Microservices
Docker packages applications into containers.
Benefits:
• Easy deployment
• Same environment everywhere

Microservices Workflow
Client Request

API Gateway

Service Discovery

Microservice

Database

Real-World Examples
Companies using microservices:
• Netflix
• Amazon

269
• Uber

விளக்கம் (Tamil Explanation)


Microservices என்றால் என்ன?
ஒரு சபரிய application-ஐ சிறிய independent services ஆக பிரித்து
உருோக்கும் architecture.

முக்கிய அம் ேங் கள்


• ஒே் சோரு service-மும் தனியாக பேறல செய் யும்
• REST API மூலம் communicate செய் யும்
• தனித்தனி deployment

Monolithic vs Microservices
Monolithic Microservices
Single application Multiple small services
Hard to scale Easy scaling
Full deployment needed Independent deployment

முக்கிய Components

Component பயன்
API Gateway Request handling
Service Registry Service discovery
Load Balancer Traffic distribution

பயன்படுத்தப் படும் Technologies


• Spring Boot
• Spring Cloud
• Docker
270
Advantages
• Fast development
• Easy maintenance
• Independent scaling

நினனவில் ககாள் ள
• Microservice = Small independent service
• REST API மூலம் services communicate செய் யும்
• ஒே் சோரு service-க்கும் தனி database இருக்கலாம்
• Cloud applications-ல் அதிகமாக பயன் படுத்தப்படுகிைது

. Additional Topics (Optional but Important)


Java 8+ Features (Lambda Expressions & Streams API)
Java 8 introduced many powerful features that simplify coding and improve
performance.
Important Java 8 features:
• Lambda Expressions
• Streams API
• Functional Interfaces
• Method References
• Default Methods
• Optional Class
• Date and Time API

1. Lambda Expressions
A Lambda Expression is an anonymous function.
It helps write shorter and cleaner code.

Syntax
271
(𝑝𝑎𝑟𝑎𝑚𝑒𝑡𝑒𝑟𝑠) → 𝑒𝑥𝑝𝑟𝑒𝑠𝑠𝑖𝑜𝑛
Example:
(a, b) -> a + b

Traditional Method
interface Demo {
void show();
}

class Test {
public static void main(String[] args) {

Demo d = new Demo() {

public void show() {


[Link]("Hello");
}
};

[Link]();
}
}

Using Lambda Expression


interface Demo {
void show();
}

class Test {

public static void main(String[] args) {

Demo d = () -> {
[Link]("Hello Lambda");
};

[Link]();
}
}

272
Advantages of Lambda
• Reduces code
• Improves readability
• Supports functional programming

Functional Interface
An interface with only one abstract method.
Example:
• Runnable
• Comparator

Example
@FunctionalInterface
interface Demo {

void display();
}

Lambda with Parameters


interface Add {

int sum(int a, int b);


}

class Test {

public static void main(String[] args) {

Add a = (x, y) -> x + y;

[Link]([Link](10, 20));
}
}

Output

273
30

2. Streams API
Streams API is used to process collections efficiently.
It supports:
• Filtering
• Sorting
• Mapping
• Collecting
Streams work on collections like:
• List
• Set

Stream Creation
List<Integer> list =
[Link](10, 20, 30);
Stream<Integer> s = [Link]();

Filter Example
import [Link].*;
import [Link].*;

class Demo {

public static void main(String[] args) {

List<Integer> list =
[Link](10, 15, 20, 25);

[Link]()
.filter(n -> n % 2 == 0)
.forEach([Link]::println);
}
}

274
Output
10
20

map() Example
Used to transform data.
import [Link].*;

class Demo {

public static void main(String[] args) {

List<Integer> list =
[Link](1, 2, 3, 4);

[Link]()
.map(n -> n * n)
.forEach([Link]::println);
}
}

Output
1
4
9
16

sorted() Example
[Link]()
.sorted()
.forEach([Link]::println);

collect() Example
List<Integer> result =
[Link]()
.filter(n -> n > 10)
.collect([Link]());
275
Method Reference
Method references simplify lambda expressions.

Example
[Link]([Link]::println);
Equivalent to:
n -> [Link](n)

forEach() Example
import [Link].*;

class Demo {

public static void main(String[] args) {

List<String> names =
[Link]("Java", "Python");

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

Optional Class
Avoids NullPointerException.
Optional<String> name =
[Link]("Java");

Date and Time API


Java 8 introduced new date/time classes.
Example:
import [Link].*;

class Demo {

276
public static void main(String[] args) {

LocalDate d = [Link]();

[Link](d);
}
}

Advantages of Streams API


• Less code
• Better readability
• Parallel processing support
• Faster data operations

Important Stream Methods


Method Purpose
filter() Filters data
map() Transforms data
sorted() Sorts data
collect() Collects result
forEach() Iterates data

விளக்கம் (Tamil Explanation)


Java 8 Features என்றால் என்ன?
Java 8-ல் அறிமுகமான புதிய features.

Lambda Expression
சிறிய anonymous function.
Syntax
() -> {}

277
Example
(a,b) -> a+b

Streams API
Collection data-ஐ process செய் ய பயன் படும் .

முக்கிய Methods

Method சவனல

filter() Data filter செய் யும்

map() Data மாை் றும்

sorted() Sort செய் யும்

forEach() Iterate செய் யும்

Stream Example
[Link]()
.filter(n -> n > 10)

Method Reference
[Link]::println

Advantages
• Code குறையும்
• Readability அதிகரிக்கும்
• Faster processing

நினனவில் ககாள் ள
• Lambda → Short function syntax

278
• Streams → Collection processing
• filter() மை் றும் map() மிகவும் முக்கியம்
• Java 8 functional programming support ேைங் குகிைது
GUI in Java (Swing / JavaFX)
GUI stands for Graphical User Interface.
GUI applications allow users to interact using:
• Windows
• Buttons
• Text fields
• Menus
• Dialog boxes
Java provides GUI frameworks such as:
• Swing
• JavaFX

1. Swing
Swing is a Java GUI toolkit available in the [Link] package.
It is built on top of AWT (Abstract Window Toolkit).

Features of Swing
• Platform independent
• Rich GUI components
• Lightweight components
• Event handling support

Common Swing Components


Component Purpose
JFrame Main window
JButton Button

279
Component Purpose
JLabel Text label
JTextField Text input
JPasswordField Password input
JCheckBox Checkbox
JRadioButton Radio button

JFrame Example
import [Link].*;

class Demo {

public static void main(String[] args) {

JFrame f = new JFrame("My Window");

[Link](400, 300);

[Link](true);
}
}

JButton Example
import [Link].*;

class Demo {

public static void main(String[] args) {

JFrame f = new JFrame();

JButton b = new JButton("Click");

[Link](100, 100, 100, 40);

[Link](b);

280
[Link](300, 300);

[Link](null);

[Link](true);
}
}

JLabel and JTextField Example


import [Link].*;

class Demo {

public static void main(String[] args) {

JFrame f = new JFrame();

JLabel l = new JLabel("Name:");

JTextField t = new JTextField();

[Link](50, 50, 100, 30);

[Link](120, 50, 120, 30);

[Link](l);
[Link](t);

[Link](300, 200);

[Link](null);

[Link](true);
}
}

Event Handling in Swing


Events occur when users interact with components.
Example:
• Button click
281
• Keyboard input

ActionListener Example
import [Link].*;
import [Link].*;

class Demo {

public static void main(String[] args) {

JFrame f = new JFrame();

JButton b = new JButton("Click");

[Link](100, 100, 100, 40);

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link]("Button Clicked");
}
});

[Link](b);

[Link](300, 300);

[Link](null);

[Link](true);
}
}

Layout Managers
Used to arrange components automatically.
Layout Purpose
FlowLayout Left to right

282
Layout Purpose
BorderLayout Top, bottom, left, right
GridLayout Grid format

2. JavaFX
JavaFX is a modern GUI framework for Java.
It provides:
• Better UI design
• Animation support
• CSS styling
• Multimedia support

JavaFX Features
• Modern interface
• Rich controls
• 2D/3D graphics
• FXML support

JavaFX Application Example


import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class Demo extends Application {

public void start(Stage stage) {

Button b = new Button("Click");

FlowPane root = new FlowPane();

[Link]().add(b);
283
Scene scene =
new Scene(root, 300, 200);

[Link]("JavaFX");

[Link](scene);

[Link]();
}

public static void main(String[] args) {

launch(args);
}
}

Swing vs JavaFX
Swing JavaFX
Older framework Modern framework
Less styling support CSS styling support
Basic graphics Advanced graphics
Lightweight Rich UI

Advantages of GUI
• User-friendly
• Easy interaction
• Better visualization
• Professional applications

Common GUI Applications


• Calculator
• Text editor
• Banking software
284
• Student management system

விளக்கம் (Tamil Explanation)


GUI என்றால் என்ன?
Graphical User Interface.
User window, button, textbox பபான் ைேை் றின் மூலம் interact செய் யும்
interface.

Swing
[Link] package பயன் படுத்தி GUI application
உருோக்கப்படுகிைது.

முக்கிய Swing Components


Component பயன்

JFrame Window
JButton Button
JTextField Text input

Button Example
JButton b = new JButton("Click");

Event Handling
Button click பபான் ை events handle செய் ய பயன் படும் .
addActionListener()

JavaFX
JavaFX என் பது modern Java GUI framework.

JavaFX Features
285
• Stylish UI
• Animation support
• CSS support

Swing vs JavaFX
Swing JavaFX

பறைய framework புதிய framework


Basic UI Modern UI

நினனவில் ககாள் ள
• Swing → Traditional GUI
• JavaFX → Modern GUI
• JFrame முக்கிய window component
• Event handling GUI-ல் முக்கியமானது

GUI in Java (Swing / JavaFX)


GUI stands for Graphical User Interface.
GUI applications allow users to interact using:
• Windows
• Buttons
• Text fields
• Menus
• Dialog boxes
Java provides GUI frameworks such as:
• Swing
• JavaFX

1. Swing
Swing is a Java GUI toolkit available in the [Link] package.
286
It is built on top of AWT (Abstract Window Toolkit).

Features of Swing
• Platform independent
• Rich GUI components
• Lightweight components
• Event handling support

Common Swing Components


Component Purpose
JFrame Main window
JButton Button
JLabel Text label
JTextField Text input
JPasswordField Password input
JCheckBox Checkbox
JRadioButton Radio button

JFrame Example
import [Link].*;

class Demo {

public static void main(String[] args) {

JFrame f = new JFrame("My Window");

[Link](400, 300);

[Link](true);
}
}

287
JButton Example
import [Link].*;

class Demo {

public static void main(String[] args) {

JFrame f = new JFrame();

JButton b = new JButton("Click");

[Link](100, 100, 100, 40);

[Link](b);

[Link](300, 300);

[Link](null);

[Link](true);
}
}

JLabel and JTextField Example


import [Link].*;

class Demo {

public static void main(String[] args) {

JFrame f = new JFrame();

JLabel l = new JLabel("Name:");

JTextField t = new JTextField();

[Link](50, 50, 100, 30);

[Link](120, 50, 120, 30);

[Link](l);
[Link](t);
288
[Link](300, 200);

[Link](null);

[Link](true);
}
}

Event Handling in Swing


Events occur when users interact with components.
Example:
• Button click
• Keyboard input

ActionListener Example
import [Link].*;
import [Link].*;

class Demo {

public static void main(String[] args) {

JFrame f = new JFrame();

JButton b = new JButton("Click");

[Link](100, 100, 100, 40);

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link]("Button Clicked");
}
});

[Link](b);

[Link](300, 300);
289
[Link](null);

[Link](true);
}
}

Layout Managers
Used to arrange components automatically.
Layout Purpose
FlowLayout Left to right
BorderLayout Top, bottom, left, right
GridLayout Grid format

2. JavaFX
JavaFX is a modern GUI framework for Java.
It provides:
• Better UI design
• Animation support
• CSS styling
• Multimedia support

JavaFX Features
• Modern interface
• Rich controls
• 2D/3D graphics
• FXML support

JavaFX Application Example


import [Link];
import [Link];

290
import [Link];
import [Link];
import [Link];

public class Demo extends Application {

public void start(Stage stage) {

Button b = new Button("Click");

FlowPane root = new FlowPane();

[Link]().add(b);

Scene scene =
new Scene(root, 300, 200);

[Link]("JavaFX");

[Link](scene);

[Link]();
}

public static void main(String[] args) {

launch(args);
}
}

Swing vs JavaFX
Swing JavaFX
Older framework Modern framework
Less styling support CSS styling support
Basic graphics Advanced graphics
Lightweight Rich UI

Advantages of GUI

291
• User-friendly
• Easy interaction
• Better visualization
• Professional applications

Common GUI Applications


• Calculator
• Text editor
• Banking software
• Student management system

விளக்கம் (Tamil Explanation)


GUI என்றால் என்ன?
Graphical User Interface.
User window, button, textbox பபான் ைேை் றின் மூலம் interact செய் யும்
interface.

Swing
[Link] package பயன் படுத்தி GUI application
உருோக்கப்படுகிைது.

முக்கிய Swing Components

Component பயன்

JFrame Window
JButton Button
JTextField Text input

Button Example
JButton b = new JButton("Click");
292
Event Handling
Button click பபான் ை events handle செய் ய பயன் படும் .
addActionListener()

JavaFX
JavaFX என் பது modern Java GUI framework.

JavaFX Features
• Stylish UI
• Animation support
• CSS support

Swing vs JavaFX
Swing JavaFX

பறைய framework புதிய framework


Basic UI Modern UI

நினனவில் ககாள் ள
• Swing → Traditional GUI
• JavaFX → Modern GUI
• JFrame முக்கிய window component
• Event handling GUI-ல் முக்கியமானது

Unit Testing with JUnit


Unit testing is the process of testing individual units (methods/classes) of a
program.
In Java, unit testing is commonly done using JUnit.

293
What is JUnit?
JUnit is a testing framework used to:
• Test Java programs
• Verify outputs
• Detect bugs automatically
It is widely used with:
• Apache Maven
• Gradle
• Eclipse IDE
• IntelliJ IDEA

Advantages of Unit Testing


• Finds bugs early
• Improves code quality
• Easier maintenance
• Supports automation

JUnit Annotations
Annotation Purpose
@Test Marks test method
@BeforeEach Runs before each test
@AfterEach Runs after each test
@BeforeAll Runs once before all tests
@AfterAll Runs once after all tests

Simple Java Class


class Calculator {

int add(int a, int b) {

294
return a + b;
}
}

JUnit Test Example


import [Link];

import static [Link].*;

class CalculatorTest {

@Test
void testAdd() {

Calculator c = new Calculator();

int result = [Link](10, 20);

assertEquals(30, result);
}
}

Output
Test Passed

Assertion Methods
Assertions are used to compare expected and actual results.
Method Purpose
assertEquals() Checks equality
assertTrue() Checks true condition
assertFalse() Checks false condition
assertNull() Checks null value
assertNotNull() Checks non-null value

295
assertTrue() Example
@Test
void testValue() {

int a = 10;

assertTrue(a > 5);


}

assertFalse() Example
@Test
void testCheck() {

int a = 5;

assertFalse(a > 10);


}

Before and After Methods


import [Link].*;

class DemoTest {

@BeforeEach
void before() {

[Link]("Before Test");
}

@Test
void test1() {

[Link]("Test Running");
}

@AfterEach
void after() {

[Link]("After Test");
}
}
296
Testing Exceptions
@Test
void testException() {

assertThrows(
[Link],
() -> {
int x = 10 / 0;
}
);
}

Maven Dependency for JUnit 5


<dependency>
<groupId>[Link]</groupId>

<artifactId>junit-jupiter</artifactId>

<version>5.10.0</version>

<scope>test</scope>
</dependency>

Running JUnit Tests


Tests can be run using:
• IDE
• Maven
• Gradle
• Command line

Test-Driven Development (TDD)


TDD means:
1. Write test
2. Write code

297
3. Run test
4. Refactor code

Best Practices
• Test one functionality at a time
• Use meaningful test names
• Keep tests independent
• Automate testing

Advantages of JUnit
• Automated testing
• Easy debugging
• Improves reliability
• Faster development

விளக்கம் (Tamil Explanation)


Unit Testing என்றால் என்ன?
Program-இன் individual methods/classes ெரியாக பேறல செய் கிைதா
என் பறத test செய் ேது.

JUnit என்றால் என்ன?


JUnit என் பது Java testing framework.

முக்கிய Annotations

Annotation பயன்
@Test Test method

@BeforeEach Test முன் run ஆகும்

@AfterEach Test பிைகு run ஆகும்

298
Example
@Test
void testAdd()

Assertion Methods
Method சவனல

assertEquals() Values compare செய் யும்

assertTrue() Condition true என check செய் யும்

Exception Testing
assertThrows()

Maven Dependency
JUnit பயன் படுத்த dependency add செய் ய பேண்டும் .

நினனவில் ககாள் ள
• JUnit → Unit testing framework
• @Test முக்கிய annotation
• Assertions result verify செய் ய பயன் படும்
• Testing code quality அதிகரிக்கும்
Build Tools in Java (Maven & Gradle)
Build tools automate the process of:
• Compiling code
• Managing dependencies
• Running tests
• Packaging applications
• Deployment
Popular Java build tools:
299
• Apache Maven
• Gradle

Why Build Tools are Needed?


Without build tools:
• Dependencies must be downloaded manually
• Compilation becomes difficult
• Large projects are hard to manage
Build tools simplify project management.

1. Apache Maven
Apache Maven is a project management and build automation tool.
It uses:
• XML configuration
• Standard project structure

Maven Architecture
Project

[Link]

Dependencies + Plugins

Build Process

Maven Project Structure


project
├── src
│ ├── main
│ │ └── java
│ └── test
├── [Link]

300
[Link]
The main configuration file in Maven.
Example:
<project>

<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>

<artifactId>sample</artifactId>

<version>1.0</version>

</project>

Maven Dependencies
Dependencies are external libraries.
Example: JUnit dependency
<dependency>

<groupId>[Link]</groupId>

<artifactId>junit-jupiter</artifactId>

<version>5.10.0</version>

</dependency>

Common Maven Commands


Command Purpose
mvn compile Compiles project
mvn test Runs tests
mvn package Creates JAR/WAR
mvn install Installs to local repository

301
Command Purpose
mvn clean Removes old files

Example
mvn package
Creates executable JAR/WAR file.

Maven Repository
Libraries are downloaded from:
• Maven Central Repository

Advantages of Maven
• Easy dependency management
• Standard project structure
• Plugin support
• Easy integration

2. Gradle
Gradle is a modern build automation tool.
It uses:
• Groovy DSL
• Kotlin DSL
Gradle is faster than Maven in many cases.

Gradle Build File


plugins {
id 'java'
}

group = '[Link]'

302
version = '1.0'

Dependency Example
dependencies {

testImplementation
'[Link]:junit-jupiter:5.10.0'
}

Common Gradle Commands


Command Purpose
gradle build Builds project
gradle test Runs tests
gradle clean Cleans project
gradle run Runs application

Example
gradle build

Maven vs Gradle
Maven Gradle
XML configuration Groovy/Kotlin DSL
Slower builds Faster builds
Easy for beginners More flexible
Convention-based Highly customizable

Dependency Management
Both tools automatically:
• Download libraries
303
• Manage versions
• Resolve conflicts

Plugins
Plugins add additional functionality.
Examples:
• Java plugin
• Spring Boot plugin

Spring Boot with Maven


Example dependency:
<dependency>

<groupId>[Link]</groupId>

<artifactId>
spring-boot-starter-web
</artifactId>

</dependency>

Spring Boot with Gradle


implementation
'[Link]:
spring-boot-starter-web'

Advantages of Build Tools


• Automation
• Faster development
• Easy dependency handling
• Better project organization

விளக்கம் (Tamil Explanation)


304
Build Tool என்றால் என்ன?
Project compile, dependency management, testing பபான் ைேை் றை automate
செய் ய பயன் படும் tool.

முக்கிய Build Tools


• Apache Maven
• Gradle

Maven
XML-based build tool.
முக்கிய file:
[Link]

Maven Commands
Command சவனல

mvn compile Compile செய் யும்

mvn test Test run செய் யும்

mvn package JAR உருோக்கும்

Gradle
Modern build tool.
Groovy/Kotlin DSL பயன் படுத்துகிைது.

Gradle Example
plugins {
id 'java'
}

Maven vs Gradle
305
Maven Gradle
XML Groovy/Kotlin
Easy Flexible
Slower Faster

நினனவில் ககாள் ள
• Maven → [Link]
• Gradle → [Link]
• Dependencies automatically download ஆகும்
• Build tools development பேகத்றத அதிகரிக்கும்

Version Control with Git


Git is a distributed version control system used to track changes in source code.
It helps developers:
• Manage code versions
• Collaborate with teams
• Restore previous versions
• Track project history

What is Version Control?


Version control is a system that records changes made to files over time.
Benefits:
• Backup of code
• Team collaboration
• Change tracking
• Error recovery

Types of Version Control

306
Type Description
Local Version Control Stored locally
Centralized Version Control Single central server
Distributed Version Control Every user has full copy
Git is a distributed version control system.

Git Architecture
Working Directory

Staging Area

Local Repository

Remote Repository

Important Git Terms


Term Meaning
Repository Project storage
Commit Saved changes
Branch Separate development line
Merge Combine branches
Clone Copy repository

Git Installation
Official website:
Git Official Website

Configure Git
git config --global [Link] "YourName"

git config --global [Link] "you@[Link]"


307
Create Git Repository
git init
Creates a new Git repository.

Check Status
git status
Shows file changes.

Add Files
git add [Link]
Add all files:
git add .

Commit Changes
git commit -m "First commit"

View Commit History


git log

Branching
Create branch:
git branch feature1
Switch branch:
git checkout feature1
Create and switch:
git checkout -b feature1

Merge Branch
git merge feature1
308
Remote Repository
Remote repositories are hosted online.
Popular platforms:
• GitHub
• GitLab
• Bitbucket

Clone Repository
git clone [Link]

Connect Local Repository


git remote add origin URL

Push Changes
git push origin main

Pull Changes
git pull origin main

Git Workflow
Edit Files

git add

git commit

git push

Important Git Commands

309
Command Purpose
git init Initialize repository
git status Show status
git add Add files
git commit Save changes
git push Upload changes
git pull Download changes
git clone Copy repository

Advantages of Git
• Fast and efficient
• Distributed system
• Easy collaboration
• Tracks all changes
• Supports branching

Git vs GitHub
Git GitHub
Version control tool Cloud hosting platform
Installed locally Online service
Tracks changes Stores repositories

விளக்கம் (Tamil Explanation)


Git என்றால் என்ன?
Git என் பது source code changes-ஐ track செய் ய பயன் படும் version
control system.

Version Control பயன்பாடுகள்


310
• Code backup
• Team collaboration
• Previous versions restore செய் ய

முக்கிய Git Commands

Command சவனல

git init Repository create செய் யும்

git status Status காட்டும்

git add Files add செய் யும்

git commit Changes save செய் யும்

git push Online upload செய் யும்

Branching
git branch feature1

GitHub
GitHub என் பது Git repositories online-ல் store செய் ய பயன் படும்
platform.

Git Workflow
git add

git commit

git push

நினனவில் ககாள் ள
• Git → Version control system
• GitHub → Online repository hosting

311
• commit changes save செய் யும்
• push online upload செய் யும்

How to Study This Syllabus


Start simple, then build up:
1. Basics → OOP → Core Java
2. Practice coding daily
3. Move to advanced topics (collections, threads)
4. Finally learn frameworks like Spring

312

You might also like