[Go to site: main page, start]

0% found this document useful (0 votes)
11 views255 pages

Java Full Stack

Java Full Stack Development involves creating both the front-end and back-end of web applications using Java technologies. It includes understanding client-server architecture, enterprise applications, and the differences between websites and web applications. Learning Java Full Stack is beneficial due to high job demand, the ability to build complete projects independently, and the support of a strong community.

Uploaded by

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

Java Full Stack

Java Full Stack Development involves creating both the front-end and back-end of web applications using Java technologies. It includes understanding client-server architecture, enterprise applications, and the differences between websites and web applications. Learning Java Full Stack is beneficial due to high job demand, the ability to build complete projects independently, and the support of a strong community.

Uploaded by

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

Java Full

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

Web Application (WebApp):


A web application is a dynamic, interactive system
where users can log in, perform actions, and receive
output.
 Users can interact with the system
 Has login/signup, forms, dashboards, etc.
 Uses a backend + database
 Data changes based on user input
Example:
Amazon, Flipkart
Gmail, Facebook
Admin dashboard, Student portal

Why Learn Java Full Stack?


1. High Demand in Job Market
 Companies prefer developers who can handle both
front-end and back-end.
 Java Full Stack developers are in high demand for
enterprise, fintech, e-commerce, and startup jobs.

2. Build Complete Projects


 You can independently create full web apps: login
systems, dashboards, portals, etc.
 No need to depend on separate front-end or back-
end teams.

3. Java is Trusted by Big Companies


 Java is stable, secure, and widely used by
companies like Amazon, Microsoft, Google, TCS,
Infosys, etc.
 It’s backed by a strong ecosystem like Spring, Spring
Boot, and Hibernate.

4. Better Salary Opportunities


 Full Stack Developers usually earn more than pure
front-end or back-end developers.

5. Strong Community and Support


 Java has vast documentation, a large community,
and a wide range of tools for faster development.

6. Java’s Speed and Performance


 Java offers high performance.
 It's ideal for building fast, scalable, and real-time
applications.

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

Client-Server Architecture (Big Picture for


Web Applications)
Client-Server Architecture is a design pattern where the
system is divided into two main parts:
 Client → The part that requests services (usually
the browser or mobile app)
 Server → The part that provides services (processes
the request, handles business logic, talks to
database)

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

Java Full Stack Development –


Summary
 Java Full Stack means building both Frontend (UI)
and Backend (logic + database) of a web application
using Java technologies.

 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.

 Web App vs Website:


 Web app is interactive (login, dashboard);
website is mostly static (info only).

 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.

Q2: Why do we need a


programming language?
Computers don't understand human languages like
English or Hindi. Programming languages act as a bridge
between humans and computers, helping us give
commands in a way that the computer can understand
and execute.
Q3: Why can computers only
understand 0 and 1?
Computers are made of electronic circuits that work on
electricity. These circuits have only two states: ON
(represented by 1) and OFF (represented by 0). That’s
why computers use binary (base-2) to process and store
data.
Q4: What are the different
types of programming
languages?
Programming languages are mainly divided into three
types:
 Low-Level Language: Close to machine language,
very fast but hard to understand (e.g., Assembly).
 High-Level Language: Easy to understand and write,
close to human language (e.g., Java, Python).
 Middle-Level Language: Has features of both low
and high-level languages (e.g., C & C++).
NOTE:
 Machine language was first introduced in the
1940s with the advent of the earliest digital
computers like ENIAC. It was the only language
these machines could understand, consisting
entirely of binary instructions.
 The first computer program is widely attributed to
Ada Lovelace, who developed an algorithm for
Charles Babbage's Analytical Engine in 1843.
 Ada Lovelace wrote the first program (an
algorithm for Bernoulli numbers) in 1843 using
mathematical notations—not a formal
programming language.
 The first designed high-level programming
language was Plankalkül, developed by Konrad
Zuse between 1942 and 1945. Though it wasn’t
implemented at the time, Plankalkül introduced
concepts like variables, arrays, loops, and
structured programming—features found in
modern languages.
 The first implemented and widely used high-level
programming language was FORTRAN (Formula
Translator), released by IBM in 1957. It was
designed for scientific and engineering
calculations and came with an advanced compiler
for its time. FORTRAN made programming more
accessible and practical, becoming the first
industry-standard language used globally.
 The first middle-level programming language is
generally considered to be C, developed in the
early 1972 by Dennis Ritchie at Bell Labs.
 Before the C language was developed, most
programming languages were not general-
purpose and were created with specific use cases
in mind. These early languages were typically
designed to solve particular types of problems or
serve specialized fields. For example, FORTRAN
was developed for scientific and mathematical
computing, COBOL was tailored for business and
financial applications, and LISP was mainly used in
artificial intelligence research. These languages
lacked the flexibility to be used across different
domains. They were also often hardware-
dependent and not suitable for writing operating
systems or low-level software. C changed this by
offering a simple, powerful, and portable
language that could be used for both system-level
programming, like operating systems, and
application development, making it one of the first
truly general-purpose programming languages.

DEMO POGRAM (LOW LEVEL):


1. Machine Language (Binary / 1st
Generation Language)
Actual binary will depend on hardware, but here's a
conceptual example:
Binary Code (Conceptual):
 0001 0101 ; Load 5 into register
 0010 0011 ; Add 3
 0011 1000 ; Store result in
memory
Note: This is not portable, extremely hard to read, and
varies between CPUs.

2. Assembly Language (2nd Generation


Language)
 MOV A, 5 ; Move 5 into register
A
 ADD A, 3 ; Add 3 to register A
 MOV RESULT, A ; Store result in
RESULT
More readable, but still hardware-specific.

Q5: What is the difference


between compiler, interpreter,
and assembler?
Term Purpose
Example Languages
 Compiler Translates the whole program
at once into machine code C, Java
(compiles to bytecode)
 Interpreter Translates and executes line by
line Python,
JavaScript
 Assembler Converts assembly language
into machine code Assembly
Language

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

Download Eclipse IDE :


[Link]
2025-03/r/eclipse-ide-enterprise-java-and-web-
developers
 IDE stands for Integrated Development
Environment.
 It is a software application that helps programmers
write, test, and debug their code all in one place.

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.

Java Program Execution Flow:


 Source Code (.java)
o▼
 Compiler (javac)
o▼
 Bytecode (.class)
o▼
 Java Interpreter (java)
o▼
 Program Output

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).

2. Create a New Java Project (SET


PERSPECTIVE FROM JAVA EE to JAVA
FIRST)
 Click on:
 File → New → Java Project
 Enter the project name, for example:
FirstJavaProject
 Click Finish

3. Create a Package (Optional but


Recommended)
 Right-click on the src folder inside your project.
 Click:
 New → Package
 Enter package name (e.g., [Link])
 Click Finish

4. Create a Java Class


 Right-click on the package you just created.
 Click:
 New → Class
 Enter the class name, e.g., HelloWorld
 Tick the checkbox that says:
 public static void main(String[] args) (this will
auto-generate the main method)
 Click Finish

5. Write Your Code


 Eclipse will open the [Link] file. You'll
see something like this:
package [Link];
public class HelloWorld {
public static void main(String[] args)
{
[Link] ("Hello,
World!");
}
}

 You can now edit or expand this code as needed.

6. Run the Program


 Right-click anywhere inside the code editor or on
the file in the Project Explorer.
 Click:
 Run As → Java Application
 The output will appear in the Console at the
bottom.

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

Created by: James Gosling in 1995 at Sun


Microsystems
 Sun Microsystems was later acquired by Oracle
Corporation on 20th April 2009 for $7.4 billion.

Origin:
 In 1991, Sun Microsystems did market research to
develop software for set-top boxes.
 This led to the creation of the Green Project.

Green Team Members:


