KEMBAR78
Object Oreinted Programming | PDF | Object Oriented Programming | Class (Computer Programming)
0% found this document useful (0 votes)
56 views341 pages

Object Oreinted Programming

This document outlines the syllabus and evaluation pattern for an Object-Oriented Programming (OOP) course, including key textbooks and reference materials. It covers fundamental concepts such as the object-oriented paradigm, UML diagrams, and properties of object-oriented systems, along with course outcomes and lab schedules. The document also provides insights into object-oriented analysis and design, encapsulation, inheritance, and polymorphism, along with examples of class diagrams and their applications.

Uploaded by

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

Object Oreinted Programming

This document outlines the syllabus and evaluation pattern for an Object-Oriented Programming (OOP) course, including key textbooks and reference materials. It covers fundamental concepts such as the object-oriented paradigm, UML diagrams, and properties of object-oriented systems, along with course outcomes and lab schedules. The document also provides insights into object-oriented analysis and design, encapsulation, inheritance, and polymorphism, along with examples of class diagrams and their applications.

Uploaded by

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

OBJECT ORIENTED

PROGRAMMING
UNIT-1
Subject Code: 23CSE111
L-T-P-C (Lecture, Tutorial, Practical, and Credit) : 3-0-2-4

By
Dr. Raj Kumar Batchu
Books to Follow
Textbook(s)
• Y.Daniel Liang, “Introduction to Java Programming”, Tenth Edition, PHI, 2013.
• Grady Booch and Robert A. Maksimchuk, “Object-oriented Analysis and Design with
Applications”, Third Edition, Pearson Education, 2009.

Reference(s)
• Naughton P. and Schildt H., “Java2 Complete Reference”, Eighth Edition, Tata McGraw-
Hill, 2011.
• Ali Bahrami, “Object Oriented Systems Development”, Second Edition, McGraw-Hill,2008.
• Jaime Nino, Fredrick A Hosch, “An Introduction to Programming and Object Oriented Design
using Java”, Wiley India Private Limited, 2010.
Evaluation Pattern
Assessment Internal External
Mid Term 20
*Continuous Assessment (Theory) 10
(CAT)

Continuous Assessment (Lab) (CAL) 40


End Semester 30

*CA – Can be Quizzes, Assignment, Projects, and Reports


Course Outcomes
• CO1: Understand Object Oriented paradigm and represent the
problem using objects and classes.
• CO2: Apply the Object Oriented concepts to design and develop
effective models using UML.
• CO3: Develop program logic in Java from design models in UML.
• CO4: Design applications with procedural and data abstraction using
Java libraries.
23CSE111 - OOP Lab Manual dates for II CSE A,B,C Sections

S.No Week Sec A Dates Sec B Dates Sec C Dates

1 1 27/1/2025 29/1/2025 24/01/2025


2 2 10/2/2025 12/2/2025 31/01/2025
3 3 24/2/2025 19/2/2025 07/02/2025
4 4 03/3/2025 05/3/2025 21/02/2025
5 5 10/3/2025 12/3/2025 28/02/2025
6 6 29/3/2025 26/3/2025 07/03/2025
7 7 14/4/2025 02/4/2025 28/03/2025
8 8 21/4/2025 09/4/2025 11/04/2025
9 9 26/4/2025 16/4/2025 12/04/2025
10 10 02/6/2025 30/4/2025 25/04/2025
Syllabus

Unit 1:
Structured to Object Oriented Approach by Examples - Object Oriented
languages - Properties of Object Oriented system – UML and Object Oriented
Software Development - Use case diagrams and documents as a functional
model - Identifying Objects and classes - Representation of Objects and its state
by Object Diagram - Simple Class using class diagram – Encapsulation - Data
Hiding - Reading and Writing Objects - Class Level and Instance Level
Attributes and Methods- JIVE environment for debugging.
Object-Oriented Paradigm
• The Object-Oriented Paradigm is a programming paradigm that uses objects and
classes as the fundamental building blocks for designing and organizing software
systems.

• It focuses on modeling real-world entities, their attributes, and their interactions to


create modular, reusable, and maintainable code.

• In the context of Object-Oriented Programming (OOP), a paradigm refers to a


fundamental and overarching approach for designing and structuring software
systems. It encompasses a set of principles, concepts, and practices that guide how
you model, organize, and interact with entities in your code.
Structured to Object Oriented Approach by
Examples
• The structured programming approach focuses on breaking
down a problem into smaller, manageable components called
functions or procedures.
• These functions operate on data using control structures like
loops and conditionals.
• However, as systems grow in complexity, structured programming
(Pascal, ALGOL, C, Modula-2, etc) can lead to difficulties in
managing the codebase, especially when changes are needed.
• Object-Oriented Programming, is a different approach to programming that
brings together data and functions that execute on them.
• It basically supports encapsulation, abstraction, inheritance, polymorphism, etc.
• It also includes data hiding feature therefore it is more secure.
• It performs well in situation where systems are undergoing continuous design,
adaption, and maintenance.
• Ex: Java, C++, C#, Python, Simula (First OO), Smalltalk (First pure OO).

The OO model is beneficial in the following ways −


• It facilitates changes in the system at low cost.
• It promotes the reuse of components.
• It simplifies the problem of integrating components to configure large system.
• It simplifies the design of distributed systems.
C (Structured) Java (Object Oriented)
int add(int a, int b) { class Calculator {
return a + b; int add(int a, int b) {
} return a + b;
int main() { } }
int result = add(3, 4); public class Main {
printf("%d", result); public static void main(String[] args) {
return 0; Calculator c = new Calculator();
} System.out.println(c.add(3, 4));
} }
Object-Oriented Analysis and Design (OOAD)
Approach
• Object-Oriented Analysis and Design (OOAD) is a methodology for
designing and modeling software systems using object-oriented concepts.

• In OOAD, you not only focus on coding but also on the overall system design,
requirements analysis, and architecture.

• The transition from a structured approach to OOAD involves identifying objects,


their attributes, methods, interactions, and the overall structure of the system.

• This analysis lays the foundation for a well-organized and maintainable codebase.
Object-Oriented Approach

• The object-oriented programming (OOP) approach aims to organize


code around the concept of objects, which are instances of classes.
• Each class defines both data (attributes) and behaviors (methods)
that are related to a specific concept.
• This approach promotes encapsulation, inheritance, and
polymorphism, leading to more modular and maintainable code.
Object Oriented Languages
 Object-oriented programming (OOP) languages are programming languages that are
based on the concepts of objects, which encapsulate data and behavior. Here are
some of the most common object-oriented programming languages:
 Java: A general-purpose, high-level programming language that is designed to have
as few implementation dependencies as possible. Java is known for its "write once,
run anywhere" approach, where code written for Java can run on any device that
supports Java without the need for recompilation.
 C++: An extension of the C programming language that adds support for object-
oriented programming. C++ is known for its performance and efficiency, as well as
its ability to be used for both high-level and low-level programming.
 C#: A general-purpose, multi-paradigm programming language developed by
Microsoft. C# is designed for use in developing software components suitable for
deployment in distributed environments.
 Python: A high-level, interpreted programming language known for its simplicity
and readability. Python supports multiple programming paradigms, including
object-oriented, imperative, functional, and procedural.
 Ruby: An object-oriented programming language known for its simplicity and
flexibility. Ruby is often used in web development due to its web application
framework, Ruby on Rails.
 Swift: A general-purpose, compiled programming language developed by Apple
for use in developing applications for Apple's platforms, including macOS, iOS,
watchOS, and tvOS.
 Objective-C: A general-purpose, object-oriented programming language that is a
superset of the C programming language. Objective-C is used primarily by Apple
for macOS and iOS application development.
Useful Links:
1.Object-Oriented Programming (OOP) Concepts
2.Object-Oriented Analysis and Design (OOAD)
3.Introduction to Object-Oriented Programming
4.Object-Oriented Analysis and Design Concepts
5.Structured Programming vs. Object-Oriented Programming
https://blog.algomaster.io/p/uml-class-diagram-
explained-with-examples
Properties of Object Oriented system

• Object
• Class

 Inheritance
 Polymorphism
 Data Abstraction
 Encapsulation
 Modularity
 Dynamic Binding
 Message Passing
 Data Hiding
Object
• Any entity that has state and behavior is known as an object.
• Example: a chair, pen, table, keyboard, bike, etc.
• It can be physical or logical.
• An Object can be defined as an instance of a class. An object contains an address
and takes up some space in memory.
• Example: A dog is an object because it has states like color, name, breed, etc. as well
as behaviors like wagging the tail, barking, eating, etc.
Class
• Collection of objects is called class. It is a logical entity.
• A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Inheritance
• When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
• If one task is performed in different ways, it is known as polymorphism.
• For example: to convince the customer differently, to draw something, for
example, shape, triangle, rectangle, etc.
• In Java, we use method overloading and method overriding to achieve
polymorphism.
• Another example can be to speak something; for example, a cat speaks meow,
dog barks, woof, etc.
• A person at the same time can have different characteristics. Like a man at the
same time is a father, a husband, an employee. So the same person posses
different behavior in different situations. This is called polymorphism.
Abstraction
• Hiding internal details and showing functionality is known as abstraction.
(or)
• It refers to providing only essential information about the data to the outside world,
hiding the background details or implementation.
For example
 phone call - we don't know the internal processing.

 Man driving a car - The man only knows that pressing the accelerators will increase
the speed of the car or applying brakes will stop the car, but he does not know about
how on pressing the accelerator the speed is increasing, he does not know about the
inner mechanism of the car or the implementation of the accelerator, brakes, etc in
the car.
Encapsulation
• Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.

