Object Oreinted Programming
Object Oreinted Programming
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)
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.
• In OOAD, you not only focus on coding but also on the overall system design,
requirements analysis, and architecture.
• This analysis lays the foundation for a well-organized and maintainable codebase.
Object-Oriented Approach
• 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.
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
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 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.
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.
Class Diagram
Object Diagram
Class to Object Diagram Example - Order System
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.
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.
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
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.
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);
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.
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 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
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.
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);
}}
• 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.
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");
• 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
• 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
A Java constructor can also accept one or more parameters. Such constructors are
known as parameterized constructors (constructors with parameters).
Example: Parameterized Constructor
• 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.
@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.
• 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");
}
}
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.
• 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.
java.lang: Contains language support classes(e.g classes which defines primitive data
types, math operations). This package is automatically imported.
java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
java.awt: Contain classes for implementing the components for graphical user interfaces
(like button, menus etc).
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.
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
Output:Hello
3) Using fully qualified name
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.
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
• java.lang is imported by
default in every Java
program, so there's no need
for manual import.
• 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.
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):
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();
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.
• 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:
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.
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)
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());
} } }
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.
def square(self):
return self.value ** 2
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)
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, 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.
names.add("Alice");
names.add("Bob");
names.add("Carol");
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):