 James Gosling (Team Lead)
 Patrick Naughton
 Mike Sheridan

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.

The focus was on:


 Platform independence
 Compact code
 Security and reliability
 Running on limited-resource devices

While working on Oak, Sun


Microsystems realized that:
 The Internet was booming
 A platform-independent, highly secure, network-
friendly and robust language would be perfect for
Internet applications, especially web applets So,
they repositioned Java for the web.

Java Naming: Full Story


Original Name: Oak
 Before being named Java, the language was
originally called “Oak”.

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.

Why “Oak” Was Rejected


 The name “Oak” was already trademarked by Oak
Technologies, a company that made hardware
products.
 Due to legal and trademark issues, Sun had to find a
new name.
Final Name: Java
The development team wanted a name that was:
 Unique
 Memorable
 Easy to spell and say
 Unrelated to technology (to avoid trademark
conflicts again)
After much brainstorming, they selected "Java",
inspired by Java Coffee

Java Naming: Story Behind the


Name "Java"
Java is an Island
 Java is the name of a large island in Indonesia.
 This island was historically famous for growing
high-quality coffee beans.
 The word “Java” became a nickname for coffee
(ESPRESSO) around the world.
1600s – Dutch Influence
 In the 1600s, the Dutch East India Company started
coffee plantations on Java Island.
 They exported Java coffee globally, making the
island's name synonymous with coffee.

Why the Name "Java"?


 While choosing a name for their new language, the
developers (including James Gosling) wanted
something unique, easy to remember, and fun.

They brainstormed many names like:


 Dynamic, Silk, Jolt, Revolution, etc. — but none felt
right.
 They used to drink a lot of coffee while coding,
especially Java coffee.
 Eventually, they chose “Java” — inspired by Java
Island’s coffee and its cool, catchy sound.
 So, Java is named after the coffee, which is named
after the island.
 Java became popular in the mid-1990s largely due
to the rapid growth of the World Wide Web
(WWW). As the Internet was expanding globally,
there was a huge demand for secure, portable, and
interactive applications that could run inside web
browsers. Java, with its unique ability to run the
same code on any platform (thanks to the JVM),
perfectly fit this need.

Day-6
Architecture of Java
The architecture of Java refers to the fundamental
components and structure that make the Java
programming language work.

1. Java Development Kit (JDK)


 Java’s full toolbox for development
 Definition: The JDK is a complete software
development kit required to develop, compile, and
run Java applications.
 JDK = JRE + Compiler + Development Tools

2. Java Runtime Environment (JRE)


 The kitchen where Java code runs
 Definition: The JRE is the environment required to
run Java applications. It does not include
development tools.
 JRE = JVM + Libraries (APIs)

3. Java Virtual Machine (JVM)


 The engine that runs Java code
 Definition: The JVM is an abstract machine that
loads, verifies, and executes byte code on any
platform.
 JVM = Interpreter + Bytecode loader + Verifier
Q: Why is Java platform-
independent?
 Java is platform-independent because of its unique
architecture. When a Java program is written and
compiled using the Java compiler (javac), it is not
directly converted into platform-specific machine
code. Instead, it is converted into an intermediate
form called bytecode (.class file). This bytecode is
the same across all platforms and can be executed
on any system that has a Java Runtime
Environment (JRE). The JRE is platform-specific and
is responsible for converting bytecode into native
machine code at runtime. This allows the same Java
program (bytecode) to run on Windows, Linux,
Mac, or any other operating system without
modification, making Java truly platform-
independent—also known as "Write Once, Run
Anywhere (WORA)".
Q: Can we Run Java code with
only JRE?
 Yes, we can run Java code with only the JRE, but
not compile it. The JRE (Java Runtime Environment)
contains everything needed to run a Java program,
such as:
 The JVM (Java Virtual Machine)
 Core Java class libraries
 Other Runtime components
 If you already have the compiled Java bytecode
(.class file), then the JRE is enough to run it using
the java command: java HelloWorld
Day-7
Features of Java
1. Simple Language
 Syntax is similar to C/C++, making it easy to
learn.
 Java code is easy to read and write.
 No explicit use of pointers, reducing
complexity and increasing safety.

2. Object-Oriented Programming Language


(OOP)
 Java follows the Object-Oriented Programming
model.
 Supports core OOP principles:
1) Encapsulation
2) Inheritance
3) Polymorphism
4) Abstraction
 Polymorphism
 Promotes modularity, reusability, and makes
code easier to maintain.
3. Platform Independent
 Java follows WORA: Write Once, Run
Anywhere.
 Java code is compiled into bytecode, which can
run on any platform with a JVM (Java Virtual
Machine).

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.

6. Robust Language (Mazboot)


 Java has strong memory management via
Garbage Collection.
 Supports exception handling to catch runtime
errors.
 Helps prevent common programming issues
like memory leaks or crashes.

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.

10. Portable Language


 Java programs are portable across platforms.
 Same .class file runs on any system with a
compatible JVM.
 No need to recompile for different machines.
11. Dynamic Language
 Java supports dynamic loading of classes at
runtime.
 Uses:
1) Class Loaders
2) Reflection API
3) Helps in developing flexible and
extensible applications.

12. Interpreted Language


 Java source code is compiled to bytecode.
 Bytecode is interpreted by the JVM.
 Combines benefits of both compiled and
interpreted languages.
 Compiled language (like C, C++):
 Runs faster — because the program is
already converted into machine code
before you run it.
 Interpreted language (like Python, JavaScript):
 Easier to run and test — you can
execute it directly without a separate
“build/compile” step.

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.

Final unit analogy:


 A paragraph is the final meaningful unit in
English, and similarly, a Java program is the
final executable unit made from simpler
building blocks.
Q1: What is a variable in Java?
 A variable is a named container used to store
data that can be changed during program
execution. Example: int a=10;

Q2: What is a literal in Java?


 A literal in Java is a fixed value that is written
directly in the code.
 It represents constant values that are directly
assigned to variables.

Q3: What is an Identifier in


Java?
 An identifier is the name used to identify
variables, methods, classes, objects, packages,
etc., in a Java program. Basically, any name
you create in your code is an identifier.

Q4: What is a keyword in Java?


 A keyword is a reserved word that has a
special meaning in Java. It is part of the
language syntax and cannot be used as names
for variables, methods, or classes. Example:
while

Q5: What is an assignment


operator in Java?
 The assignment operator (=) is used to assign a
value to a variable. It takes the value on the
right side and stores it in the variable on the
left side.

Q6: What is the semicolon (;)


called in Java?
 It is called a statement terminator because it
marks the end of a statement, telling the
compiler the instruction is complete.
Q7: What are comments in
Java and what types are there?
 Comments are notes in the code ignored by
the compiler, used to explain or document the
code. There are three types of comments in
Java:

 Single-line comment: Starts with // and goes


to the end of the line.
Example: // This is a single-line comment

 Multi-line comment: Enclosed between /* and


*/ and can span multiple lines.
Example:
/*
This is a
multi-line comment
*/
 Documentation comment: Starts with /** and
ends with */. Used to generate documentation
with tools like Javadoc.
Example:
/**
* This method adds two numbers.
*/
 Comments help programmers understand code