• In Encapsulation, the variables or data of a class are hidden from any other class
and can be accessed only through any member function (method) of their class in
which they are declared.
• As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.
// Class to demonstrate encapsulation if (age > 0) {
class Student { this.age = age;
// Private data members } else {
private String name; System.out.println("Age must be positive.");
private int age; } }}
// Public getter method for name
public String getName() { public class EncapsulationExample {
return name; public static void main(String[] args) {
} Student student = new Student();
// Public setter method for name // Setting values using setter methods
public void setName(String name) { student.setName(“Raj");
this.name = name; student.setAge(33);
} // Getting values using getter methods
// Public getter method for age System.out.println("Student Name: " + student.getName());
public int getAge() { System.out.println("Student Age: " + student.getAge());
return age; }}
} Output:
// Public setter method for age Raj
public void setAge(int age) { 33
• Example - In a company, there are different sections like the accounts section, finance section,
sales section, etc.

• The finance section handles all the financial transactions and keeps records of all the data
related to finance. Similarly, the sales section handles all the sales-related activities and keeps
records of all the sales.

• Now there may arise a situation when for some reason an official from the finance section
needs all the data about sales in a particular month. In this case, he is not allowed to directly
access the data of the sales section.

• He will first have to contact some other officer in the sales section and then request him to
give the particular data. This is what encapsulation is. Here the data of the sales section and
the employees that can manipulate them are wrapped under a single name “sales section”.
Benefits
 Modularity: Modularity is the process of dividing a system into smaller, more
manageable parts, known as modules. This allows for better organization and
reusability of code.

 Dynamic Binding: Dynamic binding is the process of linking a method call to its
corresponding implementation at runtime. This allows for more flexibility in the
behavior of objects.

 Message Passing: Message passing is the mechanism by which objects


communicate with each other. This is typically achieved through the use of
method calls.

 Data Hiding: Data hiding is the process of restricting access to certain data
within an object, allowing for better control over the use and modification of data.
UML Diagrams
1. https://www.visual-paradigm.com/guide/uml-unified-modeling-language
2. https://www.lucidchart.com
What is UML?
• UML stands for Unified Modelling Language.
• It is a industry-standard graphical language for specifying, visualizing,
constructing, and documenting the artifacts of software systems, business
modeling and other non-software systems.
• The UML represents a collection of best engineering practices that have proven
successful in the modeling of large and complex systems.
• It uses mostly graphical notations to express the analysis and design of software
projects.
• It helps project teams communicate, explore potential designs, and validate the
architectural design of the software.
• It is not dependent on any one language or technology.
Goal of UML?
• A picture is worth a 1000 words.
• It defines some general purpose modelling language, which all
modellers can use and it also needs to be made simple to understand
and use.
• UML diagrams are not only made for developers but also for
business users, common people, and anybody interested to
understand the system.
• It is not a development method rather it accompanies with processes
to make it a successful system.
Overview of UML Diagrams
Behavioral
Structural
: behavioral features of a system / business process

: element of spec. irrespective of time


• Activity
• State machine
• Class • Use case
• Component • Interaction
• Deployment
• Object
• Composite structure
Interaction
: emphasize object interaction
• Package
• Communication(collaberati
on)
• Sequence
• Interaction overview
• Timing
Class diagram
• UML class diagrams show the classes of the
system, their inter- relationships, and the operations
and attributes of the classes
• Explore domain concepts in the form of a domain
model.
• Analyze requirements in the form of a
conceptual/analysis model.
• Depict the detailed design of object-oriented or
object-based software.
Class representation in UML
Inheritance / Generalization
Class representation in UML

• Underline - static attribute/method


• +,-,# - access specifiers
• Method with same name as class – constructor
• Italic – abstract class
Class diagram Example
Hospital management system

Classes
1. Patient
o Attributes: patientId, name, age, gender
o Methods: bookAppointment()
2. Doctor
o Attributes: doctorId, name, specialization
o Methods: checkPatient()
3. Appointment
o Attributes: appointmentId, date, time
o Methods: confirmAppointment()

Relationships:
Association, Aggregation , Composition , Inheritance
Component diagram
• A component diagram is used to break down a large object-oriented system
into the smaller components, so as to make them more manageable.
• It visualizes the relationships as well as the organization between the
components present in the system. It helps in forming an executable system.
• The term "component" refers to a module of classes that represent
independent systems or subsystems, which can interact with other parts of
the system.
• In this approach, component diagrams help planners recognize system
components, ensuring everything functions as expected.
• In object-oriented programming, a component diagram helps a senior
developer organize related classes by their purpose, providing a high-level
overview of the software project.
• A single component diagram cannot represent the entire system but a
collection of diagrams is used to represent the whole.
• Each component is responsible for one clear goal within the entire
system.
• It is like a black box whose behavior is explained by the provided and
required interfaces.
Benefits of component diagrams
These are invaluable while building your system. Component diagrams can
help your team:
• Imagine the system’s physical structure.
• Pay attention to the system’s components and how they relate.
• Emphasize the service behavior as it relates to the interface.
Provided interfaces: A straight line from the component box with
an attached circle. These symbols represent the interfaces where a
component produces information used by the required interface of
another component.
Required interfaces: A straight line from the component box with
an attached half circle. These symbols represent the interfaces where
a component requires information in order to perform its proper
function.
Dependency: Shows that one part of your system depends on
another. Dependencies are represented by dashed lines linking one
component (or element) to another.
Component: A component provides and consumes behavior
through interfaces, as well as through other components. Think of
components as a type of class.
Port Symbol: Ports are represented using a square along the edge
of the system or a component. A port is often used to help expose
required and provided interfaces of a component.
• In the diagram below, each
component is enclosed in a
small box.
• The dotted lines with arrows
show how some components
are dependent on others.
• For example, the card reader,
web page, client desktop, and
ATM system are all dependent
on the bank database.
• The dotted lines with circles
at the end, known as
“lollipop” symbols, indicate a
realization relationship.

Example: Component diagram for an ATM system


Example: Component diagram for a library management system
Example: Component Diagram for an Online Order System

A typical Online Order System might include the following components:


•User Interface (UI): Manages user interactions.
•Order Processing Service: Handles order placement and validation.
•Payment Gateway: Manages transactions.
•Inventory Management: Updates stock levels.
•Database: Stores customer, product, and order information.

Example relationships:
•The UI Component communicates with the Order Processing Component.
•The Order Processing Component interacts with the Payment Gateway and
Inventory Management.
•The Database Component stores order details, customer data, and product inventory.
Deployment diagram
• UML deployment diagram depicts a static view of the run-time
configuration of hardware nodes and the software components that
run on those nodes.
• Deployment diagrams show the hardware for your system, the
software that is installed on that hardware, and the middleware used to
connect the disparate machines to one another.
You can use Deployment diagrams to:
• Show which software elements are deployed by which hardware
elements.
• Illustrate the runtime processing for hardware.
• Provide a view of the hardware system’s topology.
When to use a Deployment Diagram?
• The deployment diagram is mostly employed by network engineers,
system administrators, etc. with the purpose of representing the
deployment of software on the hardware system.
• It envisions the interaction of the software with the hardware to
accomplish the execution. The selected hardware must be of good
quality so that the software can work more efficiently at a faster rate
by producing accurate results in no time.
• The software applications are quite complex these days, as they are
standalone, distributed, web-based, etc. So, it is very necessary to
design efficient software.
Node: A hardware or software object, shown by a three-dimensional box.

Artifact: A product developed by the software, symbolized by a rectangle


with the name and the word “artifact” enclosed by double arrows.
Component: A rectangle with two tabs that indicates a software element.

Association: A line that indicates a message or other type of communication


between nodes.
Package: A file-shaped box that groups together all the device nodes to
encapsulate the entire deployment.
Node as container: A node that contains another node inside of it—such as
in the example, where the nodes contain components.

Stereotype: A device contained within the node, presented at the top of the
node, with the name bracketed by double arrows << >>.
Deployment diagram Example
This example shows a basic deployment diagram.
There is a web server, a database server, and the
machine where the user views the website.
• Green Dotted Lines: Indicate the flow
of information and requests:
 The individual machine connects to
both servers to send mortgage
applications and retrieve listings.
 The Bank Server processes
mortgage applications and may send
back confirmations or requests for
more information.

• TCP/IP: This representation at the


bottom suggests that the communication
between the individual machine and the
servers is facilitated over the internet
using the TCP/IP protocol.
Real estate and mortgage application system
Object diagram
• A UML object diagram represents a specific instance of a class diagram at a
certain moment in time.
• An object diagram focuses on the attributes of a set of objects and how those
objects relate to each other.
• It shows instances instead of classes. They are useful for explaining small
pieces with complicated relationships, especially recursive relationships.
Purpose of Object Diagram
• During the analysis phase of a project, you might create a class diagram to
describe the structure of a system and then create a set of object diagrams as
test cases to verify the accuracy and completeness of the class diagram.
• Before creating a class diagram, you can use an object diagram to identify
details about specific model elements and their relationships.
Basic Object Diagram Symbols and Notations
Object diagram
• This small class diagram shows that a university Department can contain lots of
other Departments and the object diagram below instantiates the class diagram,
replacing it by a concrete example.

Class Diagram

Object Diagram
Class to Object Diagram Example - Order System

Generalization: A relationship in which one model element


(the child) is based on another model element (the parent).
• Class diagrams show the actual
classifiers and their relationships in a
system
• Object diagrams show specific instances
of those classifiers and the links
between those instances at a point in
time.

implying that a writer can create documents.


Output:
Identifying Objects and classes - Representation of Objects
and its state by Object Diagram
• When identifying objects and representing them using object diagrams, you are essentially
capturing the structure and behavior of objects within a system. This approach helps to model
how objects interact and collaborate to fulfill the functionalities of the system. Here's how to
identify objects, represent them with state and behavior, and create object diagrams:
Identifying Objects:
• Problem Domain Understanding: Understand the problem domain and the system's requirements
to identify
the real-world entities that need to be represented as objects.
• Real-World Entities: Identify the main entities, concepts, or things that play a role in the
system. These entities will become objects in your model.
Defining State and Behavior:
• Attributes (State): For each identified object, determine its attributes (data) that
describe its current state. Attributes are properties that characterize the object.
• Methods (Behavior): Define the methods (functions or behaviors) that the object can perform.
These methods represent the actions the object can take.
Identify Objects:
Book
Member
Librarian

Define State and Behavior:


Book:
State (Attributes): Title, Author, ISBN
Behavior (Methods): Borrow, Return

Member: Librarian:
State (Attributes): Name, Member ID State (Attributes): Name, Employee ID
Behavior (Methods): Borrow Book, Return Book Behavior (Methods): Manage Inventory, Process Returns
Package diagram
• A package is a collection of logically related UML elements. Packages
are depicted as file folders and can be used on any of the UML diagrams.
• It contains classes, interfaces, and other elements that belong to the same
group.

The below is a business model in which the classes are grouped into packages:
• Packages appear as rectangles with small tabs at the top.
• The package name is on the tab or inside the rectangle.
• The dotted arrows are dependencies.
• One package depends on another if changes in the other could possibly force
changes in the first.
Dependency notations in a package diagram
• Package diagrams are used, in part, to depict import and access dependencies between
packages, classes, components, and other named elements within your system.
• Each dependency is rendered as a connecting line with an arrow representing the type
of relationship between the two or more elements.
Access: Indicates that one package Import: Indicates that functionality
requires assistance from the has been imported from one package
functions of another package. to another.

There are few constraints while using package diagrams, they are as follows.
 Package name should not be the same for a system, however classes inside different
packages could have the same name.
 Packages can include whole diagrams, name of components alone or no
components at all.
 Fully qualified name of a package has the following syntax.
Package Diagram
Behavioral - Activity diagram
• Activity diagrams help people on the business and development sides of an
organization to understand the same process and behavior.
• It represent the flow from one activity to another activity. The activity can be
described as an operation of the system.
• The flow of an activity can be parallel, branched and concurrent.
• Activity diagrams deal with all type of flow control by using different elements
such as fork, join, etc.
• The main purpose is to capture the dynamic behavior of the system.
The diagram is drawn with the four main activities of order management system −
Send order by the customer
Receipt of the order
Confirm the order
Dispatch the order
Activity diagram
Activity diagram can be used for –
 Modeling work flow by using activities.
 Modeling business requirements.
 High level understanding of the system's
functionalities.
 Investigating business requirements at a
later stage.
This diagram shows the process of either
withdrawing money from or depositing
money into a bank account. An
advantage of representing the workflow
visually in UML is the ability to show
withdrawals and deposits on one chart.
State machine diagram
• State machine diagrams can show the different states of an object also how an object
responds to various events by changing from one state to another.
• They define different states of an object during its lifetime and these states are changed
by events.
• States are defined as a condition in which an object exists and it changes when some
event is triggered.
Before drawing a State chart diagram we should clarify the following points ---
• Identify the important objects to be analyzed.
• Identify the states.
• Identify the events.

Key Elements of a State Machine Diagram


1. States - Represents different conditions an object can be in.
Example: In a Login System, states could be Idle, Entering Credentials, and Authenticated.
1.Transitions
Shows movement from one state to another due to an event.
Example: Clicking the "Login" button moves from Entering Credentials → Authenticated.
2.Initial State
The starting point of the system. Represented by a filled black circle (•).
3.Final State
The end condition of the system. Represented by a black circle with an outer ring.
4.Events/Triggers
Conditions that cause a transition between states.
Example: User enters a correct password → Moves to "Authenticated" state.
5.Conditions
Optional conditions that must be met before a transition occurs.
Example: "User enters correct PIN" → Unlocks account.
6.Composite States
A state that contains sub-states inside it.
Example: A "Processing Order" state might contain "Validating Payment" and "Packaging
Items".
State machine diagram for order object

Characteristics of State
• State represent the
conditions of objects
at certain points in
time.
• Objects (or Systems)
can be viewed as
moving from state to
state
State machine diagram to check in at an airport
Use cases diagram
• An Use Case Diagram represents the interaction between actors (users or external
systems) and a system under consideration to accomplish specific goals.
• It provides a high-level view of the system’s functionality by illustrating the various
ways users can interact with it.
• Use cases. These are like scenes in the play. They represent specific things your
system can do. In the online shopping system, examples of use cases could be
“Place Order,” “Track Delivery,” or “Update Product Information”. Use cases are
represented by ovals.
• Actors. An actor is a person, organization, or external system that uses our system to
achieve a goal. Actors are drawn as stick figures.
• Associations.Associations between actors and use cases are indicated by solid
lines. An association exists whenever an actor is involved with an interaction
described by a use case.
System Boundary
The system boundary is a visual representation of the scope or limits of the system you are
modeling. It defines what is inside the system and what is outside. Ex: Whatever you’re
developing, it can be a website, software component, business process, app, etc.

Purpose of Use Case Diagram


Use case diagrams are typically developed in the early
stage of development
• Specify the context of a system
• Capture the requirements of a system
• Validate a systems architecture
• Drive implementation and generate test cases
• Developed by analysts together with domain experts
Relations:
<<include>> - every time
<<extend>> - some times
Generalization
Use case diagram to
publish a book
Use case diagram for
Railway reservation
Interaction - Sequence diagram
• An interaction diagram is used to show the interactive behavior of a
system. Since visualizing the interactions in a system can be difficult,
we use different types of interaction diagrams to capture various
features and aspects of interaction in a system.
• Sequence Diagrams are interaction diagrams that detail how
operations are carried out. They capture the interaction between
objects in the context of a collaboration.
• Sequence Diagrams are time focus and they show the order of the
interaction visually by using the vertical axis of the diagram to
represent time what messages are sent and when.
Actors: An actor represents an external entity that interacts with the system
being modeled. This can be a user, another system, or any other entity that sends
or receives messages to/from the system. Actors help identify the boundary
between the system and its environment.
Sequence diagram of a
hospital management system
Sequence diagram for ATM
systems

Lifeline
Communication diagram
• It is a kind of interaction diagram, shows how objects interact.
• A communication diagram is an extension of object diagram.
• It offers the same information as a sequence diagram, but a communication diagram
emphasizes the messages exchanged between objects in an application.
• It offers the broader perspective within a process.
The symbols and notations used in communication diagrams are the same notations
for sequence diagrams.
• Rectangles represent objects that make up the application.
• Lines between class instances represent the relationships between different parts of
the application.
• Arrows represent the messages that are sent between objects.
• Numbering lets you know in what order the messages are sent and how many
messages are required to finish a process.
Communication diagram to
add an event to a calendar

 Even in simple examples like


this one, you’ll notice the
exact commands and requests
being shared between various
steps in the process.
 The numbers on each line
represent the order and
options in which they are
activated.
Timing diagram
• Think of a timing diagram as an inverted sequence diagram.
• It consists of a graph or waveform that depicts the state (class/object) of a lifeline
at a specific point of time.
• In a timing diagram, time passes on the x-axis from left to right, with different
components of the system that interact with each other on the y-axis.
• Timing diagrams show how long each step of a process takes. Use them to
identify which steps of a process require too much time and to find areas for
improvement.
• With timing diagrams, you can easily diagram a process and identify the major
steps it takes to complete the process.
• First, identify the major participants in the process. If you were to create a timing
diagram for a factory, you would identify departments such as design, sourcing,
manufacturing, QA, shipping, etc.
Boat manufacturing timing diagram example

• A timing diagram shows that too


much time is spent on the
upholstery stages of production.
As a result, factory administrators
may assign more employees to
the upholstery stations or seek out
ways to increase efficiency.
• If administrators can effectively
use a timing diagram to increase
efficiency, the process can be
significantly improved,
decreasing both time and money
spent on the process.
Interaction diagrams can be used −
o To model the flow of control by time sequence.
o To describe the message flow in the system
o To model the flow of control by structural organizations.
o For forward engineering.
o For reverse engineering.
UML diagram hierarchy
UML and Object Oriented Software Development
• The Unified Modeling Language (UML) is a standardized visual language used for
modeling and designing software systems, particularly those that follow object-oriented
principles. UML provides a set of diagrams and notations that help developers
communicate, visualize, and document various aspects of a software system's
architecture, structure, behavior, and interactions.
• UML Diagram Types Relevant to Object-Oriented Software Development:
• Class Diagrams: These diagrams depict the static structure of a system, showing classes,
their attributes, methods, relationships, and inheritance hierarchies.
• Object Diagrams: Object diagrams provide a snapshot of instances of classes at a
specific point in time, illustrating how objects interact and collaborate.
• Sequence Diagrams: Sequence diagrams showcase interactions between objects over
time, detailing the order of method calls and the messages exchanged.
• State Diagrams: State diagrams model the behavior of objects as they transition between
different states in response to events.
• Activity Diagrams: Activity diagrams represent the flow of activities or processes within
a system, aiding in the understanding of workflows.
• UML plays a vital role in object-oriented software development by providing a standardized way
to represent, communicate, and design complex systems using visual models. UML diagrams aid
in both the analysis and design phases of software development:
Analysis Phase: During the analysis phase, UML diagrams help to:
• Identify classes, attributes, and methods based on real-world entities.
• Define relationships between classes, such as associations, aggregations, and compositions.
• Model use cases to capture system functionality from a user's perspective.
• Visualize the requirements and interactions of the system.
Design Phase: In the design phase, UML diagrams help to:
• Create detailed class diagrams that guide the implementation process.
• Illustrate dynamic interactions using sequence and collaboration diagrams.
• Model the flow of activities and processes using activity diagrams.
• Represent the transitions of objects between different states using state diagrams.
• communicate and collaborate effectively throughout the software development lifecycle.
• Interrelation between UML and Object-Oriented Software Development:
• UML acts as a bridge between the conceptual understanding of a software system
(during analysis) and its practical implementation (during design and coding) in an
object-oriented manner. UML diagrams provide a shared language for developers,
designers, and stakeholders to communicate and collaborate effectively throughout
the software development lifecycle.
• Useful Links:
• UML Basics
• Object-Oriented Design Concepts
• UML in Object-Oriented Analysis and Design
• UML Class Diagram Tutorial
• UML Sequence Diagram Tutorial
• Object-Oriented Languages are programming languages designed to support and facilitate the
principles of Object-Oriented Programming (OOP). These languages provide features that enable
the creation, manipulation, and interaction of objects, which are instances of classes representing
real-world entities. The key features of object-oriented languages include:
• Classes and Objects: Object-oriented languages allow you to define classes, which are blueprints
for creating objects. Objects encapsulate both data (attributes) and behavior (methods) related to a
particular entity.
• Encapsulation: It refers to integrating data (variables) and code (methods) into a single unit. In
encapsulation, a class's variables are hidden from other classes and can only be accessed by the
methods of the class in which they are found.
• Inheritance: Inheritance allows you to create new classes based on existing classes, inheriting
their attributes and behaviors. It promotes code reuse and hierarchy among classes.
• Polymorphism: Polymorphism enables objects of different classes to be treated as
instances of a common superclass, allowing for flexibility and dynamic behavior.
• Abstraction: It is the process of hiding the implementation details of a class and only
showing the necessary features of the object. It helps to reduce complexity and increase
efficiency by allowing you to focus on the essential aspects.
Inheritance
Polymorphism
Abstraction
Useful Links:

1.List of Object-Oriented Programming Languages


2.Introduction to Object-Oriented Programming
3.Object-Oriented Analysis and Design
4.Comparison of Programming Paradigms
5.Choosing the Right Programming Language
Properties of Object Oriented system
The following are the key properties of object-oriented systems:
Encapsulation:
• Encapsulation is one of the four fundamental OOP concepts in Java, alongside
inheritance, polymorphism, and abstraction.
• It is the process of wrapping data (variables) and code (methods) together into a
single unit, which is known as a class.
• Encapsulation allows the programmer to control the access to data, preventing
unauthorized access or modification.
Note: It helps to achieve data hiding
 People often consider encapsulation as data hiding, but that's not entirely true.
 Encapsulation refers to the bundling of related fields and methods together. This
can be used to achieve data hiding. Encapsulation in itself is not data hiding.
Why we need Encapsulation ?
1.Data Hiding: By using private access modifiers for fields in a class, you can hide the
implementation details from users of the class. This prevents the direct access and
manipulation of the class's internal state, improving the security and maintainability of the
code.
2.Controlled Access: Encapsulation provides ultimate control over the data members and
data methods inside the class.

3.Modularity: ensures that a system is divided into independent, interchangeable modules


that can function independently and interact with each other through well-defined
interfaces.

4. Code Reusability: Encapsulation allows you to reuse your previous data or Java codes in
a new context/class. This is done with Inheritance, where new classes inherit properties of
the encapsulated classes.
5. Abstraction: Encapsulation promotes abstraction by allowing you to focus on the essential
aspects of an object while hiding the unnecessary details.

In summary, encapsulation is a powerful concept that offers several advantages, including data
hiding, controlled access, modularity, code reusability, and abstraction.
• In the above example, we have created a class
named Area. The main purpose of this class is to
calculate the area.
• To calculate an area, we need two variables:
length and breadth and a method: getArea().
Hence, we bundled these fields and methods
inside a single class.
• Here, the fields and methods can be accessed
from other classes as well. Hence, this is not data
hiding.
This is only encapsulation. We are just keeping
similar codes together.

O/P: Area: 30
Data Hiding
• Data hiding, also known as information hiding, is a programming technique
used to protect data from unauthorized access and modification.
• It involves encapsulating data within a class and providing controlled access
to it through methods.
• By hiding the internal details of a class and exposing only the necessary
information through a well-defined interface, data hiding helps maintain the
integrity and security of data.
• In Java, data hiding is achieved through the use of access modifiers. Access
modifiers determine the visibility and accessibility of class members (variables
and methods).
• By carefully choosing the appropriate access modifier, we can control how
data is accessed and modified from outside the class.
Example:
Imagine a class called "BankAccount" that represents a bank account.
The class may have private variables such as "accountNumber" and "balance" to store
the account details.
To ensure data security, these variables are hidden from direct access outside the class.
• In this example, the "accountNumber" and "balance" variables are declared private,
making them inaccessible from outside the class. To interact with these variables, the
class provides public methods like "getAccountNumber()" and "getBalance()" that
allow controlled access to the data.
public class BankAccount { public String getAccountNumber(){
private String accountNumber; return accountNumber;
private double balance; }
// Constructor, getters, and setters public double getBalance() {
// ... return balance;
} }
Implementation of Data Hiding using the access modifiers
• Getter and Setter methods are used to access and update private variables in a class.
• Since private variables cannot be accessed directly from outside the class, getter
methods allow reading the value, and setter methods allow modifying the value in a
controlled way.
Example: Without Getter & Setter (Direct Access - BAD PRACTICE)

Problem:
•There is no control over how name is
changed.
•Anyone can modify it, even setting an
invalid value.
Output:
Raj
Invalid Name!
Output: Ex: Data hiding using the private specifier
My age is 24
• Data hiding is a way of restricting the access of our
data members by hiding the implementation
details. We can use access modifiers to achieve
data hiding.
• In the above example, we have a private field age.
Since it is private, it cannot be accessed from
outside the class.
• In order to access age, we have used public
methods: getAge() and setAge(). These methods
are called getter and setter methods.
• Making age private allowed us to restrict
unauthorized access from outside the class. This is
data hiding.
 If we try to access the age field from the Main
class, we will get an error.
// error: age has private access in Person
p1.age = 24;
or
Class and Instance Level attributes
• Class attributes (Static variables) are variables defined in the class.
• Class-level attributes belong to the class itself, rather than any specific object.
• All objects share the same copy of a static variable.

Characteristics:
Declared with the static keyword inside a class.
Shared among all instances of the class.
Memory is allocated once when the class is loaded, not when objects are created.
Modifying the static variable affects all objects of the class.
Can be accessed without creating an object (using ClassName.variableName).
• Note -> When we don’t assign any value to the class attributes, they take default values
according to their data type. For example, int has a default value ‘0’ whereas String has default
value as null.
Instance Attributes: Instance attributes are associated with instances/objects of
the class. Every object has its own copy of instance variables. meaning that
changes to one object's instance variable do not affect others. Let’s take one
example

Characteristics:
• Declared inside a class but outside methods, constructors, or blocks.
• Each object of the class has its own separate copy.
• Memory is allocated when an object is created and released when the object is
garbage collected.
• Can have different values for different objects.
• Can have any access modifier (private, protected, public, or default).
• Static Variables: When a variable is declared as static, then a single copy of the
variable is created and shared among all objects at a class level. Static variables are,
essentially, global variables. All instances of the class share the same static variable.

Important points for static variables :-


• We can create static variables at class level only.
• static block and static variables are executed in the order they are present in a program.
Declaration

Initialization
Class and Instance level variable example
class Student { public static void main(String[] args) {
// Static Variable (Common for all students) Student s1 = new Student("Raj", 101);
static String schoolName = "Amrita High School"; Student s2 = new Student("Kumar", 201);
// Instance Variables (Unique for each student) s1.display();
String studentName; int rollNumber; s2.display();
// Constructor // Changing the static variable
public Student(String studentName, int rollNumber) Student.schoolName = "Montessori school";
{ System.out.println("*****School name is updated
this.studentName = studentName; for all the instances/objects*****");
this.rollNumber = rollNumber; s1.display();
} s2.display();
// Method to display details }}
public void display() {
Output:
System.out.println("Name: " + studentName + ", Name: Raj, Roll No: 101, School: Amrita High SchoolName:
Roll No: " + rollNumber + ", School: " + Kumar, Roll No: 201, School: Amrita High School
schoolName); *****School name is updated for all the instances/objects*****
}
Name: Raj, Roll No: 101, School: Montessori schoolName:
Kumar, Roll No: 201, School: Montessori school
public class Cricketer { System.out.println("Cricketer 1 name :
private String name; " + cricketer1.name + ", age : " +
private int age; cricketer1.age + ", type : " +
private String type; cricketer1.type);

public static void main(String[] args) { System.out.println("Cricketer 2 name :


Cricketer cricketer1 = new Cricketer(); " + cricketer2.name + ", age : " +
# instance attributes cricketer2.age + ", type : " +
cricketer1.name = "Sachin Tendulkar"; cricketer2.type);
cricketer1.age = 35; }
cricketer1.type = "Batsman"; }

Cricketer cricketer2 = new Cricketer();


cricketer2.name = "Shane Warne";
cricketer2.age = 38;
cricketer2.type = "Bowler";
Major Differences Between Instance and Class-Level Attributes

Feature Instance Variables Static (Class-Level) Variables


Memory Allocation Allocated when object is created Allocated once when class is loaded
Ownership Each object gets its own copy Shared across all objects
Modification Changes affect only that object Changes affect all instances
Accessed via class
Access Accessed via object (obj.varName)
(ClassName.varName)
Example String name; static String companyName;

When to Use Instance vs. class level (Static Variables)?


Use Case Instance Variable Static Variable
Unique values per object Yes No
Shared values across objects No Yes
Memory-efficient for large objects No Yes
Requires modification per instance Yes No
Syllabus
Inheritance:
• Inheritance allows one class to inherit attributes and behaviors from another class.
• It promotes code reuse and enables the creation of specialized classes (child) based
on existing classes.
• In addition, you can add new fields and methods to your current class as well.
Why Do We Need Java Inheritance?
 Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.

 Method Overriding: Method Overriding is achievable only through Inheritance. It


is one of the ways by which Java achieves Run Time Polymorphism.

 Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.
Terms used in Inheritance
 Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class (super/parent). It is
also called a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the same
fields and methods already defined in the previous class.
Syntax class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
Single Inheritance
 When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the single
inheritance.
class Animal{ Output:
void eat(){
System.out.println("eating..."); barking...
} } eating...
class Dog extends Animal{
void bark(){
System.out.println("barking...");
} }
class singleinheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
} }
class Animal{ Output:
int age1=5;
void eat(){ barking...
System.out.println("eating..."); eating...
} }
class Dog extends Animal{
int age2=2;
void bark(){
System.out.println("barking...");
} }
class singleinheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
s.o.pln(d.age1);
s.o.pl(d.age2);
} }
Multilevel Inheritance
 When there is a chain of inheritance, it is known as multilevel inheritance. As you can see
