Java
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)
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
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
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
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
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.
2. Object-Oriented
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
உருோக்க எளிதாக இருக்கும் .
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
24
25
6
These are the main components required to develop and run Java programs.
26
JVM என் பது Java program-ஐ run செய் யும் virtual machine ஆகும் .
இது bytecode-ஐ machine code-ஆக மாை் றுகிைது.
27
• Development utilities
Formula
JDK = JRE + Development Tools
Use
If you want to:
• write code
• compile programs
• run programs
you need JDK.
28
7
29
JDK
└── JRE
└── JVM
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
33
6
A Java program is written using:
• Class
• Main method
• Statements
• Objects and methods
Every Java program follows a specific structure.
34
class என் பது class உருோக்க பயன் படும் keyword.
Hello என் பது class சபயர்.
2. Main Method
public static void main(String[] args)
4. Statement
35
[Link]("Hello World");
36
6
Source Code (.java)
↓
Compiler (javac)
↓
37
Bytecode (.class)
↓
JVM
↓
Output
class Hello {
// Main method
public static void main(String[] args) {
// Print statement
[Link]("Hello World");
}
}
39
7
Class
└── Main Method
└── Statements
Summary
Part Purpose
class Defines class
main() Starting point
braces Define blocks
[Link]() Prints output
semicolon Ends statement
40
Variables, Data Types, and Operators in Java
41
6
These are the basic building blocks of every Java program.
1. Variables
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
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;
Data type என் பது variable எந்த ேறக data-ஐ store செய் யும் என் பறத
குறிப் பிடும் .
3. Operators
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
int a = 10;
int b = 5;
int sum = a + b;
Summary Table
Topic Meaning
Variable Stores value
51
Topic Meaning
Data Type Defines type of data
Operator Performs operations
52
7
Input and Output are used for interaction between:
• user
• program
53
1. Output in Java
A) print()
Example
[Link]("Hello ");
[Link]("World");
Output
Hello World
B) println()
Example
[Link]("Hello");
[Link]("World");
Output
Hello
World
54
println() output print செய் த பிைகு next line-க்கு செல் கிைது.
C) printf()
Example
int age = 20;
2. Input in Java
55
Taking Integer Input
56
5
Example
import [Link];
class Demo {
public static void main(String[] args) {
57
Scanner sc = new Scanner([Link]);
class Demo {
public static void main(String[] args) {
59
6
User → Input → Program → Output → Screen
class Addition {
public static void main(String[] args) {
int a, b, sum;
sum = a + b;
60
Output
Enter first number: 10
Enter second number: 20
Sum = 30
Important Points
Summary Table
Concept Purpose
[Link]() Output
[Link]() Output with new line
Scanner Input from user
[Link] Standard input
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
1. IF Statement
Syntax
64
if(condition) {
// code
}
Example
int age = 20;
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;
4. SWITCH Statement
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
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
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
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) {
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
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
Syntax of Class
class ClassName {
// variables
// methods
}
Example
class Student {
int id;
String name;
}
Explanation
Part Meaning
Student Class name
id, name Data members
77
2. Object
Example
Student s1 = new Student();
Explanation
Part Meaning
Student Class name
s1 Object name
new Allocates memory
int id;
String name;
}
class Demo {
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 → உண்றமயான சபாருள்
int id;
String name;
void display() {
[Link](id);
[Link](name);
}
}
class Demo {
[Link] = 101;
[Link] = "Arun";
[Link]();
}
}
Output
101
Arun
Multiple Objects
Example
class Student {
82
int id;
String name;
}
class Demo {
[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
Important Points
85
• ஒரு class மூலம் பல objects உருோக்கலாம் .
• new keyword object உருோக்க பயன் படும் .
Summary
Concept Meaning
Class Blueprint/template
Object Instance of class
new Creates object
Dot operator Access members
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
Syntax of Constructor
class ClassName {
ClassName() {
// constructor body
}
}
Example of Constructor
class Student {
Student() {
[Link]("Constructor Called");
}
Types of Constructors
89
90
6
Type Description
Default Constructor No parameters
Parameterized Constructor Accepts parameters
1. Default Constructor
Example
class Demo {
Demo() {
[Link]("Default Constructor");
}
91
}
}
Output
Default Constructor
2. Parameterized Constructor
Example
class Student {
int id;
String name;
Student(int i, String n) {
id = i;
name = n;
}
void display() {
[Link]();
}
}
Output
101 Arun
92
Parameters உடன் values pass செய் யும் constructor → parameterized
constructor.
Constructor Overloading
93
6
Example
class Demo {
Demo() {
[Link]("No Arguments");
}
Demo(int a) {
[Link](a);
}
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
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
int id;
String name;
Employee(int i, String n) {
id = i;
name = n;
97
}
void display() {
[Link]();
}
}
Output
1 Kumar
Summary Table
Concept Meaning
Constructor Initializes object
Default Constructor No parameters
Parameterized Constructor With parameters
Constructor Overloading Multiple constructors
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
Components of Encapsulation
Component Purpose
private variable Hide data
setter method Set value
getter method Get value
Example of Encapsulation
class Student {
class Demo {
[Link](101);
[Link]([Link]());
}
}
Output
101
Explanation of Program
1. Private Variable
private int id;
2. Setter Method
public void setId(int i)
3. Getter Method
public int getId()
102
Used to retrieve value from private variable.
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 {
Real-Life Example
106
107
7
name = n;
}
108
public String getName() {
return name;
}
[Link]("Kumar");
[Link]([Link]());
}
}
Output
Kumar
Flow of Encapsulation
Private Data
↓
Setter Method
↓
Getter Method
↓
User Access
Important Points
109
Summary Table
Concept Meaning
Encapsulation Wrapping data and methods
private Hides data
getter Retrieves value
setter Sets value
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 ஆகும் .
Syntax of Inheritance
class ChildClass extends ParentClass {
}
Explanation
Keyword Meaning
extends Used for inheritance
ParentClass Base class
ChildClass Derived class
112
class Animal {
void sound() {
void bark() {
[Link]("Dog barks");
}
}
class Demo {
[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
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 {
119
super keyword refers to parent class object.
Used for:
• calling parent constructor
• accessing parent methods
Example
class Animal {
void sound() {
[Link]("Animal sound");
}
}
void sound() {
[Link]();
[Link]("Dog barks");
}
}
Constructor in Inheritance
class Animal {
Animal() {
[Link]("Animal Constructor");
}
}
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
Important Points
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
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.
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
[Link](a + b);
}
[Link](a + b + c);
}
128
Add obj = new Add();
[Link](10, 20);
Explanation
Constructor Overloading
Example
class Demo {
Demo() {
[Link]("No Arguments");
}
Demo(int a) {
[Link](a);
}
}
129
2. Method Overriding
130
7
void sound() {
void sound() {
[Link]("Dog barks");
}
[Link]();
}
}
Output
Dog barks
Explanation
void sound() {
[Link]("Animal sound");
}
}
132
void sound() {
[Link]();
[Link]("Dog bark");
}
}
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.
Important Points
136
• Overloading → same method different parameters
• Overriding → child class method modification
void draw() {
[Link]("Drawing Shape");
}
}
void draw() {
[Link]("Drawing Circle");
}
[Link]();
}
}
Output
Drawing Circle
Summary Table
Concept Meaning
Polymorphism One name, many forms
Overloading Same method, different parameters
Overriding Child modifies parent method
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
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.
143
1. Abstract Class
144
7
Abstract Method
A method without body is called abstract method.
Syntax
abstract void methodName();
145
abstract void sound();
}
void sound() {
[Link]("Dog barks");
}
[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
2. Interface
146
147
6
Syntax of Interface
interface InterfaceName {
void methodName();
}
Example of Interface
interface Animal {
void sound();
}
148
public void sound() {
[Link]("Dog barks");
}
[Link]();
}
}
Output
Dog barks
Explanation
Part Meaning
interface Animal Interface declaration
implements Used to inherit interface
sound() Implemented method
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
void draw() {
151
[Link]("Drawing 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
Summary Table
Concept Meaning
Abstraction Hiding implementation
Abstract Class Partial abstraction
Interface Complete abstraction
abstract Abstract keyword
implements Interface inheritance
155
A class declared with abstract keyword is called abstract class.
Interface
An interface is used to achieve complete abstraction in Java.
156
157
6
Arrays and Strings are important concepts in Java used to store and manipulate
data.
1. Arrays in Java
ஒபர ேறக data-கறள ஒன் ைாக store செய் ய பயன் படும் structure
தான் array.
Declaration of Array
Syntax
datatype arrayName[];
or
datatype[] arrayName;
Creating Array
Syntax
arrayName = new datatype[size];
Example of Array
class Demo {
[Link](arr[0]);
[Link](arr[1]);
}
}
Output
10
20
Array Index
159
160
6
161
Traversing Array Using Loop
Example
class Demo {
[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 {
int arr[][] = {
{1, 2},
{3, 4}
};
[Link](arr[0][1]);
}
}
Output
2
2. Strings in Java
164
165
6
Declaration of String
String name = "Arun";
Example Program
class Demo {
[Link](name);
166
}
}
Output
Java
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
168
public static void main(String[] args) {
[Link]([Link]());
[Link]([Link]());
[Link]([Link](2));
}
}
Output
16
JAVA PROGRAMMING
v
String Comparison
Example
class Demo {
String s1 = "Java";
String s2 = "Java";
[Link]([Link](s2));
}
}
Output
true
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
[Link](name);
[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
174
175
6
Wrapper classes are used to convert primitive data types into objects.
A wrapper class is a class that wraps primitive data types into objects.
Java provides wrapper classes for all primitive data types.
177
178
6
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
int a = 10;
[Link](obj);
}
}
Output
10
Autoboxing
179
180
7
Example
class Demo {
int a = 100;
Integer obj = a;
[Link](obj);
}
}
Output
100
Unboxing
181
182
6
Example
class Demo {
int a = obj;
[Link](a);
}
}
Output
50
183
Wrapper object primitive value-ஆக மாறுேது unboxing.
184
7
Method Purpose
valueOf() Converts primitive to object
parseInt() Converts String to int
toString() Converts value to String
intValue() Converts object to int
String s = "200";
[Link](num);
185
}
}
Output
200
String s = [Link](num);
[Link](s);
}
}
Output
500
Real-Life Analogy
186
187
5
188
Advantage Description
Easy Parsing String conversions
Important Points
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
190
191
7
Exception handling is used to handle runtime errors and prevent abnormal program
termination.
What is an Exception?
Program run ஆகும் பபாது ஏை் படும் runtime error தான் exception.
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
// risky code
}
2. catch Block
Syntax
catch(ExceptionType e) {
// handling code
}
Example of try-catch
class Demo {
try {
int a = 10 / 0;
[Link](a);
}
catch(ArithmeticException e) {
3. finally Block
197
6
198
• closing files
• cleanup operations
Syntax
finally {
// cleanup code
}
Example of finally
class Demo {
try {
int a = 10 / 0;
}
catch(ArithmeticException e) {
[Link]("Exception handled");
}
finally {
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 {
else {
[Link]("Eligible");
}
}
}
Output
Exception in thread "main" [Link]: Not eligible
5. throws Keyword
Example
202
class Demo {
check();
}
}
Types of Exceptions
203
6
204
Type Description
Checked Exception Checked at compile time
Unchecked Exception Occurs at runtime
try {
arr[10] = 50;
}
catch(ArrayIndexOutOfBoundsException e) {
catch(Exception e) {
[Link]("General exception");
}
}
}
205
Output
Array index error
206
6
try
↓
Exception Occurs
207
↓
catch
↓
finally
Important Points
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
Creating a Package
package mypack;
Using a Package
import [Link];
Advantages of Packages
210
• Organizes classes
• Avoids naming conflicts
• Provides access protection
• Easier maintenance
1. Private
Accessible only within the same class.
class Demo {
private int x = 10;
void show() {
[Link](x);
}
}
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;
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.
int a = [Link](args[0]);
int b = [Link](args[1]);
int sum = a + b;
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
java Demo Hello
இங் பக:
• Hello என் பது command-line argument.
உதாரணம்
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
[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 {
[Link](i);
218
try {
[Link](1000);
}
catch(Exception e) {
[Link](e);
}
}
}
[Link]();
}
}
[Link]();
}
}
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 {
220
public class Test {
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.
முக்கிய Methods
221
Method பயன்
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.
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) {
[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) {
[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) {
[Link]("Java");
[Link]("Python");
[Link]("Java");
[Link](set);
}
}
Output
[Java, Python]
TreeSet Example
import [Link].*;
class Demo {
public static void main(String[] args) {
[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) {
[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) {
[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
227
Feature List Set Map
Key-Value Pair No No Yes
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<>();
நினனவில் ககாள் ள
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 {
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 {
[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 {
int ch;
[Link]();
}
}
Output
Welcome to Java
FileInputStream Example
import [Link].*;
class Demo {
public static void main(String[] args) throws Exception {
int i;
[Link]();
}
}
231
FileOutputStream Example
import [Link].*;
class Demo {
public static void main(String[] args) throws Exception {
FileOutputStream fout =
new FileOutputStream("[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
I/O Streams
Stream சவனல
File உருவாக்குதல்
File f = new File("[Link]");
File-ல் எழுதுதல்
FileWriter fw = new FileWriter("[Link]");
File-ல் படித்தல்
FileReader fr = new FileReader("[Link]");
BufferedReader
பேகமாக file read செய் ய உதவும் .
முக்கிய Methods
Method பயன்
234
Method பயன்
நினனவில் ககாள் ள
• 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
235
Type Description
Type 3 Network Protocol Driver
Type 4 Thin Driver (Most Used)
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]();
class Demo {
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 {
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);
}
}
}
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
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 பயன்
நினனவில் ககாள் ள
• 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
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
class Server {
Socket s = [Link]();
[Link]("Client connected");
DataInputStream dis =
new DataInputStream([Link]());
[Link]();
}
}
class Client {
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 {
[Link]([Link]());
[Link]([Link]());
}
}
InetAddress Class
Used to get IP address information.
import [Link].*;
class Demo {
InetAddress ip =
[Link]("localhost");
[Link](ip);
}
}
245
Class Purpose
Socket Client-side connection
ServerSocket Server-side connection
URL Represents web address
InetAddress IP address handling
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
248
Simple Servlet Example
import [Link].*;
import [Link].*;
import [Link].*;
[Link]("text/html");
[Link]("<h1>Hello Servlet</h1>");
}
}
<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
250
Servlet
↓
JSP
↓
Browser Response
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
JSP Tags
Tag பயன்
<% %> Java code
<%= %> Output print
<%! %> Variable declaration
252
Servlet JSP
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
}
254
public void doGet(
HttpServletRequest req,
HttpServletResponse res
) throws IOException {
[Link]("text/html");
[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>
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
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
257
Method பயன்
JSP Tags
Tag சவனல
<% %> Java code
<%= %> Output expression
Servlet vs JSP
Servlet JSP
Logic handling UI handling
நினனவில் ககாள் ள
• Servlet → Controller logic
• JSP → Presentation layer
• doGet() மை் றும் doPost() முக்கிய methods
• JSP web page உருோக்க எளிதானது
258
REST stands for:
• Representational
• State
• Transfer
@SpringBootApplication
public class DemoApplication {
[Link](
[Link],
args
);
}
}
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
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
@RestController
public class StudentController {
@GetMapping("/student")
public Student getStudent() {
261
Student Class
class Student {
int id;
String name;
[Link] = id;
[Link] = name;
}
JSON Output
{
"id": 101,
"name": "Arun"
}
return a + b;
}
[Link]
[Link]=8081
Changes default port number.
[Link]=root
[Link]=password
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
@GetMapping("/user")
public String user() {
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
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 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
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
நினனவில் ககாள் ள
• Microservice = Small independent service
• REST API மூலம் services communicate செய் யும்
• ஒே் சோரு service-க்கும் தனி database இருக்கலாம்
• Cloud applications-ல் அதிகமாக பயன் படுத்தப்படுகிைது
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) {
[Link]();
}
}
class Test {
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();
}
class Test {
[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 {
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 {
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 {
List<String> names =
[Link]("Java", "Python");
[Link]([Link]::println);
}
}
Optional Class
Avoids NullPointerException.
Optional<String> name =
[Link]("Java");
class Demo {
276
public static void main(String[] args) {
LocalDate d = [Link]();
[Link](d);
}
}
Lambda Expression
சிறிய anonymous function.
Syntax
() -> {}
277
Example
(a,b) -> a+b
Streams API
Collection data-ஐ process செய் ய பயன் படும் .
முக்கிய Methods
Method சவனல
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
279
Component Purpose
JLabel Text label
JTextField Text input
JPasswordField Password input
JCheckBox Checkbox
JRadioButton Radio button
JFrame Example
import [Link].*;
class Demo {
[Link](400, 300);
[Link](true);
}
}
JButton Example
import [Link].*;
class Demo {
[Link](b);
280
[Link](300, 300);
[Link](null);
[Link](true);
}
}
class Demo {
[Link](l);
[Link](t);
[Link](300, 200);
[Link](null);
[Link](true);
}
}
ActionListener Example
import [Link].*;
import [Link].*;
class Demo {
[Link](new ActionListener() {
[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
[Link]().add(b);
283
Scene scene =
new Scene(root, 300, 200);
[Link]("JavaFX");
[Link](scene);
[Link]();
}
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
Swing
[Link] package பயன் படுத்தி GUI application
உருோக்கப்படுகிைது.
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
நினனவில் ககாள் ள
• Swing → Traditional GUI
• JavaFX → Modern GUI
• JFrame முக்கிய window component
• Event handling GUI-ல் முக்கியமானது
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
JFrame Example
import [Link].*;
class Demo {
[Link](400, 300);
[Link](true);
}
}
287
JButton Example
import [Link].*;
class Demo {
[Link](b);
[Link](300, 300);
[Link](null);
[Link](true);
}
}
class Demo {
[Link](l);
[Link](t);
288
[Link](300, 200);
[Link](null);
[Link](true);
}
}
ActionListener Example
import [Link].*;
import [Link].*;
class Demo {
[Link](new ActionListener() {
[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
290
import [Link];
import [Link];
import [Link];
[Link]().add(b);
Scene scene =
new Scene(root, 300, 200);
[Link]("JavaFX");
[Link](scene);
[Link]();
}
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
Swing
[Link] package பயன் படுத்தி GUI application
உருோக்கப்படுகிைது.
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
நினனவில் ககாள் ள
• Swing → Traditional GUI
• JavaFX → Modern GUI
• JFrame முக்கிய window component
• Event handling GUI-ல் முக்கியமானது
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
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
294
return a + b;
}
}
class CalculatorTest {
@Test
void testAdd() {
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;
assertFalse() Example
@Test
void testCheck() {
int a = 5;
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;
}
);
}
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
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
முக்கிய Annotations
Annotation பயன்
@Test Test method
298
Example
@Test
void testAdd()
Assertion Methods
Method சவனல
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
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
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>
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.
group = '[Link]'
302
version = '1.0'
Dependency Example
dependencies {
testImplementation
'[Link]:junit-jupiter:5.10.0'
}
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
<groupId>[Link]</groupId>
<artifactId>
spring-boot-starter-web
</artifactId>
</dependency>
Maven
XML-based build tool.
முக்கிய file:
[Link]
Maven Commands
Command சவனல
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 பேகத்றத அதிகரிக்கும்
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
Git Installation
Official website:
Git Official Website
Configure Git
git config --global [Link] "YourName"
Check Status
git status
Shows file changes.
Add Files
git add [Link]
Add all files:
git add .
Commit Changes
git commit -m "First commit"
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]
Push Changes
git push origin main
Pull Changes
git pull origin main
Git Workflow
Edit Files
↓
git add
↓
git commit
↓
git push
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
Command சவனல
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 செய் யும்
312