but do not affect how the program runs.
==========================Program:
Variable Declaration &
Initialization========================
===
package [Link];
public class Launch {
//JVM
public static void main(String[] args) {
//ENTRY POINT

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

RULES OF CONSTRUCTING AN INDENTIFIER


1. ALLOWED: Alphabets (A-Z a-z) Digits (0-9) Special
Symbols ( $ and _ )
2. You can’t start with digits
3. You can’t take space in-between;
4. No limit of length (within 15)
5. Meaningful
6. Case sensitive
7. You can’t take keyword name as an identifier

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 (Lower Camel Case)


[Link]
• The first letter of each word is capitalized
• Ex. ThisIsMyCar , MyNameIsRaju, StartFirst
• IN JAVA : class name , interface name
[Link]
• The first letter should be in lower case and
subsequent word starts with Upper case
• Ex. thisIsMyCar , myNameIsRaju, startFirst
• IN JAVA : variable name , method name

2. PASCAL CASE: (UPPER CAMEL CASE)


• The first letter of each word is capitalized
• Ex. ThisIsMyCar , MyNameIsRaju, StartFirst
• IN JAVA : class name , interface name

3. SNAKE CASE: (Lower Snake Case)


a. Upper snake case
• All letters are in upper case but words are
separated by underscores
• Ex THIS_IS_MY_CAR
• IN JAVA: static final variable, Constant
b. Lower snake case
• All letters are in lower case but words are
separated by underscores
• Ex this_is_my_car

[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)

PACKAGE NAME CONVENTION:


• All letters are in lower case and the words are
separated by .
• Reverse order of domain name
• Ex. [Link]

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:

NASA Mars Climate Orbiter Crash (1999)

[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.

Primitive Data Types


 Primitive data types are the most basic data types
available within the Java language. They serve as
the building blocks of data manipulation in Java.
These types are not objects and hold their values
directly in memory.
 There are 8 primitive data types in Java:
 Integer Types: byte, short, int, long
 Floating-Point Types: float, double
 Other Types: char, boolean

Integer Data Types


a) byte
 Size: 1 byte (8 bits)
 Range: -128 to 127
 Description: The smallest integer type. Useful for
saving memory in large arrays, especially in place of
integers when the value range is limited.
 Example: byte age = 25;
b) short
 Size: 2 bytes (16 bits)
 Range: -32,768 to 32,767
 Description: Larger than byte but smaller than int.
Suitable for environments where memory savings
matter.
 Example: short temperature = 30000;

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;

Range Formula for Integer


types
 Range = -2^(n-1) to 2^(n-1) – 1 where n is size in bit
 Example for byte: -2^7 to 2^7 - 1 = -128 to 127

Floating-Point Data Types


a) float
 Size: 4 bytes (32 bits)
 Range: Approximately -3.4 * 10^38 to +3.4 * 10^38
 Precision: ~7 decimal digits
 Example: float pi = 3.14F;
b) double
 Size: 8 bytes (64 bits)
 Range: Approximately -1.7 * 10^308 to +1.7 *
10^308
 Precision: ~15 decimal digits
 Example: double e = 2.7182818284;

Other Primitive Data Types


a) char
 Size: 2 bytes (16 bits)
 Range: 0 to 65,535 (based on Unicode character
set)
 Description: Represents a single 16-bit Unicode
character. Stored inside single quotes.
 Example: char letter = 'A';

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 {

public static void main(String[] args) {

byte v1=122;
short v2=32000;
int v3=799999999;
long v4=34543875L; //L or l

float v5=12.67f; //F or f


double v6=12.67;

char v7='a'; // char v7=97;

boolean v8=false; //true

// 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.

User Input using Scanner


To take input from the user during program execution,
Java provides the Scanner class from the [Link]
package.
Example:
import [Link];
public class UserInputExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]); //
Scanner object to read input
[Link]("Enter a number: ");
int a = [Link](); // Taking integer
input from the user
[Link]("You entered: " +
a);
}
}

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
}

if else statement : The if else statement is a basic


decision-making control structure in Java. It is used
when you want to execute one block of code if a
condition is true, and a different block if the condition is
false.
if(condition) {
// true block
} else {
// false block
}
if else if / else if ladder: The if else if ladder is used
when multiple conditions need to be tested one by one.
It allows you to execute different blocks of code based
on which condition is true.
if(cond1) {
// code
} else if(cond2) {
// code
} else {
// default
}

Nested if else: A nested if else means using an if or if-


else block inside another if or else block. It is used to
test multiple levels of conditions.
if(cond1) {
if(cond2) {
// code
} else {
// code
}
}

Note on if Statements Without


Curly Braces {}
 In Java, if you write an if statement without curly