in the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.

class Animal{ class Multilevelinheritance{


void eat(){ public static void main(String args[]){
System.out.println("eating...");} BabyDog d=new BabyDog();
d.weep();
}
d.bark();
class Dog extends Animal{
d.eat();
void bark(){ }}
System.out.println("barking...");}
} Output:
class BabyDog extends Dog{ weeping...
void weep(){System.out.println("weeping...");} barking...
} eating...
Hierarchical Inheritance
 When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.
class Animal{ class Hierarchial{
void eat(){ public static void main(String args[]){
System.out.println("eating...");} Cat c=new Cat();
} c.meow();
class Dog extends Animal{ c.eat();
void bark(){ //c.bark(); - error
System.out.println("barking...");} }}
}
class Cat extends Animal{ Output:
void meow(){ meowing...
System.out.println("meowing...");} eating...
}
Why multiple inheritance is not supported in java?
 To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
 Consider a scenario where A, B, and C are three classes. The C class inherits A
and B classes. If A and B classes have the same method and you call it from child
class object, there will be ambiguity to call the method of A or B class.
 Since compile-time errors are better than runtime errors, Java renders compile-
time error if you inherit 2 classes. So whether you have same method or different,
there will be compile time error.
class A{
void msg(){System.out.println("Hello");}
} • Java does not support multiple inheritance
class B{ using classes to avoid ambiguity.
void msg(){System.out.println("Welcome");} • Java supports multiple inheritance using
} interfaces, allowing a class to implement
class Multipleinheritance extends A,B{ multiple interfaces.

public static void main(String args[]){


Multipleinheritance obj=new Multipleinheritance();
obj.msg(); //Now which msg() method would be invoked?
}
}

Output:
Compile Time Error (Because Java does not allow a class to inherit from two classes to
avoid ambiguity)
Method Overriding:
If the same method is defined in both the superclass and the subclass, then the
method of the subclass class overrides the method of the superclass. This is known
as method overriding.
class Animal { class BabyDog extends Dog {
// overridden method // overriding method What if the
overridden method
public void display(){ public void display(){
of the superclass has
System.out.println("I am an animal"); System.out.println("I am a babytodog... hurray");
be called?
}} }}

class Dog extends Animal { class Main {


// overriding method public static void main(String[] args) {
@Override BabyDog d1 = new BabyDog ();
public void display(){ d1.display();
System.out.println("I am not a human"); }}
}}
Output:
I am a baby dog ….. hurray
Is the code going to compile successfully? In this case, what is the result?

class C1 { Output
int x = 50;
} 40
class C2 extends C1 { 50
int x = 40; 50
}
class Check {
public static void main(String[] args) {
C2 c2 = new C2();
System.out.println(c2.x);
C1 c1 = new C1();
System.out.println(c1.x);
C1 c3 = new C2();
System.out.println(c3.x);
}}
Super Keyword

• The super keyword is used in subclasses to access superclass members (attributes,


constructors and methods).
• It eliminate the confusion between superclasses and subclasses that have methods
with the same name.

Uses
• To call methods of the superclass that is overridden in the subclass.
• To access attributes (fields) of the superclass if both superclass and subclass have
attributes with the same name.
• To explicitly call superclass no-arg (default) or parameterized constructor from the
subclass constructor.
Superclass Method: This is used when we want to call the parent class method. So whenever a
parent and child class have the same-named methods then to resolve ambiguity we use the super
keyword.

class Person { // Driver Program


void message() { class Test {
System.out.println("This is person class\n"); public static void main(String args[])
} {
} Student s = new Student();
// Subclass Student // calling display() of Student
class Student extends Person { s.display();
void message() { }
System.out.println("This is student class"); }
}
// Note that display() is only in Student class Output:
void display() { This is student class
// will invoke or call current class message() method This is person class
message();
// will invoke or call parent class message() method
super.message();
}
}
Super with Variables: This scenario occurs when a derived class and base class
have the same data members. In that case, there is a possibility of ambiguity.

class Vehicle { // Driver Program


int maxSpeed = 100; class Test {
} public static void main(String[] args)
// sub class Car extending vehicle {
class Car extends Vehicle { Car c1 = new Car();
int maxSpeed = 160; c1.display();
void display() }
{ }
// print maxSpeed of base class (vehicle)
System.out.println(“Raj Maximum Speed: "+ super.maxSpeed); Output:
} Raj Maximum Speed: 100
}
Super with Constructors: The super keyword can also be used to access the parent
class constructor. One more important thing is that ‘super’ can call both parametric
as well as non-parametric constructors depending on the situation.

class Person { // Driver Program


Person() { class Test {
System.out.println("Person class Constructor"); public static void main(String[] args)
} {
} Student s = new Student();
// subclass Student extending the Person class }
class Student extends Person { }
Student() {
// invoke or call parent class constructor Output:
super(); Person class Constructor
System.out.println("Student class Constructor"); Student class Constructor
}
}
Calling Parameterized Constructor
class Animal { // Driver Program
// default or no-arg constructor class Main {
Animal() { public static void main(String[] args) {
System.out.println("I am not a human"); Dog dog1 = new Dog();
} }
// parameterized constructor }
Animal(String type) {
System.out.println("Type: "+type); Output:
} Type: Animal
} I am a dog

class Dog extends Animal { Note:


// default constructor • The compiler can automatically call the no-arg
Dog() { constructor. However, it cannot call parameterized
// calling parameterized constructor of the superclass constructors.
super("Animal"); • If a parameterized constructor has to be called, we
System.out.println("I am a dog"); need to explicitly define it in the subclass
} constructor.
}
Polymorphism
• Polymorphism in Java is a concept by which we can perform a single
action in different ways. Polymorphism is derived from 2 Greek
words: poly and morphs. The word "poly" means many and "morphs"
means forms. So polymorphism means many forms.
• The same entity (method or operator or object) can perform different
operations in different scenarios.
• There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism.
• We can achieve polymorphism in java by method overloading and
method overriding.
class Polygon { class Main {
// method to render a shape public static void main(String[] args) {
public void render() { // create an object of Square
System.out.println("Rendering Polygon..."); Square s1 = new Square();
}} s1.render();
class Square extends Polygon { // create an object of Circle
// renders Square Circle c1 = new Circle();
public void render() { c1.render();
System.out.println("Rendering Square..."); }
}} }
class Circle extends Polygon { Output:
// renders circle Rendering Square...
public void render() { Rendering Circle...
System.out.println("Rendering Circle...");
}}
• Here, we have created a superclass: Polygon and two subclasses: Square and Circle.
• The main purpose of the render() method is to render the shape. However, the process of
rendering a square is different than the process of rendering a circle.
• Hence, the render() method behaves differently in different classes. Or, we can say render() is
polymorphic.
Why Polymorphism?
• Polymorphism allows us to create consistent code. In the previous example, we
can also create different methods: renderSquare() and renderCircle() to render
Square and Circle, respectively.
• This will work perfectly. However, for every shape, we need to create different
methods. It will make our code inconsistent.
• To solve this, polymorphism in Java allows us to create a single method
render() that will behave differently for different shapes.
• Note: The print() method is also an example of polymorphism. It is used to print
values of different types like char, int, string, etc.
Java Method Overriding
• During inheritance in Java, if the same method and same parameters is present in both the superclass
and the subclass. Then, the method in the subclass overrides the same method in the superclass. This
is called method overriding.
• The super class method should not be static and final methods cannot be overridden.
• The overriding method cannot have a lower access modifier than the method in the superclass (e.g., a
public method cannot be overridden as private).
• In this case, the same method will perform one operation in the superclass and another operation in the
subclass.
class Language { class Main {
public void displayInfo() { public static void main(String[] args) {
System.out.println("Common English Language"); Java j1 = new Java();
}} j1.displayInfo();
class Java extends Language { Language l1 = new Language();
@Override l1.displayInfo();
public void displayInfo() { }}
System.out.println("Java Programming Language"); Output: Java Programming Language
}} Common English Language

Note: The method that is called is determined during the execution of the program. Hence, method
overriding is a run-time polymorphism.
A Real Examples of Method Overriding
To override a method, the method must be defined in the subclass using the same signature
and the same return type as in its superclass. A subclass inherits methods from a superclass.
Sometimes it is necessary for the subclass to modify the
implementation of a method defined in the superclass.
This is referred to as method overriding.
Example: Java Program to demonstrate the real scenario of Method Overriding
//where three classes are overriding the //Test class to create objects and call the methods
method of a parent class. class Test2{
//Creating a parent class. public static void main(String args[]){
class Bank{ SBI s=new SBI();
int getRateOfInterest(){return 0;} ICICI i=new ICICI();
} AXIS a=new AXIS();
//Creating child classes. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
class SBI extends Bank{ System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
int getRateOfInterest(){return 8;} System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
} }
class ICICI extends Bank{ }
int getRateOfInterest(){return 7;}
} Output:
class AXIS extends Bank{ SBI Rate of Interest: 8
int getRateOfInterest(){return 9;} ICICI Rate of Interest: 7
} AXIS Rate of Interest: 9
Example: Method
class B { Output:
public void cal(double i) { Method Overriding
System.out.println(i * 2); 11.0
10.0
}}

class A extends B {
// This method overrides the method in B
public void cal(double i) {
System.out.println(i);
}}

public class Main {


public static void main(String[] args) {
System.out.println("Method Overriding");
A a = new A();
a.cal(11);
a.cal(10.0);
}}
Java Method Overloading
• When there are multiple methods with the same name but different parameters then these
methods are said to be overloaded.

• Methods can be overloaded by changes in the number of arguments or/and a change in the
type of arguments. (or) Overloading provides a way to define multiple behaviors for a method
based on the number or types of parameters it takes.

• It is primarily used to improve code readability and reusability.

• void func() { ... }, void func(int a) { ... },

• float func(double a) { ... }, float func(int a, float b) { ... }


However, based on the arguments passed, the method is performing different operations:
• prints a pattern of *, if no argument is passed or
• prints pattern of the parameter, if a single char type argument is passed.

Key Points:
• Method overloading occurs within the same class.
• Methods must have the same name but different parameter lists.
• The return type of the method does not play a role in method overloading.
• Overloaded methods can have different access modifiers (public, private, protected).

Note: The method that is called is determined by the compiler. Hence, it is also known as
compile-time polymorphism.
class Pattern { class Main {
public static void main(String[] args) {
// method without parameter Pattern d1 = new Pattern();
public void display() {
for (int i = 0; i < 10; i++) { // call method without any argument
System.out.print("*"); d1.display();
}} System.out.println("\n");

// method with single parameter // call method with a single argument


public void display(char d1.display('#');
symbol) { }}
for (int i = 0; i < 10; i++) {
System.out.print(symbol); Output: **********
}}} ##########
Abstraction
• Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
• Another way, it shows only essential things to the user and hides the internal details.
For example: sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstract class
 A class which is declared with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (method with the body).
 It can be extended and cannot be instantiated (we cannot create objects of abstract classes).
abstract class A{ }
Abstract method
 A method which is declared as abstract and does not have implementation is known
