Java Full Stack
Java Full Stack
Stack
Day-1
What is Java Full Stack?
Java Full Stack refers to a developer who can work on
both the front-end (client side) and back-end (server
side) of a web application using Java and related
technologies.
Java Full Stack Development is the practice of building
both the front-end and back-end of a web application
using Java-based technologies for the back-end.
Front-End:
Front-end is the part of a website or web
application that users see and interact with
directly. It’s also called the client-side.
Backend:
The Back-End (also called server-side) is the part of
a web application that works behind the scenes —
it handles business logic, processes user requests,
interacts with the database, and sends data to the
front-end.
Website vs Web Application
(WebApp)
Website:
A website is a collection of static or less dynamic pages
that present content to users. It's mainly informational.
Mostly read-only content
Less user interaction
Examples: blogs, company info sites
Client-Server Architecture
So, we are learning Java Full Stack to become
capable of creating real-world web applications.
But have you ever wondered — how exactly are
web applications developed in IT companies?
What happens behind the scenes when you open a
webapp or click a button on an app?
To understand that, we need to look at the Client-
Server Architecture, which forms the backbone of
how modern web applications work.
Let’s dive into the big picture and see how front-
end, back-end, and databases communicate in a
real project setup.
What is an Enterprise Application?
An Enterprise Application is a large-scale software
system designed to operate in a business or corporate
environment.
In Simple Words:
An Enterprise Application is a big, business-focused
software that helps organizations manage their
daily operations in a digital and efficient way.
If a web application or any type of application is
designed to solve business problems, support large-
scale usage, and operate securely and reliably — it
is considered an enterprise application. Example:
IRCTC
Real-World Analogy:
Think of a restaurant:
Client = The customer (who places an order)
Server = The kitchen (prepares the food)
Waiter/API = Takes order to kitchen, brings back
response
Technology Mapping: FE | BE
| BE-DB
Technology / Module Used For Category
HTML, CSS, Creating structure, design,
🟢 FE
JavaScript and basic interactivity
Styling and responsive
Bootstrap 🟢 FE
design
Building dynamic,
React 🟢 FE
component-based UIs
Core programming and logic
Core Java 🔵 BE
building
Exception Handling, Logic, data handling, error
🔵 BE
OOPs, Collections management
Input/output, threads,
File I/O, Networking,
streams, functional 🔵 BE
Java 8 Features
programming
JDBC (Java Database Connecting Java app with 🟡 BE-
Connectivity) relational databases DB
Dynamic server-side web
Servlets & JSP 🔵 BE
pages & request handling
ORM – Mapping Java 🟡 BE-
Hibernate
objects to database tables DB
Dependency Injection,
Spring Core 🔵 BE
Inversion of Control
Easier database access using 🟡 BE-
Spring JDBC
Spring framework DB
Web layer – handling HTTP
Spring MVC 🔵 BE
requests/responses
Technology / Module Used For Category
Rapid backend and
Spring Boot microservice app 🔵 BE
development
Creating RESTful APIs (used
Spring REST API 🔵 BE
by frontend)
Authentication,
Spring Security 🔵 BE
Authorization, JWT, OAuth
Breaking app into loosely
Microservices 🔵 BE
coupled services
AI features integration within
Spring AI 🔵 BE
Java backend
Writing queries, managing 🟡 BE-
SQL, MySQL, Oracle
relational data DB
Frontend (Client-side):
HTML, CSS, JS, Bootstrap, React – used to design
and build the user interface.
Backend (Server-side):
Core Java, Servlets, JSP, Spring, Spring Boot,
Spring Security – used to handle logic, security,
APIs.
Backend + Database:
JDBC, Hibernate, Spring JDBC, SQL, MySQL,
Oracle – used to connect and manage data in
databases.
Enterprise App:
A large-scale software like IRCTC that solves
business problems.
Client-Server Architecture:
Client sends request → Server processes → DB
gives data → Response goes back.
Live Diagram:
Day-2
Q1: What is a programming
language?
A programming language is a way for humans to
communicate instructions to a computer. It allows us to
write programs that tell the computer what to do.
Day-3
1. Platform Dependent vs
Platform Independent
Platform Dependent:
Software or code that only works on a specific
operating system. If you try to run it on a different
platform/os, it may not work or require
modifications.
Platform Independent:
Software or code(compiled) that can run on any
operating system without modification.
Example:
A Windows .exe program written in C++ compiled
specifically for Windows. You cannot run it on Linux
or macOS without recompiling.
Java bytecode compiled from .java files runs on any
OS.
2. Machine Dependent vs
Machine Independent
Machine Dependent:
Code or instructions (compiled) that are tied to
specific machine architecture (CPU type).
Machine Independent:
Code or instructions (compiled) that are not tied to
any specific CPU architecture and can be translated
or executed on multiple types of CPUs.
Example:
Assembly language written for x86 architecture will
only work on x86 processors.
Java bytecode is machine independent.
3. Portable vs Non-Portable
Portable:
Source code that can be easily moved and run on
different environments with no change.
Non-Portable:
Source code that cannot be easily moved to
different environments without significant changes.
Example:
Assembly code written for x86 Linux won’t run on
ARM processors or Windows without major
modifications.
Java programs are portable.
INSTALLATION
Download Java:
[Link]
[Link]
TO CHECK INSTALLATION:
OPEN CMD AND HIT java –version
Day-4
So far, we have covered the basics and successfully
installed Java. Now, let's create our very first Java
program!
We'll start with a simple approach using Notepad to
write the code and Command Prompt (CMD) to
compile and run it. This helps us understand the
internal execution steps more clearly.
Let's Begin:
1. Open Notepad and write your Java code.
2. Save the file with a .java extension, e.g.,
[Link].
3. Open Command Prompt and navigate to the
folder where the file is saved.
4. Compile the program using:
javac [Link]
This will generate a
[Link] file
(bytecode).
5. Run the program using:
java HelloWorld
You should see the output
on your screen!
✅ How to Create Your First
Java Program in Eclipse
Prerequisites:
Java JDK should be installed.
Eclipse IDE should be installed and opened.
Step-by-Step Process:
1. Open Eclipse IDE
Launch Eclipse.
Select a workspace directory (this is where all
your projects will be saved).
Day-5
History of Java
Why Java was created?
In the early 1990’s sun microsystem saw a growing need
for a platform independent, simple and secured
programming language
• 1969: US MILITERAY (ARPANET)
• 1989: WWW(WORLD WIDE WEB) was invented by
TIM BERNERS LEE
• 1990: FIRST WEB BROWSER, FIRST WEB SERVER,
WEB PAGE
Origin:
In 1991, Sun Microsystems did market research to
develop software for set-top boxes.
This led to the creation of the Green Project.
Timeline:
Project initiation: 1991
Alpha and Beta versions released: 1995
First official version (Java 1.0): 1996
Recognition:
Listed in Time Magazine’s Top 10 Projects of 1995
Featured in the book: "1000 Inventions That
Changed the World" (Java was one of them)
According to Oracle: "3 Billion devices run Java"
NOTE:
Java (then called Oak) was created for embedded
systems—specifically set-top boxes, which are small
hardware devices used for digital TV.
Why “Oak”?
James Gosling named it after an oak tree that stood
outside his office window at Sun Microsystems.
The name was meant to represent strength and
stability.
Day-6
Architecture of Java
The architecture of Java refers to the fundamental
components and structure that make the Java
programming language work.
4. Secure Language
Java runs inside a sandbox provided by the
JVM.
No direct memory access (no pointers).
Bytecode verification prevents malicious code
from executing.
5. High Performance
Java is faster than traditional interpreted
languages due to:
JIT (Just-In-Time) compiler
Efficient memory management
Not as fast as C/C++ but offers a good balance
between speed and safety.
7. Architecturally Neutral
Java programs behave consistently across
different hardware and OS.
In Java, the size of data types is fixed, unlike
C/C++.
8. Multithreaded
Java supports multithreading, which allows the
execution of multiple threads (tasks) at the
same time.
Useful for concurrent programming and better
CPU utilization.
9. Distributed Language
Java can build client-server applications and
communicate over networks.
FIRST PROGRAM:
Understanding Java
Program Structure: An
English Language
Analogy
Alphabets, digits, and symbols:
Just like English uses alphabets (A–Z, a–z), Java
uses alphabets, digits (0–9), and special
symbols (+, -, *, =, etc.) as its basic characters.
Forming elements:
These characters combine to create
meaningful elements in Java, such as variables,
constants/literals, keywords, and identifiers —
similar to how letters form words in English.
Writing statements:
These elements are then used to write
statements, which are individual instructions
in Java, like sentences in English.
Building a program:
Multiple statements are combined logically
and structurally to form a complete Java
program, just like sentences combine to make
paragraphs.
int a=100;
int b=200;
int c=a+b;
[Link](c);
}
}
======================================
======================================
=======================
Day-8
Java Identifier
It is a name given to a variable, methods, classes,
packages…etc. in a java program. It serves as a
reference for programmer to interact with them
CONVENTIONS
• These are recommendations or best practices aim
to improve code readability, maintainability and
consistency
• Conventions are not enforced by compiler but
following them makes the code easier to understand
[Link] CASE:
• All letters are in lower case but words are
separated by hyphens ( - )
• Ex. this-is-my-car
[Link] CASE:
• The First letter of each word is capitalized but
words are separated by hyphens (-)
• Ex. This-Is-My-car
[Link] CASE:
• All letters are in lower case with no separator
between words
• Ex. thisismycar
• IN JAVA: keywords (ONLY ALPHABETS)
Java Data
Types
IMPORTANCE OF DATA TYPE
Here’s a real-world incident that highlights how
critical correct data type usage is in software
development:
[Link]
orbiter/
In 1999, NASA's Mars Climate Orbiter spacecraft was lost forever
because of a data type mismatch.
One part of the software (developed by a contractor) was using
imperial units (pounds-seconds), while NASA's system expected
metric units (newton-seconds).
This happened because the data type or unit wasn't properly
defined or checked between the systems.
As a result, the spacecraft went off course, entered Mars'
atmosphere at the wrong angle, and burned up or was lost in
space.
Impact: A $327.6 million loss — all due to a simple data
unit/type error.
This incident shows that choosing the correct data types and
ensuring consistency is not just a technical detail — it can cause
mission failures and massive losses if ignored.
Let’s Start:
Java is a statically typed programming language,
which means every variable and expression type is
already known at compile time. Java data types are
divided into two categories:
1. Primitive Data Types
2. Non-Primitive Data Types (like Strings, Arrays,
Classes, etc.)
In this Session, we will focus on Primitive Data
Types.
c) int
Size: 4 bytes (32 bits)
Range: -2,147,483,648 to 2,147,483,647
Description: Default data type for integral values
unless there is a concern about memory.
Example: int salary = 500000;
d) long
Size: 8 bytes (64 bits)
Range: -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Description: Used when a wider range than int is
needed. Must end with L or l.
Example: long population = 9000000000L;
b) boolean
Size: ~1 bit (not precisely defined by Java)
Values: true or false
Description: Represents one bit of information.
Only two possible values.
Example: boolean isJavaFun = true;
NOTE:
In Java, each data type (Integer) has a fixed size in bits.
For example, byte has 8 bits, int has 32 bits. Because of
this fixed size, you can store only a limited range of
values. If the value goes beyond what can be stored in
those bits, it won’t fit — that’s why every data type
(Integer) has a fixed range.
==========================Program:
Variable Declaration &
Initialization========================
===
package [Link];
public class Launch {
byte v1=122;
short v2=32000;
int v3=799999999;
long v4=34543875L; //L or l
// float test1=22.0f/7.0f;
// [Link](test1);
//
// double test2=22.0/7.0;
// [Link](test2);
}
}
======================================
======================================
=======================
Day-9
How to Take User Input in
Java?
In Java, we can provide values to variables in two ways:
Programmer Input – Hardcoded values written
directly in the code.
User Input – Values entered by the user at runtime
using input methods like Scanner.
Programmer Input
This is when the programmer sets the value of a
variable manually in the source code. For example:
int a = 100; // Programmer input
Explanation:
The value 100 is fixed and written directly by
the programmer.
It does not change unless the code is
modified.
This approach is useful for testing or default
values but not suitable for interactive
programs.
Explanation:
Scanner sc = new Scanner([Link]); → Creates a
scanner that reads input from the keyboard.
[Link](); → Reads an integer value entered by
the user.
This allows the program to take dynamic input at
runtime.
Scanner Methods for Primitive
Types:
Data Type Scanner Method Example
byte [Link]() byte b =
[Link]();
short [Link]() short s =
[Link]();
int [Link]() int a =
[Link]();
long [Link]() long l =
[Link]();
float [Link]() float f =
[Link]();
double [Link]() double d =
[Link]();
boolean [Link]() boolean
flag = [Link]();
char Not directly supported char ch =
[Link]().charAt(0);
Java Control
Statement
In Java, control statements are used to control
the flow of execution in a program based on
certain conditions or repetitions. These
statements help you make decisions, repeat
tasks, or jump to specific parts of the code.
1. Decision Making/Selection
CFS (Control Flow Statements)
Used to execute certain blocks of code based
on conditions.
[Link] statement
Simple if statement : The if statement is the most basic
form of decision-making control structure in Java. It is
used to execute a block of code only when a given
condition is true
if(condition) {
// code
}
=========================Program:
User input and if
statement==========================
=====
package [Link];
import [Link];
public class Launch {
[Link]();
}
}
package [Link];
import [Link];
public class Launch2 {
if(age>=18) {
[Link]("ELIGIBLE");
}
else {
[Link]("NOT ELIGIBLE");
}
[Link]("EXIT");
[Link]();
}
}
package [Link];
import [Link];
public class Launch3 {
if(per>=60) {
if(age>=18) {
if(cc==91) {
[Link]("ELIGIBLE");
}
else
{
[Link]("NOT ELIGIBLE: CC");
}
}
else
{
[Link]("NOT ELIGIBLE: AGE");
}
}
else {
[Link]("NOT ELIGIBLE: PER");
}
[Link]("EXIT");
[Link]();
}
}
package [Link];
import [Link];
public class Launch4 {
// if(pincode==1111) {
// [Link]("bhopal");
// }
// else {
// if(pincode==1112) {
// [Link]("pune");
// }
// else {
// if(pincode==1113) {
// [Link]("mumbai");
// }
// else
// {
// [Link]("not found");
// }
// }
// }
if(pincode==1111) {
[Link]("bhopal");
}
else if(pincode==1112) {
[Link]("pune");
}
else if(pincode==1113) {
[Link]("mumbai");
}
else{
[Link]("not found");
}
[Link]("EXIT");
[Link]();
}
}
package [Link];
public class Launch5 {
int age=80;
if(age>=18)
; //EMPTY STATEMENT
{
[Link]("ELIGIBLE"); //outside
}
[Link]("EXIT"); //outside
}
}
===================================
===================================
============
Day-10
Logical Operators in Java
Logical operators are used to combine or modify
conditional expressions (boolean values).
Operator Symbol
Meaning Example
Result
AND && True if both
conditions are true (a > 5 && b < 10)
true if both are true
OR || True if any one
condition is true (a > 5 || b < 10)
true if at least one is true
NOT ! Reverses
the boolean value !(a > 5)
true if condition is false
Note:
&& and || are short-circuit operators – if the result can
be determined from the first condition, Java does not
check the second condition.
Switch Statement in Java
A switch statement is used to make decisions/menu
among multiple options, often replacing multiple if-else-
if statements.
Key Points:
Purpose: Select and execute one block of code from
multiple choices.
Better Performance:
If cases are contiguous (1, 2, 3…), compiler uses a
Jump Table → faster execution.
If cases are non-contiguous, compiler uses a
Lookup Table → still faster than if-else-if.
Case Values: Must be unique and constant (no
variables allowed).
Fall-through Behavior: If you don’t use break,
execution continues into the next case.
Data Types Allowed:
Primitive: byte, short, int, char
Non-Primitive: String, enum, Wrapper classes
(Byte, Short, Integer, Character)
Nested Switch: Switch inside another switch is
possible but should be used carefully for
readability.
Syntax Example:
int choice = 2;
switch (choice) {
case 1:
[Link]("Option 1");
break;
case 2:
[Link]("Option 2");
break;
default:
[Link]("Invalid choice");
}
============================Program
: Logical
Operator===========================
===
package [Link];
import [Link];
public class Launch {
[Link]();
}
}
package [Link];
import [Link];
public class Launch2 {
[Link]();
}
}
package [Link];
import [Link];
public class Launch3 {
[Link]();
}
}
===================================
===================================
===========
============================Program
: Switch
Statement==========================
==
package [Link];
import [Link];
public class Launch {
/*
* num1=10 num2=20 choice=1,2,3,4 choice==1 : add
choice==2 : sub choice==3 :
* div choice==4 : mul
*/
[Link]("ENTER NUM2:");
int num2 = [Link]();
[Link]("ENTER CHOICE:");
int choice = [Link](); // 4
if (choice == 1) {
[Link](num1 + num2);
} else if (choice == 2) {
[Link](num1 - num2);
} else if (choice == 3) {
[Link](num1 / num2);
} else if (choice == 4) {
[Link](num1 * num2);
} else {
[Link]("Wrong choice");
}
}
[Link]();
}
}
package [Link];
import [Link];
public class Launch2 {
/*
* num1=10 num2=20 choice=1,2,3,4 choice==1 : add
choice==2 : sub choice==3 :
* div choice==4 : mul
*/
[Link]("ENTER NUM1:");
int num1 = [Link]();
[Link]("ENTER NUM2:");
int num2 = [Link]();
[Link]("ENTER CHOICE:");
int choice = [Link](); // 4
[Link]("EXIT");
[Link]();
}
}
===================================
===================================
===========
Day-11
Loop Control Flow Statements
in Java
Loop control flow statements are used to execute a
block of code repeatedly based on a condition. They
help in performing repetitive tasks without writing the
same code multiple times.
How it works:
Initialization → executed once at the beginning.
Condition → checked before each iteration. If true,
loop continues; if false, loop ends.
Update → executed after each iteration.
Example:
for(int i = 1; i <= 5; i++) {
[Link]("Value of i: " +
i);
}
1.2 while loop
Purpose: Executes a block of code while the condition is
true.
Syntax:
while(condition) {
// code to execute
}
Example:
int i = 1;
while(i <= 5) {
[Link]("Value of i: " +
i);
i++;
}
Example:
int i = 1;
do {
[Link]("Value of i: " +
i);
i++;
} while(i <= 5);
Example:
int[] numbers = {1, 2, 3, 4, 5};
for(int num : numbers) {
[Link](num);
}
Output:
1
2
4
5
============================Program
: Loop Statement & Jump
Statement==========================
==
package [Link];
public class Launch {
// int i;
// for(i=1 ; i<=5 ; i++) {
// [Link]("HELLO");
// }
// int i=1;
// for( ; i<=5 ; ) {
// [Link]("HELLO");
// i++;
// }
// int i=1;
// for( i=2 ; i<=5 ; i++ ) {
// [Link]("HELLO");
// i++;
// }
// int i=1;
// for( i=2 ; i<=5 ; ) {
// [Link]("HELLO");
// i=i+2;
// }
// int i=1;
// for( i=2 ; i<=5 ; i=i+2 ) {
// [Link]("HELLO");
// }
// int count=0;
// for(int i=1 ; i<=5 ; i++) {
//
// for(int j=1 ; j<=5 ; j++) {
//
// [Link]("Hello");
// count++;
//
// }
// }
// [Link](count);
// int count=0;
// for(int i=1 ; i<=5 ; i++) {
//
// for(int j=1 ; j<=5 ; j++) {
//
// [Link]("Hello");
// count++;
//
// }
// }
// [Link](count);
// int count=0;
// for (int i = 1; i <= 10; i++) {
// if(i==5) {
// break;
// }
// count++;
// [Link]("HELLO");
// }
// [Link](count);
// int a=10;
// if(a<100){
// [Link]("hello");
// break; //CTE
// [Link]("hiiii");
// }
//Labelled for loop
// Loop1:
// for(int i=1 ; i<=5 ; i++) { //5 times
//
// Loop2:
// for(int j=1 ; j<=5 ; j++) {
//
// if(j==3) {
// break Loop1;
// }
// [Link]("Hello");
//
// }
// }
}
}
package [Link];
public class Launch2 {
// int a=100;
// while(a<=10) {
// [Link]("hello");
// a++;
// }
// int a=100;
// do{
// [Link]("hello");
// a++;
// }
// while(a<=10);
// int a=1;
// while(a<=10) {
// [Link]("hello");
// a++;
// }
int a=1;
do{
[Link]("hello");
a++; //2
}
while(a<=10);
//1Free (2 3 4 5 6 7 8 9 10)checking
}
}
===================================
===================================
==========================
Practice Program:
Question1:
Write a Java program that takes a number as input from
the user and prints whether the number is positive,
negative, or zero.
Test Cases:
Input: 35 → Output: Number is positive
Input: -12 → Output: Number is negative
Input: 0 → Output: Number is zero
Question2:
Write a Java program that accepts three numbers from
the user and determines which one is the greatest.
Test Data:
Input the 1st number: 25
Input the 2nd number: 78
Input the 3rd number: 87
Expected Output:
The greatest number is: 87
Question3:
Write a Java program that takes a number between 1
and 7 from the user and displays the corresponding
weekday name.
Test Data:
Input number: 3
Expected Output:
Wednesday
Question4:
Write a Java program that takes a month number (1 to
12) and a year as input, and displays the name of the
month along with the number of days it has for that
year.
Test Data:
Input a month number: 2
Input a year: 2016
Expected Output:
February 2016 has 29 days
Question5:
Write a Java program that takes a positive integer n
from the user, displays the first n natural numbers, and
calculates their sum.
Test Data:
Input the number: 2
Expected Output:
Input number:
2
The first n natural numbers are:
1
2
The Sum of Natural Numbers up to n terms: 3
Question6:
Write a Java program that takes a positive integer n
from the user, displays the first n natural numbers in
the form of an addition expression, and calculates their
sum.
Test Data:
Input the number: 2
Expected Output:
1+2=3
Question7:
Write a Java program to display the pattern like a
diamond.
Test Data
Input number of rows (half of the diamond) : 7
Expected Output :
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
Day-12
Operators in Java
What are Operators?
Operators are special symbols in Java used to
perform operations on variables and values.
They act on operands and produce a result.
Example:
int a = 10, b = 5;
int sum = a + b; // '+' is operator,
'a' and 'b' are operands
[Link] Operators:
Work with a single operand.
+ Unary plus (no effect) +a
- Negation (changes sign) -a
++ Increment (add 1) ++a (pre), a++
(post)
-- Decrement (subtract 1) --a, a--
! Logical NOT !(a > b)
[Link] Operators:
Used to assign values.
= Assign a = 10
+= Add & assign a += 5 → a = a + 5
-= Subtract & assign a -= 5
*= Multiply & assign a *= 5
/= Divide & assign a /= 5
%= Modulus & assign a %= 5
[Link] Operators
Used for combining boolean conditions.
&& (AND)
|| (OR)
! (NOT)
[Link] Operator
Checks if an object is an instance of a specific class.
String s = "Hello";
[Link](s instanceof
String); // true
[Link] Operators
Bitwise operators in Java are special operators that
perform operations directly on the individual bits
(0s and 1s) of numbers instead of working on whole
numbers.
Useful for low-level programming, performance
optimization, and working with binary data.
Bitwise AND (&)
Rule: 1 & 1 = 1, otherwise 0.
Bitwise OR (|)
Rule: 0 | 0 = 0, otherwise 1.
Bitwise XOR (^)
Rule: 1 ^ 1 = 0, 0 ^ 0 = 0, but 1 ^ 0 = 1.
Bitwise NOT (~)
Inverts every bit.
Left Shift (<<)
Shifts bits to the left, fills 0 on right.
Right Shift (>>)
If the number is positive → left side filled with 0.
If the number is negative → left side filled with 1
(because it keeps the sign bit).
So, it does NOT always add zero — it depends on
the sign of the number.
Unsigned Right Shift (>>>)
Shifts bits to the right, fills with 0 from left (ignores
sign).
===================================
===Program:
Operators==========================
==============
package [Link];
public class Launch {
//Post Increment
// int a = 10;
// [Link](a++); // print then increment
// [Link](a);
//Pre Increment
// int a = 10;
// [Link](++a); // increment then print
// [Link](a);
//Post Decrement
// int a = 10;
// [Link](a--); // print then decrement
// [Link](a);
//Pre Decrement
// int a = 10;
// [Link](--a); // decrement then print
// [Link](a);
// int a=10;
// int b = a++;
// [Link](a);//11 ,
// b=++a;
// [Link](a);
// b=a--;
// [Link](a);
// b=--a;
// [Link](a);
//int a=10;
// int a=10;
// //a=a+5;
// a+=5;
// [Link](a);
// int a=-4;
// int b=a>>>1;
// [Link](b);
}
}
===================================
===================================
==========================
Day-13
Methods in Java
A method in Java is a block of code within a class
that performs a specific task, is executed when it is
called, and can optionally accept input parameters
and return a value.
It is used to achieve code reusability, modularity,
readability, and maintainability. Methods allow
programmers to organize logic into smaller,
reusable units instead of writing the same code
multiple times.
Types of method
[Link]/BuiltIN/Inbuilt Methods
(Library Methods)
Already defined in Java API classes.
Example: nextInt()
[Link]-defined Methods
Created by programmers to perform custom tasks.
Example:
void greet() {
[Link]("Welcome to Java!");
}
===================================
===Program:
Methods============================
============
===================================
===================================
========================
Day-14
Recursion
Recursion in Java (or in any programming language)
is a technique in which a method calls itself either
directly or indirectly to solve a problem.
It is often used when a problem can be broken
down into smaller, similar subproblems.
A recursive method usually has two parts:
Recursive Case:
The part where the method calls itself with a
smaller or simpler input.
public class RecursionExample {
// Recursive method to calculate
factorial
public static int factorial(int n)
{
if (n == 0 || n == 1) { // Base
case
return 1;
}
return n * factorial(n - 1); //
Recursive case
}
public static void main(String[]
args) {
int result = factorial(5);
[Link]("Factorial
of 5 is: " + result);
}
}
2. Unicode
Universal standard → Supports all world languages
+ symbols + emojis.
Java uses UTF-16 encoding (16-bit).
Unicode covers ASCII as a subset.
Unicode range is much larger than ASCII.
UNICODE CHART:
[Link]
✅ Examples of Widening
byte → short → int → long → float → double
char → int → long → float → double
Note:
boolean cannot be type casted (not numeric).
2. Narrowing (Explicit) Type Casting
Converting a larger data type into a smaller data
type.
Must be done manually using (type) → compiler
does not do it automatically.
Risk of data loss (values may be truncated or
overflow).
✅ Examples of Narrowing
double → float → long → int → short → byte
double → float → long → int → char
Note:
boolean cannot be type casted (not numeric).
OOP Concepts
Class → A blueprint/template for creating objects.
Object → An instance of a class representing a real-
world entity.
Encapsulation → Binding data and methods into a
single unit (class) and restricting direct access.
Inheritance → Mechanism to acquire properties
and behaviors from another class (code reusability).
Polymorphism → One name, many forms (method
overloading & overriding).
Abstraction → Hiding implementation details and
showing only essential features.
OOP vs OOPs
OOP = Object-Oriented Programming
Refers to the programming paradigm itself.
Object-Oriented Programming
Language (OOPL)
A language that supports all OOP concepts (Class,
Object, Encapsulation, Inheritance, Polymorphism,
Abstraction) along with primitive data types (like int,
char, boolean).
Example: Java, C++
Java has primitive data types (int, char, etc.) along
with full OOP features.
C++ also has primitives and full OOP support.
These are considered OOP languages but not purely
OOP because they still allow primitives (not
everything is an object).
Object-Based Programming
Language (OBPL)
A language that supports only some OOP features —
like Object, Class, and Encapsulation — but does NOT
support Inheritance and Polymorphism.
Example:
VBScript
JavaScript (before ES6/ECMA-6)
Early JavaScript supported objects but had no
proper class, inheritance, or polymorphism
features.
These languages are object-based, but not fully
OOP because they lack the complete set of OOP
principles.
Pure Object-Oriented
Programming Language
A language where everything is treated as an object
(including primitive data types).
No primitive types outside object model.
Example:
Smalltalk → Considered the first pure OOP
language.
Ruby (close to pure — everything including
numbers and booleans are objects).
Note:
Java and C++ are not pure OOP because they allow
primitive types like int without making them
objects.
In Java, primitives can be wrapped in wrapper
classes (Integer, Double), but that’s extra — so it’s
not “pure.”
Benefits of OOPs
Object-Oriented Programming provides several
advantages over traditional Procedural Programming:
1. Reusability (Code Reuse)
Classes and objects can be reused across projects.
Inheritance allows reusing existing code instead of
rewriting.
Example: Vehicle class reused by Car, Bike, Truck.
2. Modularity (Organized Code)
Code is divided into small, independent
classes/objects.
Each object represents a real-world entity.
Easier to understand, maintain, and debug.
3. Maintainability & Extensibility
Easy to maintain and update code.
New features can be added by extending classes
(inheritance) without modifying existing code.
4. Data Security (Encapsulation)
Data is hidden inside classes using access modifiers
(private, protected).
Provides controlled access through getters/setters.
Protects from accidental misuse.
5. Flexibility (Polymorphism)
One interface, many implementations.
Same method name can perform different tasks.
Example: draw() method works differently for
Circle, Rectangle, Triangle.
6. Abstraction (Reduced Complexity)
Hides implementation details and shows only
essential features.
Example: [Link]() → user doesn’t need to know
how the engine works internally.
7. Real-world Modeling
OOP directly maps to real-world entities (Student,
Account, Car).
Makes problem-solving more natural and intuitive.
8. Scalability
Large software projects can be developed, tested,
and maintained easily.
Supports team-based development since each
module/class can be worked on independently.
Object
An object is a real-time instance (existence) of a
class inside memory (RAM).
Objects are created from classes using the new
keyword.
When an object is created, memory is allocated in
RAM to hold its data members.
An object represents real-world entities (e.g.,
Student, Car, Account).
Class = Blueprint | Object = Physical existence of
that blueprint
Example in Java:
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); //
creating object
[Link] = 1;
[Link] = "Raju";
[Link](); // Output: Raju is
studying
}
}
Characteristics of an Object
Every object has three characteristics (CAR example):
Day-16
What is a "Pillar" in OOP?
The word pillar literally means a strong support
column that holds a building.
Without pillars, the building would fall down.
In Object-Oriented Programming (OOP), the pillars
are the fundamental principles or core concepts
that support the entire programming model.
So when we say:
“Four Pillars of OOP” → Encapsulation,
Abstraction, Inheritance, Polymorphism
…it means these are the four main supports
that hold the concept of OOP together.
Encapsulation in Java
Encapsulation is the process of wrapping (binding)
data (variables) and methods (functions) together
into a single unit (class) and restricting direct access
to some components.
It hides the internal details of an object and only
exposes controlled access through methods.
In simple words: Data hiding(private fields) +
Controlled access(method) = Encapsulation
1. Why Encapsulation?
To protect data from unauthorized access.
To provide control over how data is
accessed/modified.
To make code more maintainable and flexible.
To achieve loose coupling between objects.
[Link] of Encapsulation
Data Hiding – Implementation details are hidden.
Controlled Access – You can add logic inside setters
(e.g., validation).
Flexibility – Internal implementation can be
changed without affecting outside code.
Improved Security – Prevents misuse of sensitive
data.
[Link]
Improves security by preventing unauthorized
access.
Code flexibility – Internal implementation can
change without affecting users.
Easy maintenance – Errors are localized inside the
class.
Reusability – Encapsulated code can be reused.
Increased modularity – Each class is a self-
contained unit.
Readable – it makes your code clean and easy to
read.
✅ Constructor vs Setter
Constructor → Used to initialize object. Called once
per object creation.
Setter Method → Used to update or modify values
after initialization. Can be called any number of
times.
✅ Rules of this()
this() statement must be the first statement inside
a constructor.
this()statement can be used only inside a
constructor (not inside methods).
Only one constructor call (this() or super()) is
allowed in a constructor.
If you don’t call explicitly, the compiler will insert a
call to super() by default.
You cannot call same constructor throgh this()
statement(Recursive call is not permitted here)
Day-18
Inheritance in Java (OOP Pillar)
Inheritance in Java is a mechanism where one class
acquires the properties (fields/instance variables)
and behaviors (methods) of another class.
It represents a parent-child relationship (also called
IS-A relationship).
The child class (subclass/derived class) can use,
override, or extend the functionality of the parent
class (superclass/base class).
Real-World Analogy
In real life, a Car IS-A Vehicle, a Dog IS-A Animal, a
Student IS-A Person.
The child (Car/Dog/Student) inherits basic features
of parent (Vehicle/Animal/Person) but can also
have additional features.
Advantages
Promotes code reusability (write once, reuse in
subclasses).
Enables Polymorphism (especially runtime
polymorphism via method overriding).
Improves maintainability and readability of code.
Allows hierarchical classification of classes.
Important Terminologies
Superclass / Parent class / Base class → the class
being inherited.
Subclass / Child class / Derived class → the class
that inherits.
extends keyword → used to define inheritance
between classes.
super keyword → used to access parent class
methods, variables, and constructors.
Object class → root of all classes in Java. (Every
class implicitly inherits Object.)
Siblings B and C extends A, then B and C are
siblings
IS-A Relationship
If class B extends A, then B IS-A A.
Example: Dog IS-A Animal → achieved via
inheritance.
IS-A is checked using instanceof operator in Java.
1. Single Inheritance
In single inheritance, a sub-class is derived from
only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes, it is
also known as simple inheritance.
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be
inheriting a base class and as well as the derived
class also acts as the base class for other classes.
3. Hierarchical Inheritance
In hierarchical inheritance, more than one subclass
is inherited from a single base class. i.e. more than
one derived class is created from a single base class.
For example, cars and buses both are vehicle
4. Multiple Inheritance (Through
Interfaces)
In Multiple inheritances, one class can have more
than one superclass and inherit features from all
parent classes.
Note: that Java does not support multiple
inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces.
5. Hybrid Inheritance
It is a mix of two or more of the above types of
inheritance. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to
involve multiple inheritance to implement Hybrid
inheritance.
What Happens Internally
When We Create an Object of
a Child Class in Java?
1. Basic Understanding
When we create an object of a child class using:
Child c = new Child();
Both Parent class and Child class objects are
created in memory, but as a single object
(combined).
The Parent part of the object is constructed first,
then the Child part is added.
2. Steps Happening Internally
[Link] Allocation
JVM allocates memory for the complete object
(which includes parent’s fields + child’s fields).
[Link] Constructor Execution
Before the child’s constructor body executes, the
parent’s constructor is automatically called.
This happens because the first statement inside
every constructor is an implicit (or explicit) call to
super().
[Link] Initialization
All instance variables of parent are initialized.
Then all instance variables of child are initialized.
[Link] Constructor Execution
After the parent constructor finishes, the child
constructor executes.
[Link] Points
A child object contains parent’s state + child’s state.
Parent constructor is always executed first (due to
super()).
If the parent has parameterized constructor only,
then child must explicitly call it using super(args).
Constructors are not inherited, but they are always
executed in the chain.
The process follows a constructor chaining
mechanism
✅ Conclusion:
When you create a child object → first parent is
instantiated (constructed), then child is constructed
on top of it. Both together form a single object
stored in heap memory.
2. Overridden Method
When child provides its own version of a parent’s
method.
Must have same name, return type, and
parameters.
Achieves runtime polymorphism.
3. Specialized Method
A method that is unique to child class only, not
present in parent.
✅ Correct Example:
class Bird {
void fly() { [Link]("Bird
can fly"); }
}
class Sparrow extends Bird { }
Sparrow is a Bird → valid substitution.
❌ Wrong Example:
class Bird {
void fly() { [Link]("Bird
can fly"); }
}
class Ostrich extends Bird { // Ostrich
cannot fly in reality
}
Day-19
Instance Initializer Block (IIB)
in Java
An Instance Initializer Block is a block of code inside
a class, enclosed within { }, which runs every time
an object of the class is created.
It is executed before the constructor
1. Final Variables
A variable declared with final becomes a constant.
Its value cannot be reassigned once initialized.
Example:
final int speed = 100;
speed = 200; // ❌ Error → cannot change final variable
2. Final Methods
A method declared final cannot be overridden in a
child class.
Used to prevent altering the original behavior of a
method.
Example:
class Vehicle {
final void run()
{ [Link]("Vehicle running"); }
}
class Car extends Vehicle {
// ❌ Error: Cannot override final
method
// void run() { [Link]("Car
running"); }
}
3. Final Classes
A class declared final cannot be inherited.
Used to stop inheritance.
Example:
final class Animal { }
class Dog extends Animal { } // ❌ Error:
cannot inherit from final class
4. Important Points
final is not the same as finally (used in exception
handling).
final is not the same as finalize() (method in Object
class for garbage collection).
Blank Final Variable: A final variable declared but
not assigned → must be initialized later (in
constructor).
Final with Static: static final = Constant (commonly
used for constants in Java).
static final double PI = 3.14159;
Final references (objects/arrays):
The reference cannot be changed, but the object’s
internal data can be modified.
final StringBuilder sb = new
StringBuilder("Hello");
[Link](" World"); // ✅ Allowed
sb = new StringBuilder("New"); // ❌ Not
allowed
2. Private Methods
❌ Not inherited (only accessible inside the class).
❌ Cannot be overridden.
If you declare the same method in child → it’s a
new method (not overriding).
class Parent {
private void secret() { }
}
class Child extends Parent {
void secret() { } // New method, not
override
}
3. Final Methods
✅ Inherited by child class.
❌ Cannot be overridden.
class Parent {
final void display() { }
}
class Child extends Parent {
// ❌ Error if we try to override
}
4. Static Methods
✅ Inherited (accessible by child).
❌ Cannot be overridden, only hidden (method
hiding).
class Parent {
static void greet()
{ [Link]("Parent greet"); }
}
class Child extends Parent {
static void greet()
{ [Link]("Child greet"); } //
hiding, not overriding
}
5. Constructors
❌ Not inherited.
❌ Cannot be overridden (special methods for
object creation).
6. Abstract Methods
✅ Inherited (if child is not abstract).
✅ Must be overridden in child, otherwise child
must also be abstract.
abstract class Parent {
abstract void study();
}
class Child extends Parent {
void study()
{ [Link]("Studying..."); }
}
✅ Uses of this:
To differentiate instance variable & local variable.
To pass current object as argument ([Link](this);).
To return current object (return this;).
3. super keyword
Refers to the immediate parent class object.
Used to access parent class variables & methods
when overridden.
Example:
class Parent {
int num = 100;
void display()
{ [Link]("Parent method"); }
}
1. Default (Package-Private):
Keyword: No keyword (if no modifier is written, it's
default).
Scope: Accessible within the same package only.
Not accessible outside the package.
When used?
Useful when you want to restrict access only within
your project module/package.
2. Private:
Keyword: private
Scope: Accessible only within the same class.
Not accessible from other classes, even in the same
package.
When used?
For data hiding, encapsulation, and security.
Typically used with variables and helper methods.
3. Protected:
Keyword: protected
Scope: Accessible within the same package (like
default).
Accessible in child classes outside the package (via
inheritance).
When used?
For inheritance across packages.
✅ Example:
package p1;
public class A {
protected int data = 50;
protected void show() {
[Link]("Protected
Method");
}
}
package p2;
import p1.A;
class B extends A {
public void access() {
[Link](data); // ✅
Accessible (inherited)
show(); // ✅
Accessible
}
}
class Test {
public static void main(String[] args) {
B obj = new B();
[Link]();
// [Link]; ❌ Error (only
accessible through inheritance)
}
}
4. Public:
Keyword: public
Scope: Accessible from anywhere in the project
(any package, any class).
When used?
When the member should be universally accessible.
Typically used with classes, APIs, utility methods.
Day-20
static Keyword in Java
static is a non-access modifier in Java.
It is used for memory management and making
members common to all objects of a class.
Belongs to the class rather than to any specific
object.
Memory is allocated only once, when the class is
loaded.
Static Methods
Declared using static keyword.
Belong to the class, not objects.
Can be called without creating an object using
[Link]().
Restrictions:
Can only access static data members and static
methods directly.
Cannot use this or super keyword.
Cannot access non-static members directly (need
object reference).
Example:
class Test {
static int count = 0;
static void show() {
[Link]("Static method:
Count = " + count);
}
public static void main(String[] args) {
[Link](); // calling without
object
}
}
Static Block
Used for static initialization of data.
Executed only once, when the class is loaded into
memory.
Can be multiple static blocks, executed in order of
appearance.
It runs only once when the class is loaded into
memory, before any object is created and before
main method is called.
Commonly used for one-time initialization (e.g.,
loading drivers, initializing static variables).
Example:
class Example {
static int data;
static {
data = 100;
[Link]("Static Block
executed");
}
public static void main(String[] args) {
[Link]("Main Method: " +
data);
}
}
Advantages
✅ Saves memory (only one copy).
✅ Shared across all objects.
✅ Can be used without creating objects.
✅ Useful for utility/helper classes.
Order of initialization:
Static members/blocks → Instance members/blocks
→ Constructor
Output (example):
Student@7a81197d
Output:
Student{name='Saif', age=25}
Day-21
Polymorphism
The word Polymorphism comes from Greek:
Poly → “many”
Morphe / Morphism → “forms” or “shapes”
So Polymorphism literally means “many forms”.
Advantages of Polymorphism
Code Reusability → General code in parent, specific
in child.
Reduce Line of Code
Flexibility → One Standard, multiple
implementations.
Extensibility → handle multiple object types
through a single interface.
Maintainability → Clean and modular design.
Better Abstraction
Loose Coupling
2. Downcasting
Converting a superclass type reference back into a
subclass type reference.
This must be done explicitly (manual casting).
Risky — if the object is not actually an instance of
the subclass, Java throws ClassCastException.
✅ Example:
public class Test {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
[Link]();
// Downcasting
Dog d = (Dog) a; // explicit
casting
[Link](); // ✅ Now
subclass methods accessible
}
}
Key Points:
Upcasting:
✔ Safe, automatic, used for polymorphism.
Downcasting:
✔ Explicit, sometimes necessary, but risky.
Day-22
Interface
What is an Interface?
An interface in Java is a blueprint of a class.
It defines a contract/standardization that
implementing classes must follow.
Declared using the interface keyword.
Cannot have objects directly (no instantiation).
It is just a block of Code.
Purpose of Interface
Standardization → defines rules that multiple
classes can follow.
Abstraction → hides implementation details, only
exposes method signatures. (NEXT SESSION)
Multiple inheritance → Java does not support
multiple inheritance with classes, but it allows a
class to implement multiple interfaces.
Loose Coupling → Reduces dependency between
modules.
Syntax Example
interface Vehicle {
void start(); // abstract method (by
default)
void stop();
}
class Car implements Vehicle {
public void start() {
[Link]("Car starts with
key");
}
public void stop() {
[Link]("Car stops with
brakes");
}
}
Interface Members
1. Methods
By default: public abstract
Writing public abstract is optional.
Example: void run(); // same as public abstract
void run();
2. Variables
Inside an interface, variables are:
public static final (constants)
Writing public static final is optional.
Must be initialized at the time of declaration.
Example:
interface Config {
int MAX_USERS = 100; // public static
final by default
}
What is
Standardization in Java
(via Interface)?
Standardization means defining a common set of
rules, methods, or structure that all implementing
classes must follow.
It ensures that even though the implementation
differs, the method names, signatures, and
expected behavior remain consistent.
❌ Problem:
Method names are different (doPayment,
makePayment, startPayment).
A client program cannot handle them in a common
way.
Tight coupling, messy system.
✅ Advantage (Standardization):
All classes must implement pay(double amount).
Client code becomes simple and independent of
implementation:
Payment p = new Paytm(); // Or PhonePe /
GooglePay
[Link](500.0);
class ShoppingMall {
private DebitCard card; // directly
dependent on DebitCard
❌ Problem:
If tomorrow we want to use UPI / Wallet, we must
change the ShoppingMall class code.
Not flexible, not reusable.
// Step 2: Implementations
class DebitCard implements Payment {
public void pay(double amount) {
[Link]("Payment of " +
amount + " using Debit Card");
}
}
In simple words:
Tight Coupling = ShoppingMall is married to
DebitCard forever (hard to change).
Loose Coupling = ShoppingMall just needs someone
who can “pay” (anyone implementing Payment
interface).
What is Multiple
Inheritance?
Multiple Inheritance means a class can inherit from
more than one parent (getting features from
multiple sources).
Example in real life:
o A SmartPhone is both a Camera and a Phone.
o It inherits behavior from both.
NOTE: in Java, class → class multiple inheritance is
NOT allowed because of the Diamond Problem.
A class can implement multiple interfaces.
Example:
interface A {
void show();
}
interface B {
void display();
}
Marker Interface
An empty interface (no methods, no variables).
Used to mark/tag classes for special behavior.
Examples in Java:
o Serializable
o Cloneable
o Remote
Advantages of Interface
Achieves 100% abstraction (before Java 8).
Supports multiple inheritance.
Improves loose coupling and flexibility.
Helps in scalability.
✅ Today we learned
What is Interface and its purpose (standardization,
loose coupling).
Multiple inheritance issue in Java and how
Interfaces solve it.
Marker Interface and coupling concepts.
Next Session: We will learn Abstraction in Java –
what it is, why it’s needed, and how abstract
classes differ from interfaces.
Day-23
Abstraction in Java
Abstraction is the process of hiding the
implementation details and showing only the
essential features to the user.
It focuses on what an object does rather than how
it does it.
In Java, abstraction is achieved using abstract
classes and interfaces.
In simple terms: You know what it does, but not
how it does it.
Levels of Abstraction
High-level abstraction → Interfaces (100%
abstraction possible).
Partial abstraction → Abstract classes (0–100%
abstraction).
Key Concept
Encapsulation → Hides the data (achieved using
classes & access modifiers).
Abstraction → Hides the implementation (achieved
using abstract classes & interfaces).
So, Encapsulation is data-hiding, and Abstraction is
implementation-hiding.
Real-Life Examples
[Link] Driving
You just know start(), stop(), accelerate()
You don’t know how the engine works internally →
Implementation is hidden.
[Link] Machine
User knows: insert card, enter PIN, withdraw
money.
Internal process: verifying account, updating DB →
Hidden.
Advantages of Abstraction
✅ Increases security by hiding implementation.
✅ Improves code reusability.
✅ Makes the system more flexible and scalable.
✅ Supports loose coupling.
✅ Focuses on what to do, not how to do.
interface Shape {
void draw(); // abstract method (no
implementation)
}
class Circle implements Shape {
public void draw() {
[Link]("Drawing
Circle");
}
}
class Rectangle implements Shape {
public void draw() {
[Link]("Drawing
Rectangle");
}
}
public class TestInterface {
public static void main(String[] args) {
Shape s1 = new Circle();
Shape s2 = new Rectangle();
[Link]();
[Link]();
}
}
Abstraction is achieved here because the Shape
interface hides implementation details and only
defines the behavior (draw()), while different
classes (Circle, Rectangle) provide their own
implementations. The client code (main) interacts
only with the abstract type (Shape), not with
concrete implementations.
class ShapeFactory {
// Factory method
Public Shape getShape(String shapeType)
{
if (shapeType == null) {
return null;
}
if
([Link]("CIRCLE")) {
return new Circle();
} else if
([Link]("RECTANGLE")) {
return new Rectangle();
} else if
([Link]("SQUARE")) {
return new Square();
}
return null;
}
}
Shape shape1 =
[Link]("CIRCLE");
[Link]();
Shape shape2 =
[Link]("RECTANGLE");
[Link]();
Shape shape3 =
[Link]("SQUARE");
[Link]();
}
}
Advantages
✅ Client is decoupled from concrete classes.
✅ Centralized object creation logic.
✅ Easy to add new classes without changing client
code.
✅ Improves maintainability and flexibility.