braces, only the very next single statement
immediately following the if condition is
considered part of the if block. Any statements
after that will execute regardless of the if
condition.
Example:
if (condition)
[Link]("This runs if
condition is true.");
[Link]("This always runs,
no matter what.");

=========================Program:
User input and if
statement==========================
=====

package [Link];
import [Link];
public class Launch {

public static void main(String[] args) {

Scanner scan=new Scanner([Link]); //ONE TIME

// [Link]("Enter Your Age");


// int age=[Link]();
// byte age=[Link]();
// short age=[Link]();
// long age=[Link]();
// [Link]("Your Age is "+age);

// [Link]("Enter Your Height Ex. 5.6");


// float height=[Link]();
// double height=[Link]();

// [Link]("Are you avaiable");


// boolean isAvailable=[Link]();
// [Link](isAvailable);
// [Link]("Enter your gender(m/f)");
// char gender=[Link]().charAt(0);
// [Link](gender);

[Link]();

}
}

package [Link];
import [Link];
public class Launch2 {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);


[Link]("Enter your age");
int age=[Link]();

if(age>=18) {
[Link]("ELIGIBLE");
}
else {
[Link]("NOT ELIGIBLE");
}

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

package [Link];
import [Link];
public class Launch3 {

public static void main(String[] args) {

//per>=60 , age>=18 , countryCode==91 = Eligible


//Not Eligible: PER
//Not Eligible: AGE
//Not Eligible: CC

Scanner scanner = new Scanner([Link]);


int per,age,cc;

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


age=[Link]();

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


per=[Link]();

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


cc=[Link]();

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 {

public static void main(String[] args) {

//pincode=1111 -> bhopal


//pincode=1112 -> pune
//pincode=1113 -> mumbai
//otherwise -> not found

Scanner scanner = new Scanner([Link]);


int pincode;

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


pincode=[Link]();

// 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 {

public static void main(String[] args) {

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.

When to Use if-else-if instead


of Switch:
 Decimal Values (e.g., double, float) → Switch does
not support them.
 Object Comparison (custom objects , complex
conditions or variables).
 Complex Expressions (logical combinations, ranges).

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 {

public static void main(String[] args) {

//per>=60 and age>=18 and cc==91 => Eligible


//Not Eligible
Scanner scanner = new Scanner([Link]);
int per,age,cc;

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


age=[Link]();

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


per=[Link]();

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


cc=[Link]();

if(per>=60 && age>=18 && cc==91 ) {


[Link]("eligible");
}
else {
[Link]("not eligible");
}

[Link]();
}
}

package [Link];
import [Link];
public class Launch2 {

public static void main(String[] args) {

//per>=60 and age>=18 and cc==91 => Eligible


//Not Eligible

Scanner scanner = new Scanner([Link]);


int per,age,cc;

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


age=[Link]();

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


per=[Link]();

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


cc=[Link]();

if(per>=60 || age>=18 || cc==91 ) {


[Link]("eligible");
}
else {
[Link]("not eligible");
}

[Link]();
}
}
package [Link];
import [Link];
public class Launch3 {

public static void main(String[] args) {

//per>=60 and age>=18 and cc==91 => Eligible


//Not Eligible

Scanner scanner = new Scanner([Link]);


int per,age,cc;

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


age=[Link]();

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


per=[Link]();

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


cc=[Link]();

if( ! ( per>=60 && age>=18 && cc==91 ) ) {


[Link]("eligible");
}
else {
[Link]("not eligible");
}

// if( per<60 && age<18 && cc!=91 ) {


// [Link]("eligible");
// }
// else {
// [Link]("not eligible");
// }

[Link]();
}
}

===================================
===================================
===========

============================Program
: Switch
Statement==========================
==

package [Link];
import [Link];
public class Launch {

public static void main(String[] args) {

/*
* num1=10 num2=20 choice=1,2,3,4 choice==1 : add
choice==2 : sub choice==3 :
* div choice==4 : mul
*/

Scanner scanner = new Scanner([Link]);


[Link]("ENTER NUM1:");
int num1 = [Link]();

[Link]("ENTER NUM2:");
int num2 = [Link]();

[Link]("ENTER CHOICE:");
int choice = [Link](); // 4

if (num1 > num2) {

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 {

public static void main(String[] args) {

/*
* num1=10 num2=20 choice=1,2,3,4 choice==1 : add
choice==2 : sub choice==3 :
* div choice==4 : mul
*/

Scanner scanner = new Scanner([Link]);

[Link]("ENTER NUM1:");
int num1 = [Link]();

[Link]("ENTER NUM2:");
int num2 = [Link]();
[Link]("ENTER CHOICE:");
int choice = [Link](); // 4

if (num1 > num2) {


switch (choice) {
case 1:
[Link](num1 + num2);
break;
case 2:
[Link](num1 - num2);
break;
case 3:
[Link](num1 / num2);
break;
case 4:
[Link](num1 * num2);
break;
default:
break;
}
}

[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.

Types of Loop Statements


1.1 for loop
Purpose: Executes a block of code for a fixed number of
times.
Syntax:
for(initialization; condition; update)
{
// code to execute
}

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++;
}

1.3 do-while loop


Purpose: Similar to while loop but executes at least
once because condition is checked after execution.
Syntax:
do {
// code to execute
} while(condition);

Example:
int i = 1;
do {
[Link]("Value of i: " +
i);
i++;
} while(i <= 5);

1.4 Enhanced for loop (for-each loop)


Purpose: Used for iterating over arrays or collections
without using index.
Syntax:
for(dataType variable :
arrayOrCollection) {
// code to execute
}

Example:
int[] numbers = {1, 2, 3, 4, 5};
for(int num : numbers) {
[Link](num);
}

Types of Jump Statements


2.1 break statement
Purpose: Used to exit a loop or switch statement
immediately.
Example:
for(int i = 1; i <= 10; i++) {
if(i == 5) {
break; // loop stops when i is
5
}
[Link](i);
}
Output:
1
2
3
4

2.2 continue statement


Purpose: Skips the current iteration of a loop and jumps
to the next iteration.
Example:
for(int i = 1; i <= 5; i++) {
if(i == 3) {
continue; // skip when i is 3
}
[Link](i);
}

Output:
1
2
4
5

2.3 return statement


Purpose: Exits from the current method and optionally
returns a value.
Example:
public static int sum(int a, int b) {
return a + b; // returns the sum to
the caller
}

2.4 goto statement


Note: Java does not support goto for security and
readability reasons.
However, the keyword goto is reserved and cannot be
used as an identifier.

============================Program
: Loop Statement & Jump
Statement==========================
==

package [Link];
public class Launch {

public static void main(String[] args) {

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


// [Link]("HELLO");
// }

// 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");
// }

// for(int i=1 ; i>=5 ; i++) {


// [Link]("HELLO");
// }

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


// [Link]("HELLO");
// }

// for(int i=1 ; i<=5 ; i--) {


// [Link]("HELLO");
// }

// for(int i=10 ; i>=5 ; i++) {


// [Link]("HELLO");
// }

// for(int i=10 ; i>=5 ; i--) {


// [Link]("HELLO");
// }

// for(int i=10 ; i>=5 ; i--) ;


// [Link]("HELLO");
// [Link]("HIIII");

// 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);

// for (int i = 1; i <= 10; i++) {


// if(i==5) {
// continue;
// }
// [Link]("HELLO"+i);
// }

// 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 {

public static void main(String[] args) {

// 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 :
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*

For more patterns :


[Link]
list=PL0P9REiGk_zZHIwrZI9p-5UqxIs5UbUtM

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

Types of Operators in Java


[Link] Operators:
Perform basic mathematical calculations.
 + Addition
 - Subtraction
 * Multiplication
 / Division (quotient)
 % Modulus (remainder)

[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)

Pre vs Post Example:


int x = 5;
[Link](++x); // 6 (first
increase, then use)
[Link](x++); // 6 (first use,
then increase)
[Link](x); // 7

[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] (Comparison) Operators


Used to compare values. Always return boolean.
 == Equal to 5 == 5 true
 != Not equal to 5 != 3 true
 > Greater than 7>3 true
 < Less than 2<5 true
 >= Greater or equal 5 >= 5 true
 <= Less or equal 3 <= 3 true

[Link] Operators
Used for combining boolean conditions.
 && (AND)
 || (OR)
 ! (NOT)

[Link] (Ternary) Operator


 Shorthand for if-else.
 result = (condition) ? value1 : value2;
Example:
int age = 20;
String result = (age >= 18) ? "Adult" :
"Minor";
[Link](result); // Adult

[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 {

public static void main(String[] args) {

//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);

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


// [Link]("hello");
// }

//int a=10;

// int a=10;
// //a=a+5;
// a+=5;
// [Link](a);

//32 bit representation


// int a=5; //00000101
// int b=4; //00000100
//
// int c=a & b; //00000100 //0&0->0
// [Link](c);

// int a=5; //00000101


// int b=4; //00000100
//
// int c=a | b; //00000101
// [Link](c);
// int a=5; //00000101
// int b=4; //00000100
//
// int c=a ^ b; //00000001
// [Link](c);

// int a=4; //00000100 : add 1 and make it negative


// int b=~a;
// [Link](b);

// int a=4; //00000100 //01000000


// int b=a<<4;
// [Link](b);

// int a=4; //00000100 //00000010


// int b=a>>1;
// [Link](b);

// int a=-4; //11111100 //11111110


// int b=a>>1;
// [Link](b);

// int a=-4;
// int b=a>>>1;
// [Link](b);

//00000000 00000000 00000000 00000100 : 4


//11111111 11111111 11111111 11111100 : -4
//11111111 11111111 11111111 11111110 : shift by 1
//

}
}

===================================
===================================
==========================
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!");
}

Ways to Create User-Defined


Methods in Java
There are 4 main ways to create a user-defined method:
1. Method without Parameters and
without Return Value
 Does not take input, does not return anything
(void).
class Demo {
public void greet() {
[Link]("Hello,
Welcome!");
}
}

2. Method without Parameters but with


Return Value
 Does not take input, but returns a value.
class Demo {
public int getNumber() {
return 10;
}
}

3. Method with Parameters and without


Return Value
 Takes input, but does not return anything.
class Demo {
public void displaySum(int a, int
b) {
[Link]("Sum = " +
(a + b));
}
}

4. Method with Parameters and with


Return Value
 Takes input and also returns output.
class Demo {
public int add(int a, int b) {
return a + b;
}
}

Important Points about Java


Methods
 Methods must be defined inside a class (Java does
not support standalone functions).
 Method cannot be nested – one method cannot be
defined inside another method.
 Method name must follow Java identifier rules
(cannot start with number, no special characters
except _ and $).
 Method name should follow Lower Camel Case for
better readability
 Return type is mandatory (if no return value, use
void).
 Parameter list is optional – methods may have 0 or
more parameters.
 Every method must have a body (except abstract
methods, interface methods, and native methods).
 The main() method is the entry point of any Java
program.
 Access modifiers (public, private, protected,
default) define visibility of a method.
 A method can call another method inside the same
class or another class.
 Recursive calls are allowed (a method calling itself).
 A method can return only one value (but you can
return objects/arrays to hold multiple values).

Is main() Method User-defined


or Predefined?
 The main() method in Java is a special method that
acts as the entry point of every standalone Java
application.
 The method header/signature (public static void
main(String[] args)) → Predefined (fixed by JVM).
 The method body (logic inside main) → User-
defined (written by programmer).
So, we can say:
 The main() method is predefined in signature but
user-defined in implementation.

===================================
===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:

Base Case (Termination condition):


 Stops the recursion.
 Prevents infinite calls and StackOverflowError.

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);
}
}

What is Character Encoding?


 Character Encoding is the process of converting
characters (letters, digits, symbols) into their
numeric representation so that computers can
process and store them.
 Since computers only understand numbers (binary),
every character is mapped to a unique numeric
code.

Character Encoding in Java


 Java uses Unicode for character encoding.
 Earlier systems used ASCII, which Java also supports
as a subset of Unicode.

1. ASCII (American Standard Code for


Information Interchange)
Developed for English letters, digits, and special
symbols.
Uses 7 bits (128 characters).
Ranges:
 A – Z → 65–90
 a – z → 97–122
 0 – 9 → 48–57
 Limited → Only English + basic symbols.

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]

Type Casting in Java


 Type casting in Java is the process of converting a
variable from one data type to another.
 It can be applied to both primitive types and non-
primitive types (objects).
Types of Type Casting
There are two main types of type casting in Java:
 Widening (Implicit) Type Casting
 Narrowing (Explicit) Type Casting

1. Widening (Implicit) Type Casting


 Converting a smaller data type into a larger data
type.
 Performed automatically by the compiler.
 No data loss (safe conversion).
 Also known as type promotion.

✅ 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).

Types of Variables in Java


In Java, variables are classified into 3 main types based
on their position and behavior:
 Local Variables
 Instance Variables (Non-static variables) : Later
 Static Variables (Class variables) : Later

Local Variables in Java


 A local variable is a variable that is declared inside a
method, constructor, or block.
 It is created when the method is invoked and
destroyed when the method exits.

Characteristics of Local Variables


 Scope → Limited to the method, constructor, or
block where it is declared.
 Lifetime → Exists only while the method is running;
destroyed after method finishes.
 Access Modifier → Cannot use access modifiers
(public, private, protected) with local variables.
 Default Value → No default value assigned → must
be explicitly initialized before use.
Day-15
OOP (Object-Oriented
Programming)
 OOP (Object-Oriented Programming) is a
programming paradigm (approach) that organizes
software design around objects and classes, instead
of just functions and logic.
 It is a style of programming where real-world
entities (like Student, Car, Bank Account) are
represented as objects in code.
 OOP is not just a language feature, it is a design
methodology and programming model that
improves reusability, maintainability, and
scalability of software.

Different Ways to Define OOP


 It is a style of programming
 It is a way of programming
 It is a programming paradigm (approach)
 It is a programming model
 It is a programming methodology
 It is a design approach
 It is a programming phylosophy

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.

OOPs = Object-Oriented Programming


concepts (plural form of OOP)
 Informal way of referring to all the concepts of OOP
together.
 The “s” in OOPs does NOT mean “system” or
“structure” (that’s a common misconception).
 It is just the plural form of OOP → i.e., “the set of
OOP concepts.”

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.

Class & Object in OOPs


Class
 A class is a fundamental building block of Object-
Oriented Programming.
 It is a blueprint/template used to create objects.
 A class defines properties (instance variable/data
members) and behaviors (methods).
 It is also called a User-Defined Data Type (UDDT).
 Class itself does not occupy memory in RAM when
defined. Memory is only allocated when an object
is created.
 Purpose: Provides categorization and modularity in
programs.
 Example in Java:
class Student {
public int id; // data member
public String name; // data member

void study() { // method


[Link](name + " is
studying");
}
}

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):

State (Data / Properties)


 Represents the attributes or data of the object.
 Example (Car): color, speed, mileage.
 In Java → represented by instance variables (fields).

Behavior (Methods / Functions)


 Represents what the object does.
 Example (Car): autoMode(), drift(), run().
 In Java → represented by methods.

Identity (Unique name / reference)


 Each object is uniquely identifiable in memory.
 Example (Car): car number (MH12AB1234) or
reference variable.
 In Java → represented by the object reference.

Instance Variable in Java


 An instance variable is a variable declared inside a
class but outside any method, constructor, or block.
 It belongs to the object (instance) of the class.
 For every new object created, a separate copy of
the instance variable is allocated in memory (Heap).
 Instance variables are object-level variables, stored
in heap, and each object gets its own copy.
Key Features of Instance Variables
 Declared inside a class, but not inside a method.
 Each object gets its own copy of instance variables.
 They are stored in the Heap memory (inside the
object).
 They have a default value (if not initialized):
int → 0
float → 0.0
boolean → false
object reference → null
 Accessed using object reference.
 It requires access modifier
When to Use Instance Variables?
 When you want each object to have its own state.
 Example: Different students with different id and
name.
 Example: Different cars with different color, speed,
and mileage.

Objects as First-Class Citizens


in Java
In Java, objects are treated as first-class citizens.
This means objects can be:

[Link] inside a variable


 You can assign an object to a reference variable.
Student s1 = new Student(); // object
stored in variable s1

[Link] as an argument to methods


 Methods can receive objects as parameters.
void printStudent(Student s) {
[Link]("ID: " + [Link] + ",
Name: " + [Link]);
}

[Link] from a method


 A method can return an object.
Student getStudent() {
Student s = new Student();
[Link] = 101;
[Link] = "Raju";
return s; // returning object
}

First-class citizen means → we can store, pass, and


return objects just like primitive types.
In Java:
✅ Objects can be stored in variables
✅ Objects can be passed to methods
✅ Objects can be returned from methods

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] Encapsulation is achieved in Java?


 Encapsulation is implemented using two rules:
 Declare variables as private (data hiding).
 Provide public getter and setter methods
(controlled access).

[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.

Scenarios that can Break


Encapsulation in Java
 Encapsulation means keeping fields private and
giving controlled access via methods.
 So, encapsulation is broken if we expose the
internal details directly.
✅ Common Scenarios that Break
Encapsulation:
1. Using public fields instead of private
class Student {
public int age; // ❌ Directly
accessible
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
[Link] = -100; // No control, breaks
encapsulation
}
}

 Since age is public, anyone can modify it without


restriction.
[Link] setters (no validation or
unrestricted access) ***
class Student {
private int age;

public void setAge(int age) {


[Link] = age; // ❌ No validation
}
}

 Technically encapsulated, but unsafe, since invalid


values can still be stored.
 This is weak encapsulation, not fully broken, but
risky.

[Link] internal mutable objects


directly
class Student {
private List<String> subjects = new
ArrayList<>();
public List<String> getSubjects() {
return subjects; // ❌ Returning
reference of internal object
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
List<String> subs = [Link]();
[Link]("Hacked!"); // ✅ We modified
internal state directly
}
}

 Here, encapsulation is broken because internal data


(subjects) is directly exposed.

✅ How to Fix It (Best Practices)


Option 1: Return a Copy (Defensive Copying)
class Student {
private List<String> subjects = new
ArrayList<>();

public List<String> getSubjects() {


return new ArrayList<>(subjects); //
✅ return copy
}

public void addSubject(String subject) {


[Link](subject); // controlled
modification
}
}

 Now, if someone does:


 List<String> subs = [Link]();
 [Link]("Hacked!");
 …it won’t affect the original subjects inside
Student.
Day-17
Constructor in Java
✅ What is a Constructor?
 A constructor is a special block of code similar to a
method.
 It is used to initialize an object (assign values to
data members / instance variables).
 Unlike methods, you do not call a constructor
explicitly → it is automatically invoked by the JVM
when an object is created.
 The JVM calls the constructor immediately after
object creation using the new keyword.
 You can have multiple constructors in a class
(Constructor Overloading).
 If you do not create a constructor, the JVM will
provide a Default Constructor (No-Arg
Constructor/Zero Parameterized) automatically.
✅ Rules of Constructor
 A constructor must be inside the class.
 Constructor name must be the same as the class
name (case-sensitive).
 A constructor does not have any return type (not
even void).

✅ 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.

this Keyword in Java


✅ What is this?
 “this” is a special keyword in Java.
 It works like a reference variable that is created
automatically by JVM.
 It always refers to the current class object (the
object on which the method or constructor is being
executed).
 You cannot declare or assign this yourself → it is
managed internally by JVM.

✅ Why do we need this?


 Sometimes, local variables and instance variables
have the same name. In such cases, this helps to
differentiate between them.
Constructor Chaining in Java
✅ What is Constructor Chaining?
 Constructor Chaining means calling one constructor
from another constructor within the same class or
between parent and child classes.
this() statement in Java
(Constructor Call)
✅ What is this()?
 this() statement is a special constructor call
statement in Java.
 It is used to call one constructor from another
constructor in the same class.
 This process is called Constructor Chaining (within
the same class).

✅ 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.

Types of Inheritance in Java


1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

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.

Object Class in Java


 In Java, Object is the root class of all classes.
 Every class in Java implicitly extends Object class (if
no other extends is specified).
 It belongs to the package [Link] (imported by
default).

Why Object class?


 Provides a common parent type for all classes.
 Defines some basic methods that every Java object
can use.
 Useful for generic programming (e.g., Collections
API stores Object references).
 Object Class Methods
 The Object class provides multiple methods which
are as follows:
toString() method
hashCode() method
equals(Object obj) method
finalize() method
getClass() method
clone() method
wait(), notify() notifyAll() (Concurrency
methods)

Inheritance & Related


Concepts in Java
1. Inherited Method
 A method that child class gets from the parent class
without redefining it.
 If not overridden, child directly uses parent’s
method.

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.

4. Diamond Shape Problem


 Occurs in multiple inheritance (when one class
inherits from two classes having same method).
 Java doesn’t support multiple inheritance with
classes to avoid this.
 But with interfaces, Java resolves conflict explicitly.
 If both B and C have same method, D will be
confused which one to inherit → ❌ Diamond
Problem.
 Java solves this by not allowing multiple
inheritance with classes.

5. Liskov Substitution Principle (LSP)


 One of SOLID principles.
 A child class must be substitutable for its parent
class without breaking program behavior.
 Inheritance should be logical and maintain the
relationship.

✅ 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
}

 Violates LSP → Ostrich is not a proper replacement


for Bird.
 Rule: Child should enhance parent, not contradict
it.

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

When to use IIB?


 To write common initialization code that all
constructors share.

Common Initialization Code


 If a class has multiple constructors, and all of them
share some common initialization logic → instead
of repeating that code inside every constructor, we
put it in an IIB.
 That way, the block runs before every constructor
automatically.
 Example:
class Student {
int id;
String name;
{ // Common initialization
[Link]("IIB: Welcome
Student!");
}
Student(int id) {
[Link] = id;
[Link]("Constructor 1");
}
Student(int id, String name) {
[Link] = id;
[Link] = name;
[Link]("Constructor 2");
}
public static void main(String[] args) {
new Student(101);
new Student(102, "Saif");
}
}
final Keyword in Java
 The final keyword in Java is a non-access modifier.
 It can be applied to:
 Variables
 Methods
 Classes
 Meaning: Once declared as final, it cannot be
changed, modified, or overridden (depending on
where it is used).

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

 Rules: Must be initialized at the time of declaration,


OR
 In a constructor, OR
 In an instance initializer block.

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

Method Inheritance &


Overriding in Java
1. Normal Instance Methods (non-final,
non-static, non-private)
 ✅ Inherited by child class.
 ✅ Can be overridden.
class Parent {
void show()
{ [Link]("Parent"); }
}
class Child extends Parent {
@Override
void show()
{ [Link]("Child"); }
}

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..."); }
}

7. Synchronized / Native Methods


 ✅ Behave like normal methods → inheritable and
overridable (unless declared final).
8. Methods from Object Class (toString(),
equals(), hashCode(), etc.)
 ✅ Inherited in all classes.
 ✅ Can be overridden.

✅ C++ supports but Java does


not:
 Multiple Inheritance (classes)
 Operator Overloading
 Pointers (explicit)
 Copy Constructor
 Destructors
 Goto statement
 Default arguments in functions
 Templates (powerful, unlike Java Generics)
 Struct with methods
 Storage classes (auto, register, extern, mutable)
 Global variables/functions
 Friend functions/classes
 Inline functions
 Multiple inheritance of constructors

this, this(), super, super() in


Java
1. this keyword
 Refers to the current object of the class.
 Used when local variables shadow instance
variables(Shadowing Problem)
 Used to pass the current object as a parameter.
 Used to return current object.
 Example:
class Student {
int age;
Student(int age) {
[Link] = age; // refers to
instance variable
}
}

✅ Uses of this:
To differentiate instance variable & local variable.
To pass current object as argument ([Link](this);).
To return current object (return this;).

2. this() constructor call


 Used to call another constructor of the same class.
 Must be the first statement in constructor.
 Helps in constructor chaining.
 Example:
class Student {
int age;
String name;
Student() {
this(20, "Default"); // calls 2nd
constructor
}
Student(int age, String name) {
[Link] = age;
[Link] = name;
}
}

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"); }
}

class Child extends Parent {


int num = 200;
void display() {
[Link]([Link]); // ✅
Parent variable
[Link](); // ✅
Parent method
}
}

4. super() constructor call


 Used to call parent class constructor.
 Must be the first statement in child class
constructor.
 If not written, compiler automatically inserts
super(); (default).
 Example:
class Parent {
Parent() {
[Link]("Parent
constructor");
}
}
class Child extends Parent {
Child() {
super(); // calls Parent constructor
[Link]("Child
constructor");
}
}

Access Modifiers in Java


 Access Modifiers in Java are keywords used to
define the scope (visibility) of classes, methods,
variables, and constructors. They control where
these members can be accessed from.

Types of Access Modifiers


Java provides 4 access levels:

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)
}
}

When is a protected member accessible?


 In Java, protected means:
 Within the same package → behaves like default
(package-private).
 Any class in the same package can access it directly.
 Outside the package → only accessible through
inheritance (via subclass).
 A subclass object can access the inherited protected
members inside its own class code.
 But you cannot access protected members directly
using the object reference outside the subclass.

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.

Where static Can Be Used


 Static Variables (Class Variables)
 Static Methods
 Static Blocks
 Static Nested Classes (LATER)

Static Variables/Class Variable


 Declared with the keyword static inside a class, but
outside methods/constructors/blocks.
 Shared by all objects of the class (only one copy
exists in memory).
 Stored in the Method Area (part of JVM memory).
 Used for: Common properties for all objects
 Example:
class Student {
private int rollNo;
private String name;
private static String college = "ABC
College"; // shared by all students
Student(int r, String n) {
rollNo = r;
name = n;
}
void display() {
[Link](rollNo + " " +
name + " " + college);
}
}

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.

Utility Class in Java


 A Utility Class in Java is a class that provides
common reusable methods or constants which can
be used across different parts of the application.
 Usually, the methods are static, so we don’t need
to create an object of the utility class.
 Utility classes are often made final with a private
constructor (to prevent instantiation).
 Java itself provides many utility classes:
o [Link] → utility methods for
working with collections (sort(), reverse(),
etc.)
o [Link] → utility methods for arrays
(sort(), binarySearch(), asList())
o [Link] → math operations (sqrt(),
pow(), PI)

Important Interview Points


Why is the main() Method Static in Java?
[Link] Entry Point
 When you run a Java program, the JVM needs an
entry point to start execution.
 JVM calls the main() method without creating an
object of the class.
 If main() were not static, JVM would have to create
an object first → but then it wouldn’t know which
constructor to call or what parameters to pass.
 Hence, main() is static so JVM can directly call it
using the class name.

[Link] Across Programs


 The JVM looks for a method with the exact
signature: public static void
main(String[] args)
 This standard ensures consistency across all Java
programs.
 If main() were not static, different programmers
might require different ways to start a program →
JVM would not have a standard entry point.

[Link] & Simplicity


 Calling a static method is faster and simpler for the
JVM.
 Avoids unnecessary object creation just to start the
program.
Can a constructor be static?
→ ❌ No, because constructors are used to initialize
objects, and static is class-level.

Can we override static methods?


→ ❌ No, static methods are hidden (method hiding),
not overridden.

Do Static Methods Get Inherited in Java?


 Yes, static methods are inherited by child classes.
 But they cannot be overridden (only hidden).
 Reason → Static methods belong to the class, not to
an object.
 Example of Inheritance
class Parent {
static void display() {
[Link]("Parent static
method");
}
}
class Child extends Parent {
// No display() here
}
public class Test {
public static void main(String[] args) {
[Link](); // ✅ Works,
inherited from Parent
[Link](); // ✅ Works
}
}

 Child inherited display() method from Parent.

Static Method Hiding (Not Overriding)


 If you define a static method with the same name
in the child class:
class Parent {
static void show() {
[Link]("Parent static
show()");
}
}

class Child extends Parent {


static void show() { // Hides Parent's
method
[Link]("Child static
show()");
}
}

public class Test {


public static void main(String[] args) {
[Link](); // Output → Parent
static show()
[Link](); // Output → Child
static show()

Parent p = new Child();


[Link](); // Output → Parent
static show() (NOT polymorphism)
}
}

 This is called method hiding, not overriding,


because polymorphism does not apply to static
methods.

Can abstract methods be static?


 ❌ No, abstract methods need overriding, static
cannot be overridden.

Can we declare interface methods static?


 ✅ Since Java 8, interfaces can have static methods.

Order of initialization:
 Static members/blocks → Instance members/blocks
→ Constructor

Printing a Reference in Java


1. What is a Reference?
 In Java, variables of class type (objects) store
references (addresses), not the actual object itself.
Example:
String s = new String("Hello");
 Here, s stores the reference (memory address) of
the "Hello" object on the heap.

2. Printing a Reference Variable


 When you try to print a reference variable (e.g.,
[Link](obj);), Java automatically calls
the object’s toString() method.
3. Behavior Without toString() Override
 If you don’t override toString() in your class, Java
uses the default implementation from Object class.
 Default format:
ClassName@HexadecimalHashCode
Example:
class Student {}
public class Test {
public static void main(String[] args) {
Student s1 = new Student();
[Link](s1);
}
}

Output (example):
Student@7a81197d

 Student → class name


 @7a81197d → hash code in hexadecimal form (not
real memory address, but based on the object’s
identity hash code).
4. Behavior With toString() Override
 If you override toString(), you can control how
objects are printed.
Example:
class Student {
String name;
int age;
Student(String name, int age) {
[Link] = name;
[Link] = age;
}
@Override
public String toString() {
return "Student{name='" + name + "',
age=" + age + "}";
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student("Saif",
25);
[Link](s1);
}
}

Output:
Student{name='Saif', age=25}

 Much more meaningful than default


ClassName@HashCode.

5. Why Override toString()?


 Improves readability of logs and debugging.
 Provides meaningful information instead of raw
hash codes.

Day-21
Polymorphism
The word Polymorphism comes from Greek:
 Poly → “many”
 Morphe / Morphism → “forms” or “shapes”
 So Polymorphism literally means “many forms”.

It means the same entity (method/ object) can perform


different behaviors in different situations.
It is one of the four pillars of OOP:
 Encapsulation
 Inheritance
 Abstraction
 Polymorphism ✅

In Java, polymorphism allows:


 One method name → many forms of
implementation.
 One object reference → multiple forms of actual
objects.
Types of Polymorphism in Java
Compile-Time Polymorphism (Static
Binding / Early Binding)
 Achieved by method overloading.
 Compiler decides which method to execute at
compile time.
 Decision is based on method signature (number,
type, order of parameters).
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Test {
public static void main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](5, 10));
// int version
[Link]([Link](5.5, 6.5));
// double version
[Link]([Link](1, 2, 3));
// three-parameter version
}
}

 Overloading = same method name + different


parameters.

Runtime Polymorphism (Dynamic Binding /


Late Binding/ Dynamic Method Dispatch)
 Achieved by method overriding.
 Method checking is done at compile time
depending on the reference Type but Method call is
decided at runtime, depending on the actual object.
 Requires inheritance + method overriding+
Upcasting.
Example:
class Animal {
void sound() {
[Link]("Animal makes
sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows");
}
}
public class Test {
public static void main(String[] args) {
Animal a1 = new Dog(); // reference
of Animal, object of Dog
Animal a2 = new Cat(); // reference
of Animal, object of Cat
[Link](); // Dog barks
[Link](); // Cat meows
}
}

 Method overriding gives different behaviors at


runtime.

Key Rules in Polymorphism


 Only methods are polymorphic. Variables are not.
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
}
public class Test {
public static void main(String[] args) {
Parent p = new Child();
[Link](p.x); // prints
10 (not polymorphic)
}
}

 Constructors cannot be overridden → no


polymorphism with constructors.
 Static methods are not polymorphic → they are
hidden, not overridden.
class Parent {
static void show()
{ [Link]("Parent static"); }
}
class Child extends Parent {
static void show()
{ [Link]("Child static"); }
}
public class Test {
public static void main(String[] args) {
Parent p = new Child();
[Link](); // Parent static (method
hiding)
}
}

 Final methods cannot be overridden → so no


runtime polymorphism.
 Private methods → not inherited, hence not
polymorphic.

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

Upcasting and Downcasting in


Java
1. Upcasting
 Converting a subclass type reference into a
superclass type reference.
 This happens automatically (implicit casting)
because every subclass object is-a superclass
object.
 Useful when we want to achieve runtime
polymorphism.
✅ Example:
class Animal {
void sound() {
[Link]("Animal makes a
sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
void fetch() {
[Link]("Dog is
fetching...");
}
}
public class Test {
public static void main(String[] args) {
// Upcasting: Dog → Animal
Animal a = new Dog(); // implicit
upcasting
[Link](); // ✅ Calls Dog’s
overridden method (runtime polymorphism)
// [Link](); // ❌ Not allowed
(reference type is Animal)
}
}

 Even though a refers to a Dog object, it can only


access methods defined in Animal (unless
overridden).
 Overridden methods are resolved at runtime
(dynamic method dispatch).

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
}
}

Wrong Downcasting Example (Exception):


 Animal a = new Animal();
 Dog d = (Dog) a; // ❌ Runtime error:
ClassCastException

Key Points:
Upcasting:
✔ Safe, automatic, used for polymorphism.
Downcasting:
✔ Explicit, sometimes necessary, but risky.

Use instanceof operator to avoid runtime errors before


downcasting.
✅ Example with instanceof:
if (a instanceof Dog) {
Dog d = (Dog) a;
[Link]();
}

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
}

3. Static Methods (Java 8+)


 Can be defined inside interface with
implementation.
 Example:
interface MathUtils {
static int add(int a, int b) {
return a + b;
}
}
4. Default Methods (Java 8+)
 Introduced to provide method implementation
inside interface (without breaking existing code).
 Classes can override them if needed.
 Example:
interface Printer {
default void print() {
[Link]("Default
printing...");
}
}

5. Private Methods (Java 9+)


 Used as helper methods inside interface (not
accessible outside).
 Example:
interface Helper {
private void log(String msg) {
[Link]("LOG: " + msg);
}
}

Why only public methods in


Interface?
 Interface = Contract / Standard
 An interface defines a standard (what must be
done), not how it is done.
 Since the purpose of an interface is to ensure that
any class implementing it must provide those
methods, those methods must be accessible
everywhere → hence they are always public.

If interface allowed private/protected


methods:
 private methods would never be visible to
implementing classes (useless).
 protected would restrict access only within the
package or subclasses, but the goal of an interface
is to be a universal contract, not limited access.
 That’s why Java enforces only public abstract
methods (though abstract and public are optional
keywords, they are implied).

Why only public static final


variables (constants) in
Interface?
 An interface is not an object, so it cannot hold
instance variables.
 If we allow normal variables, who would initialize
them? Interfaces can’t have constructors.
 To ensure consistency, variables in an interface are
always:
o public → accessible everywhere (just like
methods).
o static → belongs to the interface itself (no
object needed).
o final → treated as constants, value cannot be
changed.
 If variables inside an interface were not final, then
different classes could modify them.
 That would break the consistency of the contract —
imagine one implementing class changes the value
while another expects the old one.
 So, making them final ensures immutability → the
value never changes.
 This is why any variable inside an interface is a
constant.

Key Points About Interface


 Cannot create object of interface → only reference.
Vehicle v = new Car(); // allowed
(polymorphism)
Vehicle obj = new Vehicle(); // ❌ not
allowed

 A class implements an interface using implements


keyword.
class Car implements Vehicle { ... }
 An interface can extend another interface (multiple
allowed).
interface A {}
interface B extends A {}

 A class can extend one class and implement


multiple interfaces.
class MyClass extends Parent implements A, B
{ ... }

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.

Example without Interface (No


Standardization)
 Suppose you are building a system for payment
gateways.
 Each company may implement methods differently:
class Paytm {
void doPayment(double amount) { ... }
}
class PhonePe {
void makePayment(double amt) { ... }
}
class GooglePay {
void startPayment(double money) { ... }
}

❌ Problem:
 Method names are different (doPayment,
makePayment, startPayment).
 A client program cannot handle them in a common
way.
 Tight coupling, messy system.

Example with Interface (Standardization)


 Now, let’s introduce an interface:
interface Payment { //SPECIFICATION
void pay(double amount);
}
class Paytm implements Payment {
public void pay(double amount) {
[Link]("Payment of " +
amount + " through Paytm");
}
}
class PhonePe implements Payment {
public void pay(double amount) {
[Link]("Payment of " +
amount + " through PhonePe");
}
}
class GooglePay implements Payment {
public void pay(double amount) {
[Link]("Payment of " +
amount + " through GooglePay");
}
}

✅ 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);

Real-World Example of Standardization


 JDBC (Java Database Connectivity):
 Connection, Statement, ResultSet are interfaces.
 Oracle, MySQL, PostgreSQL drivers all implement
the same methods.
 Java developers just use the standard interface, not
worrying about which database is behind.

Why Standardization is Important?


 Ensures consistency → every implementation
follows same method signatures.
 Supports polymorphism → one interface reference
can point to different implementations.
 Makes code scalable and maintainable.
 Encourages loose coupling.
Coupling with
Interface
Coupling = The degree of dependency between two
classes/modules.
Two types:
 Tight Coupling → Classes depend directly on each
other.
 Loose Coupling → Classes depend on abstractions
(interfaces), not on concrete implementations.

[Link] Coupling (Bad Design)


 Here, one class creates/depends directly on
another class.
class DebitCard {
public void makePayment(double amount) {
[Link]("Payment of " +
amount + " using Debit Card");
}
}

class ShoppingMall {
private DebitCard card; // directly
dependent on DebitCard

public ShoppingMall(DebitCard card) {


[Link] = card;
}

public void purchase(double amount) {


[Link](amount); //
tightly coupled
}
}

public class Test {


public static void main(String[] args) {
DebitCard card = new DebitCard();
ShoppingMall mall = new
ShoppingMall(card);
[Link](500.0);
}
}

❌ Problem:
 If tomorrow we want to use UPI / Wallet, we must
change the ShoppingMall class code.
 Not flexible, not reusable.

[Link] Coupling (Good Design using


Interface)
 Here, we use an interface → ShoppingMall depends
only on Payment interface, not on specific card.
// Step 1: Create interface
(standardization)
interface Payment {
void pay(double amount);
}

// Step 2: Implementations
class DebitCard implements Payment {
public void pay(double amount) {
[Link]("Payment of " +
amount + " using Debit Card");
}
}

class Upi implements Payment {


public void pay(double amount) {
[Link]("Payment of " +
amount + " using Upi");
}
}

// Step 3: Client depends on Specification


class ShoppingMall {
private Payment payment; // depends on
interface, not class
public ShoppingMall(Payment payment) {
[Link] = payment;
}

public void purchase(double amount) {


[Link](amount); //
polymorphism
}
}

public class Test {


public static void main(String[] args) {
Payment payment = new Upi(); // or
new DebitCard()
ShoppingMall mall = new
ShoppingMall(payment);
[Link](1000.0);
}
}
✅ Advantage:
 Tomorrow, if a new class UPI or Wallet is created →
No need to modify ShoppingMall.
 Just pass the new object → open/closed principle
(OOP SOLID principle).
 Code is flexible, maintainable, scalable.

Why Loose Coupling is Good?


 Flexibility → Swap implementations without
changing dependent class.
 Maintainability → Easy to update/extend system.
 Reusability → Classes can be reused in different
contexts.
 Testability → Easier to mock dependencies in unit
testing.
 Scalibility  Easy to add any new Implementations

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();
}

// ✅ Class can implement multiple


interfaces
class C implements A, B {
public void show() {
[Link]("show() from A");
}
public void display() {
[Link]("display() from
B");
}
}

public class Test {


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

 Here class C is achieving multiple inheritance (from


A and B).

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

How does it work? Who uses it?


 JVM and Frameworks use marker interfaces
internally.
 When you implement a marker interface, you’re
telling the JVM / API that this class has a special
ability.
 Example : SerializableMarks that an object can be
converted into a stream of bytes.
 Used during file I/O, network transfer, caching, etc.

Advantages of Interface
Achieves 100% abstraction (before Java 8).
Supports multiple inheritance.
Improves loose coupling and flexibility.
Helps in scalability.

✅ So the final takeaway:


Interface = contract/blueprint.
Used for standardization + abstraction + loose
coupling.
Supports default, static, and private methods (Java
8+).
Enables multiple inheritance in Java.
Marker interfaces are special tagging interface.

✅ 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.

Abstraction using Interface in


Java
 An interface in Java is a special type that is used to
achieve abstraction.
 It defines a contract (what should be done), but not
the implementation (how it’s done).
 A class that implements an interface must provide
the implementation of all abstract methods.
 Interface = 100% Abstraction (before Java 8)

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.

Factory Design Pattern in Java


 The Factory Design Pattern is a creational design
pattern that provides a way to create objects
without exposing the creation logic to the client.
 Instead of using the new keyword directly, we use a
factory class/method to create objects.
In simple words:
 Factory pattern hides the object creation process
and allows the client to work with an interface or
abstract class instead of concrete classes.
 Example:
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");
}
}

class Square implements Shape {


public void draw() {
[Link]("Drawing
Square");
}
}

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;
}
}

public class FactoryPatternDemo {


public static void main(String[] args) {
ShapeFactory shapeFactory = new
ShapeFactory();

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.

You might also like