as an abstract method. abstract void printStatus(); //no method body and abstract
• If the abstract class includes any abstract method, then all the child classes
inherited from the abstract superclass must provide the implementation of the
abstract method.
• A method that doesn't have its body is known as an abstract method. We use the
same abstract keyword to create abstract methods.
• An abstract method can be declared inside the abstract class only.
• Though abstract classes cannot be instantiated, we can create subclasses from it.
We can then access members of the abstract class using the object of the subclass.
Example for abstract method
abstract class Animal { class Main {
abstract void makeSound(); public static void main(String[] args)
{
public void eat() { // create an object of Dog class
System.out.println("I can eat."); //Animal d1 = new Dog();
} Dog d1 = new Dog();
} d1.makeSound();
class Dog extends Animal { d1.eat();
// provide implementation of abstract method }
public void makeSound() { }
System.out.println("Bark bark");
} Output:
} Bark bark
I can eat.
abstract class Vehicle { // Abstract class @Override
String brand; void start() {// Implementing the abstract method
public Vehicle(String brand) { // Constructor System.out.println(brand + " bike is starting with a
this.brand = brand; self-start button...");
} }}
abstract void start(); // Abstract method class AbstractExample {
void displayInfo() { // Concrete method public static void main(String[] args) {
System.out.println("Brand: " + brand); Car myCar = new Car("Toyota");
}} myCar.displayInfo();
class Car extends Vehicle { // Subclass 1: Car myCar.start();
public Car(String brand) { System.out.println();
super(brand); Bike myBike = new Bike("Yamaha");
} myBike.displayInfo();
@Override myBike.start();
void start() { // Implementing the abstract method }}
System.out.println(brand + " car is starting with a key..."); Output:
Brand: Toyota
}}
Toyota car is starting with a key...
class Bike extends Vehicle { // Subclass 2: Bike
public Bike(String brand) { Brand: Yamaha
super(brand); Yamaha bike is starting with a self-start button...
}
Useful Links:
1.Object-Oriented Programming Concepts
2.Introduction to Object-Oriented Design
3.Encapsulation, Inheritance, and Polymorphism
4.Modularity in Object-Oriented Systems
5.Dynamic Binding in OOP
• Aggregation and composition are two types of associations in UML class diagrams that
define relationships between classes. They depict how classes are connected and interact
with each other.
Aggregation:
• Aggregation represents a "has-a" relationship where one class (the whole) contains or
is composed of other classes (the parts).
• The parts can exist independently of the whole.
• Aggregation is represented by a diamond-shaped arrowhead line connecting the whole class to
the part class.
Composition:
• Composition is a stronger form of aggregation that signifies a "whole-part" relationship.
• The parts are exclusive to the whole, meaning they cannot exist independently outside the
whole.
• Composition is represented by a diamond-shaped arrowhead line with a solid black diamond on
the whole class's side.
Note: Aggregation and composition can also have multiplicity (e.g., 0..1, 1..*, etc.)
indicating how many parts are associated with the whole.

The diamond arrowhead line represents


aggregation.
• Aggregation implies a relationship
where the child can exist
independently of the parent. Example:
Class (parent) and Student (child).
Delete the Class and the Students still
exist.
• Composition implies a relationship
where the child cannot exist
independent of the parent. Example:
House (parent) and Room (child).
Rooms don't exist separate to a House.
Aggregation Example: Composition Example:

• The hollow diamond symbolizes that the  The filled black diamond indicates strong
"whole" (Car, EngineInspection) does not own ownership—the parts (Head, Hand, Leg) are
the "part" (Engine, Wheel). completely dependent on the Person.
• The "part" can still exist even if the "whole" is  If the "whole" (Person) is deleted, the "parts" are
destroyed. also destroyed.
 This relationship is stronger than aggregation,
where parts can exist independently.
Association vs Aggrégation vs Composition
We see the following relationships:
• owners feed pets, pets please owners
(association)
• a tail is a part of both dogs and cats (aggregation
/ composition)
• a cat is a kind of pet (inheritance
generalization)
Generalization Using Class Diagram: Inheritance, Constructor, and
Overriding

• In a class diagram, generalization represents the concept of inheritance, where one


class (subclass or derived class) inherits attributes and behaviors from another
class (superclass or base class). Let's create a class diagram to illustrate
generalization, including inheritance, constructors, and method overriding.

• Class Diagram: Vehicle Hierarchy

• Consider a simple hierarchy of vehicles: "Vehicle" as the base class, "Car" and
"Motorcycle" as subclasses.
In this class diagram:
• The "Vehicle" class is the superclass.
It contains common attributes brand
and model. The startEngine method
represents a shared behavior.
• The "Car" class is a subclass of
"Vehicle." It inherits attributes from
"Vehicle" and adds its own attribute
carType.
• The "Motorcycle" class is another
subclass of "Vehicle." It inherits
attributes from "Vehicle" and adds its
own attribute hasSidecar.
Explanation:
• Inheritance: "Car" and "Motorcycle" classes inherit attributes (brand and model)
and behavior (startEngine) from the "Vehicle" class. This represents the
generalization relationship.
• Constructor: The "Vehicle" class has a constructor that initializes the attributes
brand and model when a new vehicle object is created.
• Method Overriding: Subclasses "Car" and "Motorcycle" can override the
startEngine method if they need specific implementations. For instance, the
startEngine method in "Car" could play a sound specific to cars, while the
startEngine method in "Motorcycle" could have its unique behavior.
• Attributes: Subclasses "Car" and "Motorcycle" have their specific attributes
(carType and hasSidecar).
Constructor
• A constructor is a special method that is used to initialize objects. The constructor is
called when an object of a class is created. It can be used to set initial values for
object attributes.
• A constructor is a block of codes similar to the method. It is called when an instance
of the class (object) is created.
• At the time of calling constructor, memory for the object is allocated in the memory.
• Every time an object is created using the new() keyword, at least one constructor is
called.
• It calls a default constructor if there is no constructor available in the class. In such
case, Java compiler provides a default constructor by default.
Note: It is called constructor because it constructs the values at the time of object creation. It is
not necessary to write a constructor for a class.
Rules for creating Java constructor
There are the rules defined for the constructor.
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type – not even void
 Constructors are invoked using the new operator when an object is created. Constructors
play the role of initializing objects.
 A Java constructor cannot be abstract, static, final, and synchronized

Here, Test() is a constructor. It has the same


name as that of the class and doesn't have a
return type.
Types of Constructor
In Java, constructors can be divided into three types:
1.No-Arg Constructor 2. Parameterized Constructor 3. Default Constructor
1. No-Arg Constructors
Similar to methods, a Java constructor may or may not have any parameters (arguments).
If a constructor does not accept any parameters, it is known as a no-argument constructor.
Example: Java Private No-arg Constructor
class Main { public static void main(String[] args) {
int i; // calling the constructor without any parameter
// constructor with no parameter Main obj = new Main();
private Main() { System.out.println("Value of i: " + obj.i);
i = 5; }
System.out.println("Constructor is }
called"); Output: Constructor is called
} Value of i: 5
Notice that we have declared the constructor as private.
• Once a constructor is declared private, it cannot be accessed from outside the class.
• So, creating objects from outside the class is prohibited using the private constructor.
• Here, we are creating the object inside the same class.
• However, if we want to create objects outside the class, then we need to declare the
constructor as public.

Example: Java Public no-arg Constructors

class Company { class Main {


String name; public static void main(String[] args) {
// public constructor // object is created in another class
public Company() { Company obj = new Company();
name = “Amrita"; System.out.println("Company name = " + obj.name);
} }
} }
Output:
Company name = Amrita
2. Parameterized Constructor

A Java constructor can also accept one or more parameters. Such constructors are
known as parameterized constructors (constructors with parameters).
Example: Parameterized Constructor

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

String languages; // call constructor by passing a single value


// constructor accepting single value Main obj1 = new Main("Java");
Main(String lang) { Main obj2 = new Main("Python");
languages = lang; Main obj3 = new Main("C");
System.out.println(languages + " Programming Language"); }
} }
Output:
Java Programming Language
Python Programming Language
C Programming Language
3. Java Default Constructor
If we do not create any constructor, the Java compiler automatically creates a no-arg
constructor during the execution of the program. This constructor is called the default
constructor. Here, we haven't created any constructors.
Example: Default Constructor Hence, the Java compiler automatically creates the default constructor.

class Main { class Main {


int a; int a;
boolean b; boolean b;
public static void main(String[] args) { Main() {
// calls default constructor a = 0;
Main obj = new Main(); b = false;
System.out.println("Default Value:"); }
System.out.println("a = " + obj.a); public static void main(String[] args) {
System.out.println("b = " + obj.b); Main obj = new Main();
} System.out.println("Default Value:");
} System.out.println("a = " + obj.a);
Output: Default Value: System.out.println("b = " + obj.b);
a=0 }
b = false }
Constructors Overloading in Java
Like regular methods, constructors can be overloaded (i.e., multiple constructors can have the same
name but different signatures), making it easy to construct objects with different initial data values.
class Main { public static void main(String[] args) {
String language; // call constructor with no parameter
Main() { // constructor with no parameter Main obj1 = new Main();
this.language = "Java"; // call constructor with a single parameter
} Main obj2 = new Main("Python");
Main(String language) { // constructor with a single parameter obj1.getName();
this.language = language; obj2.getName();
} }}
public void getName() { Output:
System.out.println("Programming Language: " + this.language); Programming Language: Java
} Programming Language: Python

• Here, both the constructors initialize the value of the variable language with different values.
• Based on the parameter passed during object creation, different constructors are called, and
different values are assigned.
Example: Call the constructor of the superclass from the constructor of the child class
We can also call the constructor of the superclass from the constructor of child class using super().
// superclass // child class
class Languages { class Main extends Languages {
// constructor of the superclass // constructor of the child class
Languages(int version1, int version2) { Main() {
if (version1 > version2) { // calling the constructor of super class
System.out.println("The latest version is: " + version1); super(11, 8);
} }
else { // main method
System.out.println("The latest version is: " + version2); public static void main(String[] args) {
} // call the first constructor
} Main obj = new Main();
} }}
Output: The latest version is: 11

• Inside the constructor of the Main class, notice the line, super(11, 8); Here, we are calling the
constructor of the superclass (i.e. Languages(int version1, int version2)) from the constructor of
the subclass (Main()).
• The super keyword invokes the constructor of the super class.
Example : Java program to call one constructor from another
class Main { // main class
int sum; public static void main(String[] args) {
// first constructor // call the first constructor
Main() { Main obj = new Main();
// calling the second constructor // call display method
this(5, 2); obj.display();
} }
// second constructor }
Main(int arg1, int arg2) { Output: Sum is: 7
// add two value
this.sum = arg1 + arg2; Here, we have created two constructors
} inside the Main class. Inside the first
void display() { constructor, we have used this keyword to
System.out.println("Sum is: " + sum); call the second constructor.
}
Note: The line inside a constructor that calls another constructor should be the first line of the
constructor. That is, this(5, 2) should be the first line of Main().
Visibility: Attributes and Methods
In object-oriented programming and UML (Unified Modeling Language), visibility refers to
the access control of various elements within a class or system. It determines which parts of a
class are accessible from other classes and parts of the system. The UML notation uses
symbols to represent different visibility levels.
Public (+): Denoted by the "+" symbol.
• Elements (attributes, methods, and classes) with public visibility are accessible from
anywhere, including outside the class and package.
Private (-): Denoted by the "-" symbol.
• Elements with private visibility are accessible only within the defining class.
• Private attributes and methods are encapsulated and can't be accessed directly from
outside the class.
Protected (#): Denoted by the "#" symbol.
• The protected access specifier allows a class, method, or variable to be accessed from
within the same package or by subclasses (even if they are in a different package).
However, it cannot be accessed by unrelated classes outside the package.
Package – Private (Default, ~): Denoted by the "~" symbol or no symbol at all.
• It allows a class, method, or variable to be accessed only within the same package. It is not
accessible from outside the package, even by subclasses.
class Person {
+ name: String // Public attribute
- age: int // Private attribute
# address: String // Protected attribute
~ gender: char// Package visibility attribute
+ Person(name: String, age: int)// Public constructor
- calculateAge() : int // Private method
# updateAddress() : void // Protected method
~ greet() : String // Package visibility method
}
In this example:
• The name attribute has public visibility and can be accessed anywhere.
• The age attribute has private visibility and is restricted to the Person class.
• The address attribute has protected visibility, so it can be accessed by subclasses.
• The gender attribute has package visibility and can be accessed within the package.
• The constructors and methods follow similar visibility levels.
Polymorphism in OOP (Object-Oriented Programming)
Polymorphism is a key concept in object-oriented programming (OOP) that allows objects of different classes
to be treated as objects of a common superclass. It enables code to be more flexible, extensible, and reusable
by providing a way to write code that can work with objects of various types without knowing their specific
implementations. Polymorphism is primarily achieved through method overriding and method overloading.
1. Method Overriding:
• In method overriding, a subclass provides a specific implementation for a method that is already defined in
its superclass.
• The method in the subclass must have the same name, return type, and parameters / argument list as the
method in the superclass.
• When an object of the subclass is used, the overridden method in the subclass is invoked instead of the
method in the superclass.

2. Method Overloading:
• Method overloading involves defining multiple methods in the same class with the same name but
different parameter lists.
• The methods can have different parameter types, different numbers of parameters, or both.
• The appropriate method to execute is determined at compile-time based on the method's name and parameter
list. Overloaded methods can have different access modifiers (public, private, protected).
• Polymorphism requires inheritance and an overridden function.
• Shape is the superclass or parent class; Circle, Rectangle, and Triangle are all subclasses or
children of Shape.
• The draw functions in the subclasses override the draw function in the Shape class.

Fig. Overloaded vs. overridden methods. Methods


are color coded.
Fig. UML class diagram of the Shape classes.
Abstract Classes and Interfaces in OOP
Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or
interfaces.
Abstract Classes:
• An abstract class is a class that cannot be instantiated on its own. It serves as a blueprint
(Provide a way to define a standard set of behaviors and features that multiple classes
can share without implementing them from scratch. These classes can create a foundation
upon others to build, allowing developers to quickly create new classes with minimal
effort) for other classes.
• Abstract classes may have abstract methods (methods without implementations) and
concrete methods (methods with implementations).
• Subclasses of an abstract class are required to provide implementations for
all the abstract methods.
• Abstract classes can have instance variables and constructors.
In Java, the following some important observations about abstract classes are as follows:
• An instance of an abstract class can not be created.
• Constructors are allowed.
• We can have an abstract class without any abstract method.
• There can be a final method in abstract class but any abstract method in class(abstract
class) can not be declared as final or in simpler terms final method can not be abstract
itself as it will yield an error: “Illegal combination of modifiers: abstract and final”
• We can define static methods in an abstract class
• We can use the abstract keyword for declaring top-level classes (Outer class) as well
as inner classes as abstract
• If a class contains at least one abstract method then compulsory should declare a class
as abstract
• If the Child class is unable to provide implementation to all abstract methods of the
Parent class then we should declare that Child class as abstract so that the next level
Child class should provide implementation to the remaining abstract method
Abstract class having constructor, data member
and methods
//example of abstract class that have method body class TestAbstraction2{
abstract class Bike{ public static void main(String args[]){
Bike(){ // Constructor Bike obj = new Honda();
System.out.println("bike is created"); obj.run();
} obj.changeGear();
abstract void run(); // abstract method }
void changeGear(){ // Normal method } Rule:
System.out.println("gear changed"); If there is an abstract method in a
} Output: class, that class must be abstract.
} bike is created
running safely..
class Honda extends Bike{ gear changed
void run(){System.out.println("running safely..");
} class Bike12{ // what will be output
} abstract void run();
}
abstract class Calculator class AbstractMethodExample
{ {
abstract void display(); public static void main(String arg[])
} {
Calculator add = new Add();
class Add extends Calculator add.display();
{
void display() Calculator sub = new Sub();
{ sub.display();
System.out.println("In the Add Child Class"); }
} }
}
Output:
class Sub extends Calculator In the Add Child Class
{ In the Sub Child Class
void display()
{
System.out.println("In the Sub Child Class");
}
}
// Abstract class // Base class
abstract class Sunstar { class Base {
abstract void printInfo(); public static void main(String args[])
} {
Sunstar s = new Employee();
// Abstraction performed using extends s.printInfo();
class Employee extends Sunstar { }
void printInfo() }
{
String name = “AAshish";
int age = 8; Output:
float salary = 222.2F; AAshish
8
System.out.println(name); 222.2
System.out.println(age);
System.out.println(salary);
}
}
• An Abstract class name
and Abstract methods
are capitalized in the
class diagram.
• GeometricObject is an
Abstract class.
• getArea() and
getPerimeter() are
Abstract methods.
Interfaces
• The interface in Java is a mechanism to achieve abstraction.
• An interface is a blueprint of a class. It has static constants and abstract methods.
• There can be only abstract methods in the Java interface, not the method body.
• It is used to achieve abstraction and multiple inheritances in Java using Interface.
• In other words, you can say that interfaces can have abstract methods and variables.
It cannot have a method body.
• Interface methods are by default abstract and public.
• Interface attributes are by default public, static and final.
• A class can implement multiple interfaces, allowing it to inherit behavior from
multiple sources.
• Classes implement interfaces using the ‘implements’ keyword.
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important
details of an object (interface).
2) Java does not support "multiple inheritance" (a class can only inherit
from one superclass). However, it can be achieved with interfaces,
because the class can implement multiple interfaces.
Note: To implement multiple interfaces, separate them with a comma.
How to declare an interface
interface <interface_name>{
// declare constant fields
// declare methods that abstract by default.
}
The relationship between classes and interfaces
• As shown in the figure given below, a class extends another class, an
interface extends another interface, but a class implements an
interface.
Example to demonstrate interface :
import java.io.*; class Main {
interface Animal { public static void main(String[] args)
// interface methods (does not have a body) {
public void animalSound(); Cow myCow = new Cow();
public void sleep(); myCow.animalSound();
} myCow.sleep();
}
class Cow implements Animal { }
public void animalSound() {
System.out.println("The cow says: Amba Amba");
} Output:
public void sleep() {
System.out.println("Zzz..i am sleepy"); The cow says: Amba Amba
}} Zzz… I am sleepy

• Interface methods are by default abstract and public


Example to demonstrate Multiple interfaces :
interface FirstInterface { class Main {
public void myMethod(); // interface method public static void main(String[] args) {
} DemoClass myObj = new DemoClass();
interface SecondInterface { myObj.myMethod();
public void myOtherMethod(); // interface method myObj.myOtherMethod();
} }
// DemoClass "implements" FirstInterface and SecondInterface }
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() { Output:
System.out.println("First Interface..");
} First Interface..
public void myOtherMethod() { Second Interface...
System.out.println("Second Interface...");
}
}
interface Animal { public class Main {
void eat(); public static void main(String[] args)
} {
interface Bird { Sparrow sp = new Sparrow();
void fly(); sp.eat();
}// Multiple inheritance sp.fly();
class Sparrow implements Animal, Bird }}
{
public void eat() { Output
System.out.println("Sparrow is eating"); }
public void fly() { Sparrow is eating
System.out.println("Sparrow is flying"); } Sparrow is flying
}
Multiple inheritance is not supported through class in java, but it is possible
by an interface, why?
• Multiple inheritance is not supported in the case of class because of ambiguity.
However, it is supported in case of an interface because there is no ambiguity. It is
because its implementation is provided by the implementation class.

interface Printable{ public static void main(String args[]){


void print(); }
TestInterface3 obj = new TestInterface3();
interface Showable{ obj.print();
void print(); } } }

class TestInterface3 implements Printable, Showable{ Output:

public void print(){ Amrita


System.out.println(“Amrita");
}
Interface Inheritance

A class implements an interface, but one interface extends another interface.

interface Printable{ public static void main(String args[]){


void print(); }
TestInterface4 obj = new TestInterface4();
interface Showable extends Printable{ obj.print();
void show(); } obj.show();
} }
class TestInterface4 implements Showable{
public void print(){ Output:
System.out.println("Hello"); } Hello
Welcome
void show(){
System.out.println("Welcome"); }
Default Method in Interface
We can have method body in interface. But we need to make it default method.

interface Drawable{ class TestInterfaceDefault{

void draw(); public static void main(String args[]){


default void msg(){ Drawable d=new Rectangle();
System.out.println("default method"); d.draw();
} } d.msg();
}
class Rectangle implements Drawable{ }

public void draw(){ Output:


System.out.println("drawing rectangle"); drawing rectangle
} } default method
Q. Consider the example of vehicles like bicycles, cars, bikes, etc they have common functionalities. So we
make an interface and put all these common functionalities. And lets Bicycle, Bike, car, etc implement all
these functionalities in their own class in their own way.

import java.io.*; @Override


interface Vehicle { public void applyBrakes(int decrement){
// all are the abstract methods. speed = speed - decrement;
void changeGear(int a); } // to decrease speed
void speedUp(int a); public void printStates() {
void applyBrakes(int a); System.out.println("speed: " + speed+ " gear: " + gear);
} }}
class Bicycle implements Vehicle{ class Bike implements Vehicle {
int speed; int speed;
int gear; int gear;
@Override @Override
public void changeGear(int newGear){ public void changeGear(int newGear){
gear = newGear; gear = newGear;
} // to change gear } // to change gear

@Override @Override
public void speedUp(int increment){ public void speedUp(int increment){
speed = speed + increment; speed = speed + increment;
} // to increase speed } // to increase speed
// to decrease speed System.out.println("Bicycle present state :");
@Override bicycle.printStates();
public void applyBrakes(int decrement){
speed = speed - decrement; // creating instance of the bike.
Bike bike = new Bike();
public void printStates() { bike.changeGear(1);
System.out.println("speed: " + speed+ " gear: " + gear); bike.speedUp(4);
} bike.applyBrakes(3);
}
class GFG { System.out.println("Bike present state :");
public static void main (String[] args) { bike.printStates();
// creating an instance of Bicycle }
// doing some operations }
Bicycle bicycle = new Bicycle(); Output:
bicycle.changeGear(2); Bicycle present state :
bicycle.speedUp(3); speed: 2 gear: 2
bicycle.applyBrakes(1); Bike present state :
speed: 1 gear: 1
• The final method in Java is used as a non-access modifier applicable only to a variable, a
method, or a class. It is used to restrict a user in Java.

• The following are different contexts where the final is used:


 Variable
 Method
 Class

• Final variables: When a variable is declared as final, its value cannot be changed once it has
been initialized. This is useful for declaring constants or other values that should not be
modified.
• Final methods: When a method is declared as final, it cannot be overridden by a subclass.
This is useful for methods that are part of a class’s public API and should not be modified by
subclasses.
• Final classes: When a class is declared as final, it cannot be extended by a subclass. This is
useful for classes that are intended to be used as it is and should not be modified or extended.
// Java program to show that interfaces can
// have methods from JDK 1.8 onwards
interface In1{
final int a = 10;
default void display() {
System.out.println("hello");
}
}

// A class that implements the interface.


class TestClass implements In1{
// Driver Code
public static void main (String[] args) {
TestClass t = new TestClass();
t.display();
}}

Output:
hello
• Another feature that was added in JDK 8 is that we can now define static methods in
interfaces that can be called independently without an object.
• Note: these methods are not inherited.

hello
Difference Between Class and Interface
Local and Global (or class)
Local Variable:
• Local variables are variables that are declared within a
specific scope, such as within a function or a block of code.

• These variables are only accessible within that particular


scope and are typically used for temporary storage of data
or for performing calculations within a limited context.

• Once the scope in which a local variable is defined ends, the variable typically goes out of scope
and its memory is released.

• In many programming languages, local variables have a limited visibility and lifespan compared
to global variables, which are accessible from any part of the program.

• This encapsulation of variables within specific scopes helps to organize code, prevent unintended
modifications, and manage memory efficiently.
Global Variable:
• Global variables are variables that are declared outside of any function or block of code and
can be accessed from any part of the program.
• Unlike local variables, which have limited scope, global variables have a broader scope and
can be used across multiple functions, modules, or files within a program.

Static Variable:
• When a variable is defined as static, then a single copy of the variable is created and shared
among all objects at the class level. Static variables are, essentially, global variables.
• All instances of the class share the same static variable.

Important points for static variables:


 We can create static variables at class-level only.
 Static block and static variables are executed in order they are present in a program.
 Static variable can call by directly with the help of class only, we do not need to create
object for the class in this.
public class VariableExample { Output:
// Global (Instance) variable Local Count: 5
int globalCount = 10; Global Count: 10
void display() { Updated Global Count: 15
// Local variable
int localCount = 5; globalCount is a global variable
System.out.println("Local Count: " + localCount); (instance variable) because it is declared
System.out.println("Global Count: " + globalCount); at the class level and shared among all
} methods.
localCount is a local variable because it
void update() { // Another method that can access the global variable is declared inside the display() method
globalCount += 5; and only accessible there.
System.out.println("Updated Global Count: " + globalCount); Attempting to use localCount in another
} method like update() would result in a
compile-time error.
public static void main(String[] args) {
VariableExample obj = new VariableExample();
obj.display();
obj.update();
}}
Local Global

The sum is: 30 The sum is: 130


Packages
• A java package is a group of similar types of classes, interfaces and sub-packages.

Advantage of Java Package


 Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
 Java package provides access protection.
 Java package removes naming collision.
• Package in java can be categorized in two forms, built-in package and user-defined
package.
Built-in Packages
These packages consist of a large number of classes which are a part of Java API. Some of
the commonly used built-in packages are:

 java.lang: Contains language support classes(e.g classes which defines primitive data
types, math operations). This package is automatically imported.

 java.io: Contains classes for supporting input / output operations.

 java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.

 java.applet: Contains classes for creating Applets.

 java.awt: Contain classes for implementing the components for graphical user interfaces
(like button, menus etc).

 java.net: Contain classes for supporting networking operations.


Importing java.lang
Output

Explanation:
•In this example, we import java.lang.*
to have access to some of the
fundamental classes provided by Java,
such as Math, String, and Integer.

•The code demonstrates the usage of


these classes by calculating the area of a
circle, determining the length of a string,
and converting an integer to its binary
representation.
User-defined packages are those that the users define.
• Inside a package, you can have Java files like classes, interfaces, and a package
as well (called a sub-package).

How to access package from another package?


There are three ways to access the package from outside the package.
 import package.*;
 import package.classname;
 fully qualified name.

1) Using packagename.*
• If you use package.* then all the classes and interfaces of this package will be
accessible but not sub packages.
• The import keyword is used to make the classes and interface of another package
accessible to the current package.
Output:Hello
2) Using packagename.classname

If you import package.classname then only


declared class of this package will be accessible.

Note: If you import a package, subpackages will


not be imported.

Output:Hello
3) Using fully qualified name

• If you use fully qualified name then only


declared class of this package will be
accessible. Now there is no need to import.
But you need to use fully qualified name
every time when you are accessing the class
or interface.
• It is generally used when two packages have
same class name e.g. java.util and java.sql
packages contain Date class.
• If you import a package, all the classes and
interface of that package will be imported
excluding the classes and interfaces of the
subpackages. Hence, you need to import the
subpackage as well. Output:Hello
Subpackage in Java
• A package defined inside a package is called a sub-package. It’s used to make the
structure of the package more generic. It lets users arrange their Java files into their
corresponding packages.
• For example, say, you have a package named cars. You’ve defined supporting Java
files inside it.
• But now you want to define another package called
superCars. Should we define it inside the car's package
or outside as another package? At this point, you must
say that it should go inside cars because superCars are
also related to cars.
• But to be more generic, we’re defining it as a separate
package, but having it inside cars makes them part of
cars.
UNIT 3
Exceptions
Introduction:
• Exception handling enables a program to deal with exceptional situations and
continue its normal execution.
• Exception Handling in Java is one of the effective means to handle runtime
errors so that the regular flow of the application can be preserved.
• It is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, InputMismatchException, ArrayIndexOutOfBoundsException, etc.

What are Java Exceptions?


• An Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the
program’s instructions.
An exception can occur for many reasons. Some of them are:
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out of disk memory)
• Code errors
• Opening an unavailable file

Java Exception hierarchy

• As you can see from the image, the


Throwable class is the root class in the
hierarchy.
• Note that the hierarchy splits into two
branches: Error and Exception.
Errors
• Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc.
• Errors are usually beyond the control of the programmer and we should not
try to handle errors. Ex: LinkageError, VirtualMachineError.

Exceptions
• Exceptions can be caught and handled by the program.
• When an exception occurs within a method, it creates an object. This object
is called the exception object.
• It contains information about the exception such as the name and description
of the exception and state of the program when the exception occurred.

Java Exception Types


• The exception hierarchy also has two branches: RuntimeException and IOException.
1. RuntimeException
• A runtime exception happens due to a programming error. They are also known as
unchecked exceptions.
• These exceptions are not checked at compile-time but run-time.

Some of the common runtime exceptions are:


• Improper use of an API - IllegalArgumentException
• Null pointer access (missing the initialization of a variable) - NullPointerException
• Out-of-bounds array access - ArrayIndexOutOfBoundsException
• Dividing a number by 0 - ArithmeticException
 You can think about it in this way. "If it is a runtime exception, it is your fault".
 The NullPointerException would not have occurred if you had checked whether the
variable was initialized or not before using it.
 An ArrayIndexOutOfBoundsException would not have occurred if you tested the
array index against the array bounds.
ArithmeticException
2. IOException
• IOException (Input/Output Exception) belongs to a class of checked exception in Java
that occurs during input and output operations, such as reading from a file, writing to a
file, or interacting with streams.
• Checked exceptions are thrown at compile time. Resolving checked exceptions is
necessary to execute a Java program.
• There are many subclasses of IOException, such as FileNotFoundException,
SSLException, EndOfStreamException, and DirectoryNotFoundException.

Situation Example
File not found Trying to read a file that doesn't exist.
Disk full, permissions error, or file is
Error reading/writing file
locked.
Network failures or broken pipe during
Stream interruptions
stream operations.
Closing a stream or reader improperly Forgetting to close resources or trying to
read from a closed stream.
Explanation:
•FileNotFoundException is thrown when compiling the above Java program. Hence,
the program does not compile and cannot be executed.
•This exception is thrown to avoid scenarios such as if the named file does not exist,
is a directory rather than a regular file, or cannot be opened for reading for some other
reason.
•Apart from the close() and read() methods of the FileReader class, it also throws an
IOException, which must be handled.
Exception Handling
• We know that exceptions abnormally terminate the execution of a program.
• This is why it is important to handle exceptions. Here's a list of different approaches to
handle exceptions in Java.
• Different approaches to handle exceptions in Java.
 try...catch block
 finally block
 throw and throws keyword
1. Java try...catch block
• The try-catch block is used to handle exceptions in Java.
• Here, we have to place the code that might generate an exception inside the try block.
• Every try block is followed by a catch block.
• When an exception occurs, it is caught by the catch block. The catch block cannot be
used without the try block.
Ex: Exception Handling
using try…catch

• The classes used (System,


ArithmeticException, etc.)
are part of the java.lang
package.

• java.lang is imported by
default in every Java
program, so there's no need
for manual import.

Output: ArithmeticException => / by zero

• To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an
exception occurs, the rest of the code inside the try block is skipped.
• The catch block catches the exception and statements inside the catch block is executed.
• If none of the statements in the try block generates an exception, the catch block is skipped.
2. Java finally block
• The finally block is always executed no matter whether there is an exception or not.

• The finally block is optional. And, for each try block, there can be only one finally
block.

• If an exception occurs, the finally block is executed after the try...catch block.
Otherwise, it is executed after the try block.

Syntax:
Ex: Exception Handling
using finally

• We are dividing a number by 0 inside the try block. Here, this code generates an
ArithmeticException.
• The exception is caught by the catch block. And, then the finally block is executed.
• Note: It is a good practice to use the finally block, because it can include important
cleanup codes.
3. Java throw and throws keyword
• The Java throw keyword is used to explicitly throw a single exception.
• When we throw an exception, the flow of the program moves from the try block to
the catch block. We use the throw keyword within a method.
• Syntax: throw throwableObject;
public class Main{
static int division(int number1, int number2){
if (number2 == 0) {
throw new ArithmeticException("Divisor should not be 0");
}else {
System.out.println("Both numbers are correct!!"); Exception in thread "main"
return number1/number2; java.lang.ArithmeticException
} public static void main(String args[]){ : Divisor should not be 0
int res=division(12,0);
System.out.println(res);
System.out.println("Continue...");
}}
• In this example, we are explicitly throwing the ArithmeticException using the throw keyword.
• Similarly, the throws keyword is used to declare the type of exceptions that might
occur within the method declaration.
Syntax: accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 … {
// code } - we can use throws to declare multiple exceptions.
• When we run this program, if the file
test.txt does not exist, FileInputStream
throws a FileNotFoundException which
extends the IOException class.
• The findFile() method specifies that an
IOException can be thrown. The main()
method calls this method and handles the
exception if it is thrown.
• If a method does not handle exceptions,
the type of exceptions that may occur
within it must be specified in the throws
clause.
import java.util.*; // Handling multiple exceptions int d1 = obj.nextInt();
class JavaThrows { System.out.print("Enter value for b: ");
public float ThrowsExample(int a, int b, int n) throws int d2 = obj.nextInt();
ArithmeticException, ArrayIndexOutOfBoundsException { System.out.print("Enter array length: ");
if (n < 3) { int len = obj.nextInt();
throw new ArrayIndexOutOfBoundsException("Array JavaThrows jt = new JavaThrows();
length must be at least 3"); try {
} float res = jt.ThrowsExample(d1, d2, len);
float arr[] = new float[n]; System.out.println("Division of " + d1 + " and " + d2 +
arr[0] = a; " is " + res);
arr[1] = b; }
if (b == 0) { catch (ArithmeticException e1) {
throw new ArithmeticException("Divisor should not be 0"); System.out.println("Division by zero is not
} possible!!");
arr[2] = a / b; }
return arr[2]; catch (ArrayIndexOutOfBoundsException e2) {
} System.out.println("Index out of range!!! " +
public static void main(String arg[]) { e2.getMessage());
Scanner obj = new Scanner(System.in);
Enter value for a: 5 } Enter value for a: 5
System.out.print("Enter value for a:Enter
"); value for b: 0 }} Enter value for b: 2
Enter array length: 3 Enter array length: 2
Division by zero is not possible!! Index out of range!!! Array length must be at least 3
******** Example to represent arithmetic and array index out of bounds exception **********
public class ExceptionExample {
public static void main(String[] args) {
try { Output
// ArithmeticException Example Caught ArithmeticException: / by zero
int a = 10, b = 0; Execution completed in try-catch-finally block.
int result = a / b;
// Will cause ArithmeticException
System.out.println("Result: " + result);
// ArrayIndexOutOfBoundsException Example
int[] numbers = {1, 2, 3};
System.out.println("Element: " + numbers[5]); // Invalid index
}
catch (ArithmeticException ae) {
System.out.println("Caught ArithmeticException: " + ae.getMessage());
}
catch (ArrayIndexOutOfBoundsException ai) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + ai.getMessage());
}
finally {
System.out.println("Execution completed in try-catch-finally block.");
} }}
Nested Try Block
• A try block can be nested within another try block. This structure is termed as
Nested try block. Whenever an exception is raised within a nested try block, its
exception is pushed to Stack. The exception propagates from child to parent try
block and so on.

• For example, the inner try block can be used to handle


ArrayIndexOutOfBoundsException while the outer try block can handle the
ArithemeticException (division by zero).

Why use nested try block


• Sometimes a situation may arise where a part of a block may cause one error and
the entire block itself may cause another error. In such cases, exception handlers
have to be nested.
Nested try block example
public class NestedTryBlock{ //catch block of inner try block 2
public static void main(String args[]){ catch(ArrayIndexOutOfBoundsException e)
{
try{ //outer try block System.out.println(e);
try{ //inner try block 1 }
System.out.println("going to divide by 0"); System.out.println("other statement");
int b =39/0; }
} //catch block of outer try block
//catch block of inner try block 1 catch(Exception e)
catch(ArithmeticException e) {
{ System.out.println("handled the exception (outer catch)");
System.out.println(e); }
} System.out.println("normal flow..");
try{ //inner try block 2 } //main fucnt } // Class ends
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4; // tries to assign value to index 5,
which is out of bounds
}
Custom Exceptions:
• In Java, we can create our own exceptions that are derived classes of the Exception class.
• Creating our own Exception is known as custom exception or user-defined exception.
• Basically, Java custom exceptions are used to customize the exception according to user need.

• Consider creating custom


exceptions for specific
application scenarios.
• Custom exceptions can provide
more meaningful information
about the error.
import java.util.ArrayList; else { // insert language to ArrayList
import java.util.Arrays; languages.add(language);
// create a checked exception class System.out.println(language + " is added to the
CustomException extends Exception { ArrayList"); } }
public CustomException(String message) { public static void main(String[] args) {
// call the constructor of Exception class // create object of Main class
super(message); Main obj = new Main();
}} // exception is handled using try...catch
class Main { try {
ArrayList<String> languages = new obj.checkLanguage("Swift");
ArrayList<>(Arrays.asList("Java", "Python", "JS")); obj.checkLanguage("Java");
// check the exception condition }catch(CustomException e) {
public void checkLanguage(String language) throws System.out.println("[" + e + "] Exception
CustomException { Occured");
// throw exception if language already present in }
ArrayList }}
if(languages.contains(language)) { Output:
throw new CustomException(language + " already Swift is added to the ArrayList
exists"); [CustomException: Java already exists] Exception
} Occured
Exception Handling in OOAD (Object-Oriented Analysis and Design):

• In Object-Oriented Analysis and Design (OOAD), exception handling is


considered during the design phase to ensure that the system can gracefully
handle and recover from errors at runtime.
• The design might involve defining custom exception classes that represent
specific error scenarios within the system.
• Exception handling design also considers how error information is propagated and
reported to users or other parts of the system.
Inner Class
• Java inner class or nested class is a class that is declared inside the class or
interface.
• We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.
• Additionally, it can access all the members of the outer class, including private
data members and methods.

Syntax: class Java_Outer_class{


//code
class Java_Inner_class{
//code
} // inner
} // outer
Types of Inner Classes
• Non-static Nested Class (Inner Class): Associated with an instance of the outer class.
• Static Nested Class: Not associated with an instance of the outer class and can access
only static members of the outer class.
• Local Inner Class: Defined within a block, typically a method.
• Anonymous Inner Class: A class without a name, used to instantiate objects with certain
"on-the-fly" functionality.

When to Use Which?


• Inner Class: When the class is tightly coupled to the outer class (e.g., Tree and Node).
• Static Nested Class: When you need a helper class but don’t need outer instance access.
• Local/Anonymous: For short-lived, one-off implementations (e.g., GUI event handlers).
1. Non-static Nested Class (Inner Class)
• Definition: A class defined inside another class without the static keyword.
• Association: Each instance is tied to an instance of the outer class.
• Access: Can access all members (even private) of the outer class.
• Use Case: Used when the inner class logically belongs to the outer class (e.g., Engine is part of Car).

class OuterClass {
private String message = "Hello from Outer Class";
class InnerClass {
void display() { Output
System.out.println(message); Hello from Outer Class
} } // inner class
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
} } // outer class
2. Static Nested Class
• Definition: A class defined inside another class with the static keyword.
• Association: Not tied to any instance of the outer class (like a regular top-level class).
• Access: Can only access static members of the outer class.
• Use Case: Used when the nested class doesn't need access to instance-specific data.

class OuterClass {
private static String message = "Hello from Static Nested Class";
Here, It can access
the static members of
static class StaticNestedClass {
Output OuterClass directly.
void display() {
Hello from Static Nested Class No instance of
System.out.println(message);
OuterClass is needed
}}
to create an instance
of StaticNestedClass.
public static void main(String[] args) {
OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
nested.display();
}}
3. Local Inner Class
• Definition: A class defined inside a block (e.g., a method, loop, or if statement).
• Scope: Only visible within the block where it’s defined.
• Access: Can access final or effectively final local variables of the enclosing block.
• Use Case: Used for one-off implementations.
class Outer {
void outerMethod() { Output
final int localVar = 30; Access local variable: 30
class LocalInner {
void display() { / / Must be final or effectively final
System.out.println("Access local variable: " + localVar);
}}
LocalInner inner = new LocalInner();
inner.display();
} // outerMethod
public static void main(String[] args) {
Outer outer = new Outer();
outer.outerMethod();
} } // outer class
4. Anonymous Inner Class
•Definition: A class without a name, defined and instantiated in a single expression.
•Use Case: Used for quick implementations of interfaces or abstract classes.
•Syntax: Uses new InterfaceName() { ... } or new ClassName() { ... }.

interface Greeting {
void greet();
} Output
Hello from anonymous class!
class Outer {
void anonymousDemo() {
Greeting greeting = new Greeting() { // Anonymous class implementing Greeting
public void greet() { // @Override
System.out.println("Hello from anonymous class!");
}};
greeting.greet();
}
public static void main(String[] args) {
Outer outer = new Outer();
outer.anonymousDemo();
}}
Summary
• Use Sparingly: Inner classes can make code harder to read if overused. Use
them when they logically belong to the outer class.
• Anonymous Classes: Ideal for implementing interfaces or abstract classes
with a small amount of functionality.
• Accessing Members: Inner classes can access all members of the outer
class, including private members, making them useful for encapsulation.
• Static Nested Classes: Use when the nested class does not require access to
the outer class's instance members.
• Avoid Complexity: Keep inner classes simple to avoid increasing the
complexity of the outer class.
class CPU { public class Main {
double price; public static void main(String[] args) {
// nested class
class Processor{ // create object of Outer class CPU
// members of nested class CPU cpu = new CPU();
double cores; // create an object of inner class Processor using outer class
String manufacturer; CPU.Processor processor = cpu.new Processor();
double getCache(){ // create an object of inner class RAM using outer class CPU
return 4.3; CPU.RAM ram = cpu.new RAM();
} System.out.println("Processor Cache = " + processor.getCache());
} System.out.println("Ram Clock speed = " + ram.getClockSpeed());
// nested protected class
protected class RAM{ }
// members of protected nested class }
double memory;
String manufacturer; Output: Processor Cache = 4.3
double getClockSpeed(){ Ram Clock speed = 5.5
return 5.5;
}
}
}
Inner Classes in OOAD (Object-Oriented Analysis and Design):

• In Object-Oriented Analysis and Design (OOAD), inner classes might not be as


prominent as in programming languages. However, the concept of encapsulation and
modular design that inner classes provide aligns with OOAD principles. The idea of
grouping related classes together and managing their visibility is consistent with
good design practices.
• Inner classes can be used in OOAD to model relationships where one class plays a
supporting or auxiliary role to another class. For example, a Student class might have
an inner class representing a ContactInformation object that encapsulates email
addresses, phone numbers, etc.
Java String
• In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. The java.lang.String class is used to create a string object.
Note: To work with mutable
• char[] ch={‘A',‘M',‘R',‘I',‘T',‘A'}; strings (i.e., strings that can be
• String s=new String(ch);  modified
is same as: String without creating new
s=“AMRITA";
objects), use the StringBuffer
• Java String class provides a lot of methods to perform operations on
or StringBuilder strings such as
classes.
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
• The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
• The CharSequence interface represents a sequence of characters. It is implemented by the
String, StringBuffer, andStringBuilderclasses. This means we can create and manipulate strings
in Java using any of these three classes.
• In Java, String objects are immutable, meaning their values cannot be changed after creation.
When a string is modified, a new object is created in memory.
String object can be created in two ways: 1. By string literal 2. By new keyword
1) String Literal
• Java String literal is created by using double quotes.
• Syntax: <String_Type> <string_variable> = "<sequence_of_string>";
String s="welcome";
• Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool.
• For example: String s1="Welcome";
String s2="Welcome"; //It doesn't create a new instance
• Note: String objects are stored in a special memory area known as the "string constant
pool".
• Why Java uses the concept of String literal?
• To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
2) By new keyword
• String s=new String("Welcome"); //creates two objects and one reference variable
• In such case, JVM will create a new string object in heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap.
Java String class methods
public class StringExample{ The java.lang.String class
public static void main(String args[]){ provides many useful
String s1="java"; methods to perform
char ch[]={'s','t','r','i','n','g','s'}; operations on sequence of
String s2=new String(ch); char values.
String s3=new String("example");
System.out.println(s1);
Output:
java
System.out.println(s2);
System.out.println(s3); strings
example
}}
Java String class methods
• String length() - The length() method finds the length of a string. The length of the
Java string is the same as the Unicode code units of the string.
• String concat() - The concat() method appends (concatenate) a string to the end of
another string.
• String equals() - The equals() method compares two strings, and returns true if the
strings are equal, and false if not.
import java.lang.String; import java.lang.String;
public class LengthExample{ public class Main {
public static void main(String args[]){ public static void main(String[] args) {
String s1="java"; String myStr1 = "Adithya ";
String s2="python"; String myStr2 = "Ram";
System.out.println("string length is: "+s1.length()); String myStr3 = "Ram";
System.out.println("string length is: "+s2.length()); System.out.println(myStr1.concat(myStr2));
}} System.out.println(myStr1.equals(myStr3));
System.out.println(myStr2.equals(myStr3));
Output: }}
string length is: 4 Output:
string length is: 6 Adithya Ram false true
// The Java String class substring() method returns a part of the string.
public class PasswordMaker {
public static void main(String[] args) {
String firstName = "Raj";
String middleName = "Kumar";
String lastName = "Batchu";
int age = 32;
// extract initials
String initials = firstName.substring(0,1) +middleName.substring(0,1) +lastName.substring(0,1);
// append age after changing the initials to lower case
String password = initials.toLowerCase() + age;
System.out.println("Your Password = " + password);
}}

Output:
Your Password = rkb32
Output:
String in uppercase: WELCOME!
YOU ARE PRACTICING STRINGS
CONCEPT
String in lowercase: welcome! you
are practicing strings concept
Length of the string: 43
Index of 'Concept': 36
The compareTo method is used to compare two strings lexicographically. It returns:
I. A negative value if the first string is smaller. II. Zero if both strings are equal.
III. A positive value if the first string is larger.

Output:
String 1: This is exercise 1
String 2: This is Exercise 1
"This is exercise 1" is equal to
"This is Exercise 1"
StringBuilder Class:
• The StringBuilder class in Java provides a mutable sequence of characters.
• It allows efficient manipulation of strings without creating new objects for each
operation.
• StringBuilder is often used when there are a lot of string concatenations or
modifications in a loop to avoid excessive object creation.
• Syntax: StringBuilder sb = new StringBuilder();

Important Constructors of StringBuilder class

Constructor Description
It creates an empty String Builder with the initial capacity of 16
StringBuilder()
characters.
StringBuilder(String str) It creates a String Builder with the specified string.
StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.
// The StringBuilder append() method concatenates the given argument with this String.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Hello Java
}} Output: Hello Java
// The StringBuilder insert() method inserts the given string with this string at the given position.
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb); //prints HJavaello
} } Output: HJavaello
// The reverse() method of StringBuilder class reverses the current string.
class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
} } Output: olleH
Example Program using StringBuilder(int length)
public class StringBuilderExample {
public static void main(String[] args) {
// Create a StringBuilder with initial capacity of 50 characters
StringBuilder sb = new StringBuilder(50);
// Append some strings
sb.append("Hello");
sb.append(" ");
sb.append("World!");
// Output the result
System.out.println("StringBuilder content: " + sb.toString());
// Display the current capacity
System.out.println("Current capacity: " + sb.capacity());
// Display the current length of the string
System.out.println("Current length: " + sb.length());
}}
Output: StringBuilder content: Hello World!
Current capacity: 50
Current length: 12
Differences Between String and StringBuilder
String:
• Immutable- String objects are immutable, meaning once a String object is created, it cannot
be modified. Any modification to a String results in the creation of a new String object
• thread-safe - String is inherently thread-safe because it is immutable. Multiple threads can
access a String object concurrently without synchronization issues.
• less efficient for frequent modifications.

StringBuilder:
• Mutable- objects are mutable, meaning they can be modified without creating new objects.
This allows for efficient modifications, especially when performing multiple concatenations
or other string manipulations.
• not thread-safe - StringBuilder is not thread-safe. If multiple threads access a StringBuilder
instance concurrently, and at least one thread modifies it, external synchronization is required.
• more efficient for frequent modifications.
Wrapper Classes in OOP (Object-Oriented Programming)
• Wrapper classes in object-oriented programming (OOP) provide a way to convert
primitive into object and object into primitive.
• Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and
objects into primitives automatically. The automatic conversion of primitive into an
object is known as autoboxing and vice-versa unboxing.
• Wrapper classes are primarily used when objects are required, such as when using
collections, generics, or interacting with APIs that expect objects.
Common Wrapper Classes in Java:
1. Integer: Wraps an int value.
2. Double: Wraps a double value.
3. Boolean: Wraps a boolean value.
4. Character: Wraps a char value.
5. Byte: Wraps a byte value.
6. Short: Wraps a short value.
7. Long: Wraps a long value.
8. Float: Wraps a float value.
Autoboxing and Unboxing Example
• The automatic conversion of primitive data types into its equivalent Wrapper type
is known as boxing and the automatic conversion of wrapper class type into
corresponding primitive type is known as unboxing. So java programmer doesn't
need to write the conversion code.

class BoxingExample1{ class UnboxingExample1{


public static void main(String args[]){ public static void main(String args[]){
int a=50; Integer i=new Integer(50);
Integer a2=new Integer(a); //Boxing int a=i; // unboxing
Integer a3=5; //Boxing System.out.println(a);
System.out.println(a2+" "+a3); } }
}
}
Output:50 5 Output:50
Wrapper Classes in OOAD (Object-Oriented Analysis and Design):
• In Object-Oriented Analysis and Design (OOAD), the concept of wrapper classes
is not a central concern. OOAD is more focused on modeling objects, classes,
relationships, behaviors, and interactions in a software system. Wrapper classes,
while not a primary topic in OOAD, can be used as part of the implementation
details of the classes and objects being designed.
• However, when designing classes that encapsulate attributes of primitive data
types, using appropriate data types and designing methods to interact with
them in a meaningful way aligns with the principles of OOAD.
Java Arrays
• Java array is an object which contains elements of a similar data type.
• The elements of an array are stored in a contiguous memory location.
• It is a data structure where we store similar elements.
• We can store only a fixed set of elements in a Java array.
• Array in Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.
Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
• Random access: We can get any data located at an index position.
Disadvantages
• Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
Declaring an Array:
• Syntax: dataType[] arrayName;
• dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects.
• arrayName - it is an identifier.

• Here, the array can store 10 elements. We can also say that the size or length of the
array is 10. In Java, we can declare and allocate the memory of an array in one single
statement. For example, int[] age = {12, 4, 5, 2, 5}; (or)
• double[] data = new double[10]; int[] age = new int[5]; // declare an array
age[0] = 12; // initialize array
age[1] = 4;
//declare and initialize an array age[2] = 5;
age[3] = 2;
age[4] = 5;
//Java Program to illustrate how to declare, instantiate, initialize and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
// printing the elements of an array
for(int i=0;i<a.length;i++) //length is the property/method of array
System.out.println(a[i]);
}}
Output:
10
20
70
40
50
Methods in Java Array Class
• Java provides several methods within the java.util.Arrays class, including
Arrays.sort(), Arrays.copyOf(), Arrays.equals(), and more.
• They are static, meaning they can be called directly from the class itself, and are used
to manipulate arrays.
• The static methods of the Java Array class could be used to perform operations like:

 Filling the elements - Arrays.fill()


 Sorting the elements - Arrays.sort()
 Comparing array with other array - Arrays.equals()
 Converting the array elements to String - Arrays.toString()
 Many more...
Sorting Arrays with Arrays.sort()
Java provides a built-in method, Arrays.sort(), which sorts an array into ascending numerical
order or alphabetical order for strings.
Filling Arrays with Arrays.fill()
The Arrays.fill() method is used to fill an entire array with a single value. It can be useful
when you want to reset all values in an array or initialize them to a specific value.
Converting Arrays to Strings with Arrays.toString()
The Arrays.toString() method is a simple and effective way to convert an entire array into a
string format, which is useful for printing or logging purposes.
Copying Arrays with Arrays.copyOf()
The Arrays.copyOf() method allows you to create a new array that is a copy of an existing
array. This method is useful when you want to manipulate an array without affecting the
original data.
Comparing Arrays with Arrays.equals()
The Arrays.equals() method is used to check if two arrays are equal, meaning their length,
order, and elements are the same.
import java.util.Arrays; import java.util.Arrays;
public class Main { public class ArrayExample {
public static void main(String[] args) { public static void main(String[] args) {
String[] fruits = {"Apple", "Cherry", "Banana", "Dragonfruit"}; //Initialize the array
Arrays.sort(fruits); int[] array = new int[5];
for (String fruit : fruits) { Arrays.fill(array, 1);
System.out.print(fruit + " "); for (int i : array) {
} System.out.print(i + " ");
}} } }}
Output: Output:
Apple Banana Cherry Dragonfruit 11111
import java.util.Arrays; import java.util.Arrays;
public class ArrayExample { public class CopyArrayExample {
public static void main(String[] args) { public static void main(String[] args) {
int[] array = {1, 2, 3}; int[] original = {1, 2, 3, 9};
System.out.println(Arrays.toString(array)); int[] copy = Arrays.copyOf(original,
}} original.length);
System.out.println(Arrays.toString(copy));
Output: }}
[1, 2, 3] Output:
[1, 2, 3, 9]
Array List
• The ArrayList class is a resizable array, which can be found in the java.util package.
• ArrayList class in Java implement dynamic arrays, which can grow or shrink as
needed. They are part of the Java Collections Framework and are used to store and
manage collections of objects.
Difference between Array and Array List:
• The difference between a built-in array and an ArrayList in Java, is that the size of an
array cannot be modified.
• While elements can be added and removed from an ArrayList whenever you want.
Syntax
import java.util.ArrayList; // import the ArrayList class
ArrayList<Type> listName = new ArrayList<>(); // Declaring and Initializing
ArrayList<String> Alist = new ArrayList<String>(); // Example with strings
Note: Use wrapper classes like Integer, Double, Character, etc., instead of primitives
like int, double, char for ArrayList type.
The ArrayList class has many useful methods as follows.
1. Add elements 2. Access elements 3. Change elements 4. Remove elements
Note: Array indexes start with 0, [0] is the first element.
import java.util.ArrayList; System.out.println(cars.size());
public class Main { // size of ArrayList
public static void main(String[] args) { cars.clear(); // remove all the elements
ArrayList<String> cars = new ArrayList<>(); System.out.println(cars);
cars.add("Volvo"); }
cars.add("BMW"); }
cars.add("Ford"); Output:
System.out.println(cars); [Volvo, BMW, Ford]
cars.add(0, "Mazda"); // Insert element based on index [Mazda, Volvo, BMW, Ford]
System.out.println(cars); Mazda
System.out.println(cars.get(0)); // Accessing an element [Opel, Volvo, BMW, Ford]
cars.set(0, "Opel"); // modify an element [Volvo, BMW, Ford]
System.out.println(cars); 3
cars.remove(0); // removing an element []
System.out.println(cars);
Math Methods
• The Java Math class has many methods that allows you to perform mathematical
tasks on numbers.

Java Math.random() method


• Math.random() returns a double type pseudo-random number, greater than or equal
to zero and less than one.
• This method never returns exactly 1, but it can return 0.
• To use the random() method we need to import math class “import
java.lang.Math”.
// Java program to demonstrate working import java.lang.Math;
// of java.lang.Math.random() method class Gfg2 {
import java.lang.Math; public static void main(String args[]){
class Gfg1 { // define the range
public static void main(String args[]) int max = 10;
{ int min = 1;
// Generate random number int range = max - min + 1;
double rand = Math.random(); // generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
// Output is different everytime this code is executed
int rand = (int)(Math.random() * range);
System.out.println("Random Number:" + rand);
// Output is different everytime this code is executed
}} System.out.println(rand);
}}}
o/p: 0.5568515217910215
O/P: 6 8 10 10 5 3 6 10 4 2
import static java.lang.Math.*;
public class Main { Output:
public static void main(String[] args) { 2.0
System.out.println(Math.max(2.0, 0.25)); 18.0
System.out.println(Math.min(31.2f, 18.0f)); 0.0
System.out.println(Math.floor(0.40)); 5.0
System.out.println(Math.floor(5)); 1.0
-5.0
System.out.println(Math.ceil(0.40)); 4.7
System.out.println(Math.ceil(-5.1)); 1
System.out.println(Math.abs(-4.7)); -6
System.out.println(Math.round(0.60)); 3.0
System.out.println(Math.round(-5.9)); 0.0
System.out.println(Math.sqrt(9));
System.out.println(Math.log(1));
}
}
Math and Random in OOAD (Object-Oriented Analysis and Design):
• In the context of Object-Oriented Analysis and Design (OOAD), the
math and random concepts might not be central topics, but they play a
role when designing classes that involve mathematical calculations,
simulations, or statistical operations. These classes could be part of a
larger system where mathematical and random calculations are
required for specific behaviors.

• For example, in a simulation of a game where dice are rolled, a Dice


class could encapsulate the random number generation required for
the game's mechanics.
Number
• The Number class in Java is an abstract class that serves as the superclass for classes
representing numeric values, such as Integer, Double, Float, Long, Short, and Byte.
• The Number class is part of the java.lang package and provides methods to convert the
numeric value to different primitive types.

Key Points
 Abstract Class: Number is an abstract class, meaning you cannot instantiate it directly.
Instead, you work with its concrete subclasses.
 Primitive Conversion Methods: Number provides methods to convert the value of the
object to various primitive types, such as int, long, float, double, byte, and short.

Subclasses of Number are:


Byte, Short, Integer, Long, Float, Double
Methods of the Number Class
The Number class provides several methods that all its subclasses inherit:
 int intValue(): Converts the number to an int.
 long longValue(): Converts the number to a long.
 float floatValue(): Converts the number to a float.
 double doubleValue(): Converts the number to a double.
 byte byteValue(): Converts the number to a byte.
 short shortValue(): Converts the number to a short.
• In the context of the Number class and its wrapper subclasses like Integer,
Double, and Byte, the valueOf() methods are static factory methods that provide
a way to create instances of these wrapper objects.
public class NumberExamples { public static void demonstrateNumberMethods(Number
number) {
public static void main(String[] args) { System.out.println("Original Number: " + number);
// Creating instances of Number subclasses
using valueOf() // Using the inherited methods
Integer intNumber = Integer.valueOf(10); System.out.println("intValue(): " +
Double doubleNumber = Double.valueOf(3.14); number.intValue());
Byte byteNumber = Byte.valueOf((byte) 127); System.out.println("longValue(): " +
number.longValue());
System.out.println("--- Integer Example ---"); System.out.println("floatValue(): " +
demonstrateNumberMethods(intNumber); number.floatValue());
System.out.println("doubleValue(): " +
System.out.println("\n--- Double Example ---"); number.doubleValue());
demonstrateNumberMethods(doubleNumber); System.out.println("byteValue(): " +
number.byteValue());
System.out.println("\n--- Byte Example ---"); System.out.println("shortValue(): " +
demonstrateNumberMethods(byteNumber); number.shortValue());
} }
}
Output:
--- Integer Example ---
Original Number: 10
intValue(): 10 --- Byte Example ---
longValue(): 10 Original Number: 127
floatValue(): 10.0 intValue(): 127
doubleValue(): 10.0 longValue(): 127
byteValue(): 10shortValue(): 10 floatValue():127.0
--- Double Example --- doubleValue():127.0
Original Number: 3.14 byteValue(): 127
shortValue(): 127
intValue(): 3
longValue(): 3
floatValue(): 3.14
doubleValue(): 3.14
byteValue(): 3
shortValue(): 3
Number in OOAD (Object-Oriented Analysis and Design):

• In Object-Oriented Analysis and Design (OOAD), the concept of


"number" might not be a primary focus. However, numeric attributes
and calculations play a significant role in many software systems. The
design might involve classes that manage and perform operations on
numeric data.
File streams
• The File class from the java.io package, allows us to work with files.
• To use the File class, create an object of the class, and specify the filename or
directory name.
• File streams in Java are part of the java.io package, and they provide the mechanisms
for reading from and writing to files.

import java.io.File; // Import the File class


File myObj = new File("filename.txt"); // Specify the filename
Create a File
• To create a file, you can use the createNewFile() method. This method returns a
boolean value: true if the file was successfully created, and false if the file already
exists.
• Note that the method is enclosed in a try...catch block. This is necessary because it
throws an IOException if an error occurs (if the file cannot be created for some
reason).
Streams
• In java, the IO operations are performed using streams.
• A stream means continuous flow of data.
• A stream is a logical container of data that allows us to read from and write to it.
• A stream can be linked to a data source or destination like a cosole, file or
network connection by java IO system.
• Streams are defined in the java.io package.
• Stream based IO operations are performed using input and output streams.
• The input stream is used for input operations and output
stream is for output operations.
• In java, every program creates 3 streams automatically,
• System.out: Standard o/p stream for console o/p.
• System.in: Standard i/p stream for console i/p.
• System.err: Standard error stream for console error.
Depending upon the data a stream holds, it can be classified into:
• Byte Stream
• Character Stream

Byte stream
• Byte stream is used to read and
write a single byte (8 bits) of data.
• All byte stream classes are derived
from base abstract classes called
InputStream and OutputStream.

Character Stream
• Character stream is used to read
and write a single character of data.
• All the character stream classes are
derived from base abstract classes
Reader and Writer.
import java.io.File; // Ex: Creating a file
import java.io.IOException;
public class Firstfile {
public static void main(String[] args) {
try {
File myObj = new File("E:\\Amrita\\Even Sem 2024\\OOP\\JAVA LAB\\Files\\filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}}}
Output:
File created: filename1.tt
//File already exists.
Write To a File
• we use the FileWriter class together with its write() method to write some text to the
file we created. Note that when you are done writing to the file, you should close it
with the close() method:
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
public class Writefile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("E:\\Amrita\\Even Sem 2024\\OOP\\JAVA LAB\\Files\\filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}}}
Output:
Successfully wrote to the file.
Read a File
• we use the Scanner class to read the contents of the text file.
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("E:\\Amrita\\Even Sem 2024\\OOP\\JAVA LAB\\Files\\filename1.txt");
Scanner myReader = new Scanner(myObj);
// Loop through each line of input from the console
while (myReader.hasNextLine()) {
// Read the next line
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}}} o/p: Files in Java might be tricky, but it is fun enough!
Using Byte Streams (Binary Data)

import java.io.FileOutputStream; // Read bytes from the file


import java.io.FileInputStream; try {
import java.io.IOException; FileInputStream fis = new
public class ByteStreamExample { FileInputStream("binary.txt");
public static void main(String[] args) { int b;
// Write bytes to a file System.out.println("Reading binary file:");
try { while ((b = fis.read()) != -1) {
FileOutputStream fos = new System.out.print((char) b); // Convert byte to
FileOutputStream("binary.txt"); character
String data = "Binary stream data!"; }
fos.write(data.getBytes()); // Convert string to byte fis.close();
array } catch (IOException e) {
fos.close(); System.out.println("Error reading file.");
System.out.println("Data written using byte stream."); e.printStackTrace();
} catch (IOException e) { }}}
System.out.println("Error writing file."); Output:
e.printStackTrace(); Data written using byte stream.
Reading binary file:
Binary stream data!
Serialization
• Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It
is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
• The reverse operation of serialization is called deserialization
where byte-stream is converted into an object.

• The serialization and deserialization process is platform-independent, it means you can


serialize an object on one platform and deserialize it on a different platform.
• For serializing the object, we call the writeObject() method of ObjectOutputStream class,
and for deserialization we call the readObject() method of ObjectInputStream class.
• We must have to implement the Serializable interface for serializing the object.
• It is mainly used to travel object's state on the network (that is known as marshalling).
Ex: Java Serialization import java.io.*;
import java.io.Serializable; class Persist{
public class Student implements Serializable public static void main(String args[]){
{ try{
int id; //Creating the object
String name; Student s1 =new Student(211,"ravi");
public Student(int id, String name) { //Creating stream and writing the object
this.id = id; FileOutputStream fout=new FileOutputStream("f.txt");
this.name = name; // ObjectOutputStream - A stream for writing objects to an
} output stream by serializing them.
} ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
• The ObjectOutputStream class is used to out.flush();
write primitive data types, and Java //closing the stream
objects to an OutputStream. out.close();
• An ObjectInputStream deserializes System.out.println("success");
objects and primitive data written using }
an ObjectOutputStream catch(Exception e){
System.out.println(e);
} } } o/p: success
Generics
• Generics are a feature in many object-oriented programming languages that allow you
to create classes, interfaces, and methods with placeholders for types.
• They provide a way to write code that can work with different data types while
maintaining type safety.
• To create an instance of generic class BaseType <Type> obj = new BaseType <Type>()
Key Points:
• Generics enable the creation of classes or methods that can work with different types
without sacrificing type safety.
• They allow you to define a class or method with placeholders for types (type
parameters).
• Type parameters are specified when using the generic class or method and determine the
actual data type.
• Generics are particularly useful for collections, algorithms, and classes where type
flexibility is required.
Why to use Java Generics
1. Type-safety
• We can hold only a single type of objects in generics. It doesn't allow to store other objects.
• Without Generics, we can store any type of objects.
2. Type casting is not required: There is no need to typecast the object. Before Generics, we need to type cast.
3. Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good
programming strategy says it is far better to handle the problem at compile time than runtime.

List list = new ArrayList(); List list = new ArrayList(); List<String> list = new ArrayList<String
list.add(10); list.add("hello"); >();
list.add("10"); String s = (String) list.get(0); list.add("hello");
With Generics, it is required to specify the t //typecasting After Generics, we don't nee list.add(32);//Compile Time Error
ype of object we need to store. d to typecast the object.
List<Integer> list = new ArrayList<Integer List<String> list = new ArrayList<String>(
>(); );
list.add(10); list.add("hello");
list.add("10");// compile-time error String s = list.get(0);

In Java, the iterator() method is used to obtain an iterator over a collection. An iterator is an object that
allows you to traverse through the elements of a collection (such as arraylists, lists, sets, etc.) one at a time.
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add(“ravi");
//list.add(32); //compile time error
String s=list.get(1); //type casting is not required
System.out.println("element is: "+s); .
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }

o/p: element is: ravi


rahul
ravi
class Box<T> { // Generics class example
private T value;
• T is a type parameter. It stands for
public void setValue(T value) {
a generic type.
this.value = value;
} • You can think of T as a
public T getValue() { placeholder that will be replaced
return value; with a real data type when you
}} create an object of this class.

public class Main { • A private variable value of type T.


public static void main(String[] args) { • A setter method setValue() that
Box<String> stringBox = new Box<>(); accepts a value of type T.
stringBox.setValue("Hello"); • A getter method getValue() that
System.out.println(stringBox.getValue());
returns the value of type T.
}}
o/p:
Hello
This program demonstrates a generic method in Java that can print elements of any
array type (e.g., Integer[], String[], etc.).
public class GenericMethodExample { • This is a generic method.
public static <T> void printArray(T[] array) { • <T> tells the compiler that T is a
for (T element : array) { type parameter (can be Integer,
System.out.print(element + " "); String, etc.).
}
• T[] array means it takes an array of
System.out.println();
any type T.
}
public static void main(String[] args) { • The same printArray method works
Integer[] intArray = {1, 2, 3}; for both Integer[] and String[]
String[] strArray = {"A", "B", "C"}; arrays.
printArray(intArray); • Generic methods make your code
printArray(strArray); flexible and type-safe, allowing
}} reuse with different data types
o/p: 1 2 3 without rewriting logic.
ABC
Collections in Java
• The Collection is an interface used to represent group of objects known as elements.
• This framework provides many interfaces (Set, List, Queue, Deque) and their implemented
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet) in
order to store, retrieve, and manipulate group of objects(elements) in a single entity.
• Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Key Features of Collection Framework:
 Reusable data structures like Lists, Sets, Maps, and Queues.
 Algorithms for searching, sorting, shuffling, etc.
 Thread-safe versions of collections are available.
 Supports generics, making collections type-safe.
 Includes support for iteration using the Iterator interface.
Interfaces provided by collections framework

1. Collection Interface: The root of the


collection hierarchy.
2. List Interface: An ordered collection (also
known as a sequence).
3. Set Interface: A collection that does not
allow duplicate elements.
4. Queue Interface: A collection designed for
holding elements prior to processing.
5. Map Interface: An object that maps keys to
values, without duplicates in keys.
Hierarchy of collections interface
Green Colour – Interfaces
Blue Colour – Classes
Class to class – extends
interface to class - implements
Hierarchy of Map interface

Green Colour – Interfaces


Blue Colour - Classes
Interfaces that Extend the Java Collections Interface
• The collection framework contains multiple interfaces where every interface is used to store a
specific type of data.
1. Iterable Interface
• Root interface of the Collection framework.
• Provides the ability to iterate through a collection.
• Contains one method:
Iterator<T> iterator();
2. Collection Interface
• Extends Iterable.
• The foundation interface for all collection types (List, Set, Queue, etc.).
• Declares core collection operations like:
• add(), remove(), clear(), size(), contains(), etc.
• Ensures common method structure across all collections.
These methods are common to most collection types like List, Set, Queue, etc.
Method Description
add(E) Adds the specified element e to the collection.
remove(Object o) Removes a single instance of the specified element o from the collection.
size() Returns the number of elements in the collection.
clear() Removes all elements from the collection.
contains(Object o) Returns true if the collection contains the specified element o.
iterator() Returns an Iterator over the elements in the collection, useful for traversing.
Common Methods
Collection Interface:
• add(), remove(), size(), clear(), contains(), iterator()
List:
• get(index), set(index, value), add(index, value), remove(index)
Set:
• add(), remove(), contains()
Map:
• put(key, value), get(key), remove(key), containsKey(), keySet(),
entrySet()
Key Classes
1.ArrayList: A resizable array implementation of the List interface.
2.LinkedList: A doubly linked list implementation of the List and Deque interfaces.
3.HashSet: A hash table-backed implementation of the Set interface.
4.TreeSet: A NavigableSet implementation based on a red-black tree.
5.HashMap: A hash table-backed implementation of the Map interface.
6.TreeMap: A NavigableMap implementation based on a red-black tree.
7.PriorityQueue: An unbounded priority queue based on a priority heap.
1. List Interface – ArrayList class
• List interface Extends Collection.
• Represents an ordered collection (also allows duplicates). You can access elements by index.
• Commonly implemented by classes: ArrayList, LinkedList, Vector, Stack
• Supports indexed access and manipulation:
List<T> list = new ArrayList<>();
Array List class: A resizable array that implements the List interface.
• Key Features:
 Maintains insertion order.
 Allows duplicate elements.
 Provides fast random access using an index (get(index)).
• Use Case: When frequent access and iteration are needed but insertions/deletions are less
frequent.
Example:
List<String> names = new ArrayList<>();
names.add(“Raj");
names.add(“Kumar");

Method Description
get(int index) Returns the element at the specified position in the list.
set(int index, E element) Replaces the element at the specified position with the specified element.
add(int index, E element) Inserts the specified element at the specified position.
remove(int index) Removes the element at the specified position in the list.
import java.util.ArrayList; Example demonstrating how to create a list, add elements
import java.util.List; to it, and iterate over its elements:
public class ListExample {
public static void main(String[] args) {
//ArrayList is a concrete class that implements the List interface.
//It provides a resizable array implementation of the List interface.
//List is an interface that represents an ordered collection (or sequence) of elements.
List<String> list = new ArrayList<>();
list.add("Amrita");
list.add("OOP"); Output:
list.add("CSE"); Amrita
for (String fruit : list) { OOP
System.out.println(fruit); CSE
} Size of the list: 3
// Additional list operations Element at index 1: OOP
List after removing 'CSE':
System.out.println("Size of the list: " + list.size());
[Amrita, OOP]
System.out.println("Element at index 1: " + list.get(1));
list.remove("CSE");
System.out.println("List after removing 'CSE': " + list);
}}
2. Set Interface – HashSet class
• Set is an interface in the Java Collections Framework that represents a collection that does not
allow duplicate elements.
• Description: Hashset Implements the Set interface using a hash table.
• Key Features:
 No duplicate elements.
 No guaranteed order of elements.
 Offers constant time performance for add, remove, and contains (O(1)).
• Use Case: When uniqueness of elements is required and order doesn’t matter.
• Example:
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Apple"); // Duplicate ignored
Method Description
add(E) Adds the specified element if it's not already present.
remove(Object o) Removes the specified element if present.
contains(Object o) Checks if the set contains the specified element.
import java.util.HashSet; for (String fruit : set) {
import java.util.Set; System.out.println(fruit);
public class SetExample { }
public static void main(String[] args) { // Additional set operations
// Create a new set of strings System.out.println("Size of the set: " + set.size());
Set<String> set = new HashSet<>(); System.out.println("Set contains 'Banana': " +
// Add some elements to the set set.contains("Banana"));
set.add("Apple"); set.remove("Banana");
set.add("Banana"); System.out.println("Set after removing 'Banana': " + set);
set.add("Cherry"); }}
set.add("Apple"); Output: Apple
// Duplicate element, will not be added Cherry
// Iterate over the elements of the set and print Banana
them Size of the set: 3
Set contains 'Banana': true
Set after removing 'Banana': [Apple, Cherry]
4. Map Interface
• Not a child of Collection — it's separate.
• Represents a key-value pair data structure.
• Each key maps to at most one value.
• No duplicate keys allowed, but values can be duplicated.
• This map interface is implemented by various classes like HashMap, TreeMap, etc.
Example:
Map<T> hm = new HashMap<> ();
Map<T> tm = new TreeMap<> (); Where T is the type of the object.
Method Description
put(K key, V value) Adds a key-value pair or updates the value if the key already exists.
get(Object key) Returns the value associated with the specified key, or null if not found.
remove(Object key) Removes the mapping for the specified key.
containsKey(Object key) Checks if the map contains a mapping for the specified key.
keySet() Returns a Set view of all the keys in the map.
entrySet() Returns a Set view of all key-value pairs (Map.Entry<K,V>) in the map.
HashMap class: A map that uses a hash table for fast key lookup. To store and retrieve data using key-value pairs
Map.Entry<K, V>: Represents a key-value pair in the map.

// Java program to demonstrate the working of a HashMap


import java.util.*;
public class HashMapDemo {
// Main Method
public static void main(String args[])
{ Output:
// Creating HashMap and adding elements Value for 1 is Run
Map<Integer, String> hm= new HashMap<Integer, String>(); 1 Run
hm.put(1, “Run"); 2 and
hm.put(2, “and"); 3 Run
hm.put(3, “Run");
// Finding the value for a key
System.out.println("Value for 1 is " + hm.get(1));
// Traversing through the HashMap
for (Map.Entry<Integer, String> e : hm.entrySet())
System.out.println(e.getKey() + " "+ e.getValue());
}
}
3. Queue Interface
• The Queue interface represents a data structure that follows the FIFO (First-In-First-Out)
principle—just like a real-world queue.
• In this structure, the first element added is the first one to be removed.
• This interface is dedicated to storing all the elements where the order of the elements matter.
• Example: whenever we try to book a ticket, the tickets are sold on a first come first serve basis.
Therefore, the person whose request arrives first into the queue gets the ticket.
• Java provides several classes that implement the Queue interface, including:
 PriorityQueue
 ArrayDeque, etc.
Syntax:
Queue <T> pq = new PriorityQueue<> ();
Queue <T> ad = new ArrayDeque<> (); Where T is the type of the object.
Priority Queue class:
Definition:
• A PriorityQueue is a special type of queue where elements are processed based on priority, not just
insertion order.
Key Features:
• Elements are ordered by natural order (like numbers in ascending order), or using a custom
Comparator.
• Internally implemented using a priority heap.
• Does not allow null elements.
Order of Processing:
• Unlike regular queues (FIFO), the highest priority element is processed first.
• The element with the least value (by default) is given the highest priority.
// Java program to demonstrate the working of priority queue in Java
import java.util.*;
class GfG {
// Main Method
public static void main(String args[])
{
// Creating empty priority queue
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();
// Adding items to the pQueue using add()
pQueue.add(10);
pQueue.add(20);
pQueue.add(15); Output
// Printing the top element of PriorityQueue 10
System.out.println(pQueue.peek()); 10
// Printing the top element and removing it from the PriorityQueue container 15
System.out.println(pQueue.poll());
// Printing the top element again
System.out.println(pQueue.peek());
}
}
Vector in OOP (Object-Oriented Programming):
• Both Vector and ArrayList are classes in Java that implement dynamic arrays, which can grow or shrink as
needed. They are part of the Java Collections Framework and are used to store and manage collections of
objects.
• However, the primary difference between a vector and an ArrayList is that a Vector is synchronized and an
ArrayList is non-synchronized.
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<Integer> numbers = new Vector<>();
Output: numbers.add(10);
Numbers in Vector: numbers.add(20);
10 numbers.add(30);
20 System.out.println("Numbers in Vector:");
30 for (int number : numbers) {
System.out.println(number);
}
}}
Iterator and Iterable
• Iterator and Iterable are interfaces in Java that provide a way to traverse and iterate
over collections like lists, sets, etc. They are part of the Java Collections
Framework and are used to provide a standardized way of iterating through elements
in various collection classes.

• Iterator Interface: The Iterator interface is used to traverse a collection element by


element.
• It performs operations like retrieving and removing elements during traversal.

• This interface has three methods:


 boolean hasNext() - Returns true if there are more elements to iterate over.
 next() - Returns the next element in the iteration.
 remove() - Removes the last element returned by the iterator.
import java.util.ArrayList;
Output:
import java.util.Iterator; Apple
public class IteratorExample { Banana
public static void main(String[] args) { Orange
ArrayList<String> fruits = new ArrayList<>(); After the remove()
fruits.add("Apple"); method is called :
fruits.add("Banana"); [Apple, Banana]
fruits.add("Orange");
Iterator<String> iterator = fruits.iterator(); // Get an iterator for the list of fruits
while (iterator.hasNext()) { // Use the iterator to traverse the list
String fruit = iterator.next();
System.out.println(fruit);
}
iterator.remove(); // removes the last element
System.out.println( "After the remove() method is called : " + fruits);
}}
Iterable
1. Iterable Interface
• The Iterable interface is the root interface for all collection classes that can be iterated
using an iterator (e.g., in a for-each loop).
• The collection class should import java.util package
Key Point:
• It has only one method: Iterator<T> iterator();
Common Usage:
• When a class implements Iterable, it can be used in the enhanced for-each loop.
import java.util.*;
public class IterableExample { Output:
public static void main(String[] args) { Alice
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); Bob
for (String name : names) { // uses Iterable interface Charlie
System.out.println(name);
} }}
Comparator and Comparable in Java's Collection Framework:

• Java's Collection Framework provides two main interfaces, Comparator and


Comparable, that allow you to define custom sorting behavior for objects in
collections. These interfaces help you achieve ordering based on criteria other than
the natural ordering of objects.

• Comparable Interface: The Comparable interface allows you to define a natural


ordering for objects of a class. Objects that implement Comparable can be sorted
using methods like Collections.sort().
import java.util.ArrayList; public class Main {
import java.util.Collections; public static void main(String[] args) {
class Student implements Comparable<Student> ArrayList<Student> students = new ArrayList<>();
{ students.add(new Student("Alice", 20));
private String name; students.add(new Student("Bob", 18));
private int age; students.add(new Student("Carol", 22));
public Student(String name, int age) { Collections.sort(students); //uses compareTo()
this.name = name; for (Student student : students) {
this.age = age; System.out.println(student);
} }
public int compareTo(Student other) { }}
return Integer.compare(this.age, other.age);
} // sort by age Output:
public String toString() { Bob (18 years)
return name + " (" + age + " years)"; Alice (20 years)
}} Carol (22 years)
• Comparator Interface: The Comparator interface allows you to define custom ordering for objects that might
not implement Comparable. It is especially useful when you need to sort objects based on multiple criteria.

class Student { list.add(new Student(103, "Ravi"));


int rollNo; list.add(new Student(101, "Anu"));
String name; list.add(new Student(102, "Kiran"));
Student(int rollNo, String name) { Collections.sort(list, new NameComparator()); //
this.rollNo = rollNo; uses compare()
this.name = name; for (Student s : list)
}}// Comparator to sort by name System.out.println(s.rollNo + " " + s.name); }}
class NameComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) { Output:
return s1.name.compareTo(s2.name); 101 Anu
}} 102 Kiran
public class ComparatorExample { 103 Ravi
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
The End…

Thank you for your co-operation.


class Number:
def init (self, value):
self.value = value

def square(self):
return self.value ** 2

def multiply(self, factor):


return self.value * factor

num_obj = Number(5)
print("Square:", num_obj.square())
print("Multiplied:", num_obj.multiply(3))
Number in OOP (Object-Oriented
Programming):
In the context of Object-Oriented Programming (OOP), the concept of
"number" refers to the representation and manipulation of numeric
values using classes and objects. In most programming languages,
primitive data types like integers, floating-point numbers, and more
complex numeric types can be encapsulated within objects to provide
additional functionality and behavior.
Math and Random in OOP (Object-Oriented Programming):
Math: In OOP, the math module (or similar mathematical libraries in other programming languages)
provides a set of functions and constants for performing mathematical operations. These functions
are often static methods of a Math class or module.
import math
class MathCalculator:
def init (self, value):
self.value = value

def calculate_square_root(self):
return math.sqrt(self.value)

def calculate_power(self, exponent):


return math.pow(self.value, exponent)

calc = MathCalculator(16)
print("Square Root:", calc.calculate_square_root())
print("Power:", calc.calculate_power(3))
Random: The random module is used to generate pseudo-random numbers in OOP.
It provides various functions to generate random numbers, and these functions can
be encapsulated within classes.

import random
class RandomNumberGenerator:
def generate_integer(self, start, end):
return random.randint(start, end)

def generate_float(self):
return random.random()

rng = RandomNumberGenerator()
print("Random Integer:", rng.generate_integer(1, 10))
print("Random Float:", rng.generate_float())
Array Methods in OOP (Object-Oriented
Programming):
Arrays are a fundamental data structure in programming, and various programming languages provide built-in
array methods for manipulating arrays. These methods can be encapsulated within classes to create more
organized and reusable code.

class ArrayManipulator:
def init (self, array):
self.array = array
def sort_array(self):
return sorted(self.array)
def find_maximum(self):
return max(self.array)
arr_obj = ArrayManipulator([3, 1, 5, 2, 4])
sorted_arr = arr_obj.sort_array()
max_value = arr_obj.find_maximum()
print("Sorted Array:", sorted_arr)
print("Maximum Value:", max_value)
Array Methods in OOAD (Object-Oriented Analysis and
Design):
• In Object-Oriented Analysis and Design (OOAD), array methods
become important when designing classes that involve the
management and manipulation of collections of objects. These
methods can be part of the behavior of classes responsible for
handling lists, arrays, or other data structures.
• For instance, consider a library system where a Library class manages
an array of Book objects. The Library class might have methods like
findBook to search for books, addBook to add books to the collection,
and sortBooks to organize the books alphabetically.
File Streams in OOP (Object-Oriented Programming):
File streams are a way to perform input and output operations with files in object-oriented programming. They
involve creating classes that encapsulate file-related operations for reading and writing data to files.
class FileManager:
def init (self, file_name):
self.file_name = file_name
def read_file(self):
with open(self.file_name, 'r') as file:
return file.read()
def write_file(self, data):
with open(self.file_name, 'w') as file:
file.write(data)
file_handler = FileManager("data.txt")
content = file_handler.read_file()
print("File Content:", content)
new_data = "This is new content."
file_handler.write_file(new_data)
File Streams in OOAD (Object-Oriented
Analysis and Design):
In the context of Object-Oriented Analysis and Design (OOAD), file
streams play a role when designing classes that need to interact with
external data sources, such as files. These classes encapsulate the
interaction and provide a higher-level interface for the rest of the
system.

For example, in a larger system like a document management


application, a Document class might use a FileManager class to handle
reading and writing of documents to files. This separation allows the
Document class to focus on its core responsibilities, while the
FileManager class handles file-related concerns.
• OBJECT ORIENTED PARADIGM
Syllabus
Unit 3
Generics, Collection framework- Comparator and Comparable, Vector
and Array list, Iterator and Iterable, Introduction to Threads, Creating
Threads, Thread States, Runnable Threads, Coordinating Threads,
Interrupting Threads, Runnable Interface, Swings – Frame Layouts,
Widgets, displaying image and graphics.
Generics in OOP (Object-Oriented Programming):
• Generics are a feature in many object-oriented programming languages
that allow you to create classes, interfaces, and methods with placeholders
for types. They provide a way to write code that can work with different
data types while maintaining type safety.
• Key Points:
• Generics enable the creation of classes or methods that can work with
different types without sacrificing type safety.
• They allow you to define a class or method with placeholders for types
(type parameters).
• Type parameters are specified when using the generic class or method and
determine the actual data type.
• Generics are particularly useful for collections, algorithms, and classes
where type flexibility is required.
class MyGenericClass<T> {
private T value;
MyGenericClass(T value) {
this.value = value;
}
T getValue() {
return value;
}
}

public class Main {


public static void main(String[] args) {
MyGenericClass<Integer> intObj = new MyGenericClass<>(10);
MyGenericClass<String> strObj = new MyGenericClass<>("Hello");

System.out.println("Integer Value: " + intObj.getValue());


System.out.println("String Value: " + strObj.getValue());
}
}
Generics in OOAD (Object-Oriented Analysis and Design):
• In Object-Oriented Analysis and Design (OOAD), the concept of
generics aligns with the principles of creating flexible and reusable
classes that can work with different types while maintaining
consistency and safety. Generics are particularly useful when
designing classes that deal with collections, data structures, and
algorithms.

• For example, when designing a generic List class, you're able to create
a class that can store elements of any type while preserving type
information for retrieval.
Comparator and Comparable in Java's
Collection Framework:
• Java's Collection Framework provides two main interfaces, Comparator
and Comparable, that allow you to define custom sorting behavior for
objects in collections. These interfaces help you achieve ordering based
on criteria other than the natural ordering of objects.

• Comparable Interface: The Comparable interface allows you to define a


natural ordering for objects of a class. Objects that implement
Comparable can be sorted using methods like Collections.sort().
import java.util.ArrayList;
import java.util.Collections;
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public int compareTo(Student other) {
return Integer.compare(this.age, other.age);
}
public String toString() {
return name + " (" + age + " years)";
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 18));
students.add(new Student("Carol", 22));
Collections.sort(students);
for (Student student : students) {
System.out.println(student);
}
}
}
• Comparator Interface: The Comparator interface allows you to define custom ordering for objects that might not implement Comparable. It is especially useful
when you need to sort objects based on multiple criteria.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Student {
private String name;
private int age;

public Student(String name, int age) {


this.name = name;
this.age = age;
}

public String toString() {


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

public class Main {


public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 18));
students.add(new Student("Carol", 22));

Collections.sort(students, new Comparator<Student>() {


public int compare(Student s1, Student s2) {
return s1.toString().compareTo(s2.toString());
}
});

for (Student student : students) {


System.out.println(student);
}
}
}
• In the first example, the Student class implements Comparable to
provide a natural ordering based on age. In the second example, an
anonymous Comparator is used to sort the students based on their
names.
• In the context of Object-Oriented Analysis and Design (OOAD),
Comparator and Comparable can be used to model how objects
should be sorted and compared within a larger system. For example,
if you are designing a library management system, you might model a
Book class with a Comparable implementation to sort books based on
ISBN or publication date. You could also define custom Comparator
instances for different sorting criteria.
• The main idea is to encapsulate the sorting and comparison behavior
within the relevant classes, allowing them to be used consistently
throughout the system's design and implementation.
Vector and ArrayList in OOP (Object-Oriented Programming):
Both Vector and ArrayList are classes in Java that implement dynamic arrays, which can grow or shrink as
needed. They are part of the Java Collections Framework and are used to store and manage collections of
objects.
import java.util.ArrayList; public
class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();

names.add("Alice");
names.add("Bob");
names.add("Carol");

System.out.println("Names in ArrayList:"); for


(String name : names) {
System.out.println(name);
}}}
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
Vector<Integer> numbers = new Vector<>();

numbers.add(10);
numbers.add(20);
numbers.add(30);

System.out.println("Numbers in Vector:");
for (int number : numbers) {
System.out.println(number);
}
}
}
Vector and ArrayList in OOAD (Object-
Oriented Analysis and Design):
• In the context of Object-Oriented Analysis and Design (OOAD), Vector and

ArrayList are part of the Java Collections Framework and are considered as tools or implementations
rather than primary modeling concepts.
• However, when designing classes that involve collections of objects, you might decide to use either
Vector or ArrayList based on your specific requirements. For example, if thread safety is crucial,
Vector might be preferred due to its synchronized nature.
• In an OOAD context, these classes may be used to represent collections of objects, but the primary focus
is on the design of classes, their relationships, behaviors, and interactions within the system.
Iterator and Iterable in OOP (Object-Oriented Programming):

• Iterator and Iterable are interfaces in Java that provide a way to


traverse and iterate over collections of objects. They are part of the
Java Collections Framework and are used to provide a standardized
way of iterating through elements in various collection classes.

• Iterator Interface: The Iterator interface provides methods for


sequentially accessing elements in a collection and performing
operations like retrieving and removing elements during traversal.
import
java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {


public static void main(String[] args) {
ArrayList<String> fruits = new
ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");

Iterator<String> iterator = fruits.iterator();


while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
}
}
}
• Iterable Interface: The Iterable interface represents objects that can be iterated using an Iterator. Classes
implementing Iterable provide an iterator() method that returns an instance of Iterator.
import java.util.ArrayList;
import java.util.Iterator;
public class IterableExample implements Iterable<String>
{
private ArrayList<String> items = new ArrayList<>();
public void addItem(String item)
{ items.add(item);
}
@Override
public Iterator<String> iterator()
{ return items.iterator();
}
public static void main(String[] args) {
IterableExample iterableExample = new IterableExample();
iterableExample.addItem("One");
iterableExample.addItem("Two");
iterableExample.addItem("Three");
for (String item : iterableExample)
{ System.out.println(item);
}
}
}
Books to Follow
Text Book(s):
• Weisfeld M. The object-oriented thought process. Third edition, Addison-Wesley Professional; 2013.
• Wampler BE. The Essence of Object-Oriented Programming with Java and UML. Addison-Wesley
Professional;
• 2002.
Reference(s):
• Deitel PJ. Java how to program. Eleventh Edition, Pearson; 2018.
• Nino J, Hosch FA. Introduction to programming and object-oriented design using Java. Wiley India Private
Limited; 2010.
• Naughton P. and Schildt H. Java 2: the complete reference. Eighth Edition, Tata McGraw- Hill; 2011.
• Bahrami A. Object Oriented Systems Development. Second Edition, McGraw-Hill; 2008.
• Booch G, Maksimchuk RA. Object-oriented Analysis and Design with Applications. Third Edition, Pearson
Education; 2009.

You might also like