You are on page 1of 148

Department Of Information science

BVBCET

[ESSENTIALS OF
INFORMATION TECHNOLOGY]

Subject Code: ISO404


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Unit 1- Chapter 1- Introduction to Computer Systems


Computer System:
The complete computer is made up of the CPU (Central Processing Unit), memory and related electronics (main
cabinet), all the peripheral devices connected to it and its operating system.
Computer systems fall into two categories:
clients
Servers.

Client Computer:
A client computer is an individual computer that accesses the information and programs stored on a server as part
of a network environment.

Server Computer:
"Servers" are computer programs running to serve the requests of other programs, the "clients".

Components of Computer System:


Components of computer are made up of two devices namely, Processing Device and Storage Device.
Processing devices are the components responsible for the processing of information within the computer
system. This includes devices such as the CPU, memory and motherboard.
Storage devices are components which allow data to be stored within a computer system. This includes HDD
(Hard disk drives).

Computers are made of the following basic components:


Motherboard - This is where the core components of your computer reside which are listed below. Also the
support cards for video, sound, networking and more are mounted into this board.

1. Microprocessor - This is the brain of your computer. It performs commands and instructions and controls
the operation of the computer.

2. Memory - The RAM in your system is mounted on the motherboard. This is memory that must be powered
on to retain its contents.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

3. Drive controllers - The drive controllers control the interface of your system to your hard drives. The
controllers let your hard drives work by controlling their operation. On most systems, they are included on
the motherboard, however you may add additional controllers for faster or other types of drives.

Hard disk drive(s) - This is where your files are permanently stored on your computer. Also, normally, your
operating system is installed here.

CD-ROM drive(s) - This is normally a read only drive where files are permanently stored. There are now
read/write CD-ROM drives that use special software to allow users to read from and write to these drives.

Floppy drive(s) - A floppy is a small disk storage device that today typically has about 1.4 Megabytes of
memory capacity.

Other possible file storage devices include DVD devices, Tape backup devices, and some others

Monitor - This device which operates like a TV set lets the user see how the computer is responding to their
commands.

Keyboard - This is where the user enters text commands into the computer.

Mouse - A point and click interface for entering commands which works well in graphical environments.

Program Execution Cycle:


An instruction cycle (sometimes called fetch-and-execute cycle, fetch-decode-execute cycle, or FDX) is the basic
operation cycle of a computer. It is the process by which a computer retrieves a program instruction from its memory,
determines what actions the instruction requires, and carries out those actions.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Computer Networks:
A computer network or data network is a telecommunications network which allows computers to exchange data. In
computer networks, networked computing devices pass data to each other along network links (data connections).
The connections between nodes are established using either cable media or wireless media. The best-known
computer network is the Internet.

Network computer devices that originate, route and terminate the data are called network nodes. Nodes can include
hosts such as personal computers, phones, servers as well as networking hardware. Two such devices can be said
to be networked together when one device is able to exchange information with the other device, whether or not they
have a direct connection to each other.

Computer networks differ in the transmission media used to carry their signals, the communications protocols to
organize network traffic, the network's size, topology and organizational intent. In most cases, communications
protocols are layered on (i.e. work using) other more specific or more general communications protocols, except for
the physical layer that directly deals with the transmission media.

Characteristics of a computer network:

Share Resources from one computer to another

Create files and store them in one computer, access those files from the other computer(s) connected over
the network

Connect a printer, scanner, or a fax machine to one computer within the network and let other computers of
the network use the machines available over network.

Computer network is mainly divided into 3 types

1. LAN (Local Area Network)

2. MAN (Metropolitan Area Network)

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

3. WAN (Wide Area Network)

LAN:

A computer network spanned inside a building and operated under single administrative system is generally termed
as Local Area Network (LAN). Usually, LAN covers an organization offices, schools, colleges or universities. Number
of systems connected in LAN may vary from as least as two to as much as 16 million.

LAN provides a useful way of sharing the resources between end users. The resources such as printers, file
servers, scanners, and internet are easily sharable among computers.

Fig 1: LAN Network

MAN:

The Metropolitan Area Network (MAN) generally expands throughout a city such as cable TV network. It can be in the
form of Ethernet,Token-ring, ATM, or Fiber Distributed Data Interface (FDDI).

Metro Ethernet is a service which is provided by ISPs. This service enables its users to expand their Local Area
Networks. For example, MAN can help an organization to connect all of its offices in a city.

Backbone of MAN is high-capacity and high-speed fiber optics. MAN works in between Local Area Network and
Wide Area Network. MAN provides uplink for LANs to WANs or internet.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Fig 2: MAN Network

WAN:

As the name suggests, the Wide Area Network (WAN) covers a wide area which may span across provinces and
even a whole country. Generally, telecommunication networks are Wide Area Network. These networks provide
connectivity to MANs and LANs. Since they are equipped with very high speed backbone, WANs use very expensive
network equipment.

Fig 3: WAN Network

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Software & its Classification:

Software is a set of programs, which is designed to perform a well-defined function. A program is a sequence of
instructions written to solve a particular problem.

There are two types of software

System Software

Application Software

System Software:

The system software is collection of programs designed to operate, control, and extend the processing capabilities
of the computer itself. System software are generally prepared by computer manufactures. These software products
comprise of programs written in low-level languages which interact with the hardware at a very basic level. System
software serves as the interface between hardware and the end users.

Some examples of system software are Operating System, Compilers, Interpreter, Assemblers etc.

Features of system software are as follows:

Close to system

Fast in speed

Difficult to design

Difficult to understand

Less interactive

Smaller in size

Difficult to manipulate

Generally written in low-level language

Application Software:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Application software products are designed to satisfy a particular need of a particular environment. All software
applications prepared in the computer lab can come under the category of Application software.

Application software may consist of a single program, such as a Microsoft's notepad for writing and editing simple
text. It may also consist of a collection of programs, often called a software package, which work together to
accomplish a task, such as a spreadsheet package.

Examples of Application software are following:

Payroll Software

Student Record Software

Inventory Management Software

Income Tax Software

Railways Reservation Software

Microsoft Office Suite Software

Microsoft Word

Microsoft Excel

Microsoft PowerPoint

Features of application software are as follows:

Close to user

Easy to design

More interactive

Slow in speed

Generally written in high-level language

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Easy to understand

Easy to manipulate and use

Bigger in size and requires large storage space

Relationship between Hardware and Software:

Hardware and software are mutually dependent on each other. Both of them must work together to make a
computer produce a useful output.

Software cannot be utilized without supporting hardware.

Hardware without set of programs to operate upon cannot be utilized and is useless.

To get a particular job done on the computer, relevant software should be loaded into the hardware

Hardware is a one-time expense.

Software development is very expensive and is a continuing expense.

Different software applications can be loaded on a hardware to run different jobs.

Software acts as an interface between the user and the hardware.

If hardware is the 'heart' of a computer system, then software is its 'soul'. Both are complimentary to each
other.

Operating System:
An operating system (OS) is a collection of software that manages computer hardware resources and provides
common services for computer programs. The operating system is a vital component of the system software in a
computer system.

An operating System (OS) is an intermediary between users and computer hardware. It provides users an
environment in which a user can execute programs conveniently and efficiently.

In technical terms, It is a software which manages hardware. An operating System controls the allocation of
resources and services such as memory, processors, devices and information.

Definition:
An operating system is a program that acts as an interface between the user and the computer hardware and
controls the execution of all kinds of programs.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Fig 4: OS Block Diagram

Following are some of important functions of an operating System.

Memory Management

Processor Management

Device Management

File Management

Security

Control over system performance

Job accounting

Error detecting aids

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Coordination between other software and users

Memory Management:

Memory management refers to management of Primary Memory or Main Memory. Main memory is a large array of
words or bytes where each word or byte has its own address.

Main memory provides a fast storage that can be access directly by the CPU. So for a program to be executed, it
must in the main memory. Operating System does the following activities for memory management.

Keeps tracks of primary memory i.e. what part of it are in use by whom, what part are not in use.

In multiprogramming, OS decides which process will get memory when and how much.

Allocates the memory when the process requests it to do so.

De-allocates the memory when the process no longer needs it or has been terminated.

Swapping, or paging, between main memory and disk, when disk is too small to hold all current processes.

Binding of Instruction and Data to memory:

Address binding of instructions and data to memory addresses can happen at three different stages.

Compile time: If memory location known a priori, absolute (complete) code can be generated; must
recompile code if starting location changes.

Load time: Must generate re-locatable code if memory location is not known at compile time.

Execution time: Binding delayed until run time if the process can be moved during its execution from one
memory segment to another. Need hardware support for address maps (e.g., base and limit registers).

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Fig 5: Multistep Processing of a User Program

Logical and Physical Address Space:

The concept of a logical address space that is bound to a separate physical address space is central to
proper memory management.

Logical address generated by the CPU; also referred to as virtual address.

Physical address address seen by the memory unit.

Logical and physical addresses are the same in compile-time and load-time address-binding schemes;
logical (virtual) and physical addresses differ in execution-time address-binding scheme.

Memory-Management Unit (MMU):

It is a Hardware device that maps virtual to physical address.

In MMU scheme, the value in the relocation register is added to every address generated by a user process
at the time it is sent to memory.

The user program deals with logical addresses; it never sees the real physical addresses.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Fig 6: MMU Block Diagram

Dynamic Loading:

Dynamic loading is a mechanism by which a computer program can, at run time, load a library (or other binary) into
memory, retrieve the addresses of functions and variables contained in the library, execute those functions or access
those variables, and unload the library from memory.

Features:

Routine is not loaded until it is called

Better memory-space utilization; unused routine is never loaded.

Useful when large amounts of code are needed to handle infrequently occurring cases.

No special support from the operating system is required implemented through program design.

Dynamic Linking:

Linking is often referred to as a process that is performed when the executable is compiled, while a dynamic linker is
a special part of an operating system that loads external shared libraries into a running process and then binds those
shared libraries dynamically to the running process. This approach is also called dynamic linking or late linking.

Features:

Usually used with system libraries, such as a language subroutine libraries.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Linking postponed until execution time.

Small piece of code, stub, used to locate the appropriate memory-resident library routine.

Stub replaces itself with the address of the routine, and executes the routine.

Operating system needed to check if routine is in processes memory address.

Dynamic linking is particularly useful for libraries.

Dynamic Storage-Allocation Problem:

How to satisfy a request of size n from a list of free holes.

First-fit: Allocate the first hole that is big enough.

Best-fit: Allocate the smallest hole that is big enough; must search entire list, unless ordered by size.
Produces the smallest leftover hole.

Worst-fit: Allocate the largest hole; must also search entire list. Produces the largest leftover hole.

Note: First-fit and best-fit better than worst-fit in terms of speed and storage utilization.

Fig 7: Example

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Fragmentation:

Fragmentation is a phenomenon in which storage space is used inefficiently, reducing capacity or performance and
often both. In many cases, fragmentation leads to storage space being "wasted", and in that case the term also
refers to the wasted space itself.

There are three different but related forms of fragmentation: external fragmentation, internal fragmentation, and data
fragmentation,

External Fragmentation total memory space exists to satisfy a request, but it is not contiguous.

Internal Fragmentation allocated memory may be slightly larger than requested memory; this size
difference is memory internal to a partition, but not being used.

Data Fragmentation - occurs when a collection of data in memory is broken up into many pieces that are
not close together.

Methods to reduce external fragmentation:

Compaction

Shuffle memory contents to place all free memory together in one large block

Compaction is possible only if relocation is dynamic, and is done at execution time

Another strategy: paging

Example of Relocation for Compaction:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Fig 8: Example

Paging:

paging is one of the memory management schemes by which a computer stores and retrieves data from the
secondary storage for use in main memory. In the paging memory-management scheme, the operating system
retrieves data from secondary storage in same-size blocks called pages. The main advantage of paging
over memory segmentation is that it allows the physical address space of a process to be non contiguous.

Fragmentation is a significant problem with all these memory management schemes

Lets organize physical address spaced (main memory) into equal (small) sized chunks called frames.

And divide logical (virtual) address space into chunks of the same size called pages

The pages of a program can thus be mapped to the available frames in main memory, not necessarily
contiguous

Result: a process can be scattered all over the physical memory.

Logical Address in Paging:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Within each program, each logical address consists of a page number and an offset within the page

A Memory Management Unit (MMU) is put between the CPU address bus and physical memory bus

A MMU register holds the starting physical address of the page table of the process currently running

Presented with a logical address (page number, offset) the MMU accesses the page table to obtain the
physical address (frame number, offset)

Paging Hardware:

Fig 9: Paging Hardware

Segmentation:

Segmentation is the division of a computer's primary memory into segments or sections. A program is a collection of
segments. A segment is a logical unit such as:

main program,

procedure,

function,

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

method,

object,

local variables, global variables,

common block,

stack,

symbol table, arrays

Segmentation Hardware:

Fig 10: Segmentation Hardware

Process Management:

Process: A process is a program in execution. The execution of a process must progress in a sequential fashion.
Definition of process is following.

A process is defined as an entity which represents the basic unit of work to be implemented in the system.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Components of process are following:

S.N. Component & Description

1 Object Program
Code to be executed.

2 Data
Data to be used for executing the program.

3 Resources
While executing the program, it may require some resources.

4 Status
Verifies the status of the process execution. A process can run to
completion only when all requested resources have been allocated to
the process. Two or more processes could be executing the same
program, each using their own data and resources.

Process States:

As a process executes, it changes state. The state of a process is defined as the current activity of the process.

Process can have one of the following five states at a time.

S.N. State & Description

1 New
The process is being created.

2 Ready
The process is waiting to be assigned to a processor. Ready
processes are waiting to have the processor allocated to them by the
operating system so that they can run.

3 Running
Process instructions are being executed (i.e. The process that is
currently being executed).

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

4 Waiting
The process is waiting for some event to occur (such as the
completion of an I/O operation).

5 Terminated
The process has finished execution.

State Diagram:

Fig 14: Process State Diagram

Process scheduling:

The process scheduling is the activity of the process manager that handles the removal of the running process from
the CPU and the selection of another process on the basis of a particular strategy.

Process scheduling is an essential part of a Multiprogramming operating system. Such operating systems allow
more than one process to be loaded into the executable memory at a time and loaded process shares the CPU
using time multiplexing.

Scheduling Queues

Scheduling queues refers to queues of processes or devices. When the process enters into the system, then this
process is put into a job queue. This queue consists of all processes in the system. The operating system also
maintains other queues such as device queue. Device queue is a queue for which multiple processes are waiting for
a particular I/O device. Each device has its own device queue.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

This figure shows the queuing diagram of process scheduling.

Queue is represented by rectangular box.

The circles represent the resources that serve the queues.

The arrows indicate the process flow in the system.

Fig 15: Flow Diagram

Queues are of two types

Ready queue

Device queue

A newly arrived process is put in the ready queue. Processes waits in ready queue for allocating the CPU. Once the
CPU is assigned to a process, then that process will execute. While executing the process, any one of the following
events can occur.

The process could issue an I/O request and then it would be placed in an I/O queue.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

The process could create new sub process and will wait for its termination.

The process could be removed forcibly from the CPU, as a result of interrupt and put back in the ready
queue.

Two State Process Model

Two state process models refer to running and non-running states which are described below.

S.N. State & Description

1 Running
When new process is created by Operating System that process
enters into the system as in the running state.

2 Not Running
Processes that are not running are kept in queue, waiting for their
turn to execute. Each entry in the queue is a pointer to a particular
process. Queue is implemented by using linked list. Use of
dispatcher is as follows. When a process is interrupted, that process
is transferred in the waiting queue. If the process has completed or
aborted, the process is discarded. In either case, the dispatcher then
selects a process from the queue to execute.

Schedulers:

Schedulers are special system softwares which handles process scheduling in various ways.Their main task is to
select the jobs to be submitted into the system and to decide which process to run. Schedulers are of three types

Long Term Scheduler

Short Term Scheduler

Medium Term Scheduler

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Long Term Scheduler:

It is also called job scheduler. Long term scheduler determines which programs are admitted to the system for
processing. Job scheduler selects processes from the queue and loads them into memory for execution. Process
loads into the memory for CPU scheduling. The primary objective of the job scheduler is to provide a balanced mix
of jobs, such as I/O bound and processor bound. It also controls the degree of multiprogramming. If the degree of
multiprogramming is stable, then the average rate of process creation must be equal to the average departure rate
of processes leaving the system.

On some systems, the long term scheduler may not be available or minimal. Time-sharing operating systems have
no long term scheduler. When process changes the state from new to ready, then there is use of long term
scheduler.

Short Term Scheduler:

It is also called CPU scheduler. Main objective is increasing system performance in accordance with the chosen set
of criteria. It is the change of ready state to running state of the process. CPU scheduler selects process among the
processes that are ready to execute and allocates CPU to one of them.

Short term scheduler also known as dispatcher, execute most frequently and makes the fine grained decision of
which process to execute next. Short term scheduler is faster than long term scheduler.

Medium Term Scheduler:

Medium term scheduling is part of the swapping. It removes the processes from the memory. It reduces the degree
of multiprogramming. The medium term scheduler is in-charge of handling the swapped out-processes.

Fig 16: Flow Diagram

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Running process may become suspended if it makes an I/O request. Suspended processes cannot make any
progress towards completion. In this condition, to remove the process from memory and make space for other
process, the suspended process is moved to the secondary storage. This process is called swapping, and the
process is said to be swapped out or rolled out. Swapping may be necessary to improve the process mix.

Comparison between Scheduler:

S.N. Long Term Short Term Medium Term


Scheduler Scheduler Scheduler

1 It is a job scheduler It is a CPU It is a process


scheduler swapping scheduler.

2 Speed is lesser than Speed is fastest Speed is in between


short term scheduler among other two both short and long
term scheduler.

3 It controls the degree It provides lesser It reduces the degree


of multiprogramming control over degree of multiprogramming.
of
multiprogramming

4 It is almost absent or It is also minimal in It is a part of Time


minimal in time time sharing system sharing systems.
sharing system

5 It selects processes It selects those It can re-introduce the


from pool and loads processes which process into memory
them into memory for are ready to and execution can be
execution execute continued.

Scheduling Algorithms:

Major scheduling algorithms here which are following

First Come First Serve (FCFS) Scheduling

Shortest-Job-First (SJF) Scheduling

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Priority Scheduling

Round Robin(RR) Scheduling

Multilevel Queue Scheduling

First Come First Serve (FCFS):

Jobs are executed on first come, first serve basis.

Easy to understand and implement.

Poor in performance as average wait time is high.

Wait time of each process is following

Proces Wait Time : Service Time - Arrival Time


s

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

P0 0-0=0

P1 5-1=4

P2 8-2=6

P3 16 - 3 = 13

Average Wait Time: (0+4+6+13) / 4 = 5.55

Shortest Job First (SJF):

Best approach to minimize waiting time.

Impossible to implement

Processer should know in advance how much time process will take.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Wait time of each process is following

Proces Wait Time : Service Time - Arrival Time


s

P0 3-0=3

P1 0-0=0

P2 16 - 2 = 14

P3 8-3=5

Average Wait Time: (3+0+14+5) / 4 = 5.50

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Priority Based Scheduling:

Each process is assigned a priority. Process with highest priority is to be executed first and so on.

Processes with same priority are executed on first come first serve basis.

Priority can be decided based on memory requirements, time requirements or any other resource
requirement.

Wait time of each process is following

Proces Wait Time : Service Time - Arrival Time


s

P0 9-0=9

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

P1 6-1=5

P2 14 - 2 = 12

P3 0-0=0

Average Wait Time: (9+5+12+0) / 4 = 6.5

Round Robin Scheduling:

Each process is provided a fix time to execute called quantum.

Once a process is executed for given time period. Process is preempted and other process executes for
given time period.

Context switching is used to save states of preempted processes.

Wait time of each process is following

Proces Wait Time : Service Time - Arrival Time


s

P0 (0-0) + (12-3) = 9

P1 (3-1) = 2

P2 (6-2) + (14-9) + (20-17) = 12

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

P3 (9-3) + (17-12) = 11

Average Wait Time: (9+2+12+11) / 4 = 8.5

Multi Queue Scheduling:

Multiple queues are maintained for processes.

Each queue can have its own scheduling algorithms.

Priorities are assigned to each queue.

Fig 17: Multi Queue Block Diagram

File Management in OS:

File: A file is a collection of related information defined by its creator. Files represent programs (both source and
object forms) and data.

Naming Convention:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

The absolute file name consists of:

drive name

directory name(s)

file name

Extension

For example: d:/network/LAN.doc

File Management:

The operating system is responsible for the following activities in connections with file management:

File creation and deletion.

Directory creation and deletion.

Support for manipulating files and directories.

Mapping files onto secondary storage.

File backup on stable (nonvolatile) storage media.

Identify and locate a selected file

Use a directory to describe the location of all files plus their attributes

On a shared system describe user access control

Blocking for access to files

Allocate files to free blocks

Manage free storage for available blocks.

Purpose of File Management:

The file manager handles all files on secondary storage media. To perform these tasks, file management must:

be able to identify the numerous files by giving unique names to them

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

maintain a list telling where exactly each file is stored, how many sectors on the medium it occupies, and in
which order those sectors make up the file

provide simple and fast algorithms to read and write files

give and deny access rights on files to users and programs

allocate and deallocate files to processes

provide users and programs with simple commands for file handling

File Operations:

Create

Delete

Open

Close

Read

Write

Typical Operations:

Retrieve All: Retrieve all the records of a file. This operation will be required for an application that must
process all the information in the file at one time.

Retrieve One: This operation requires the retrieval of just a single record. Interactive, transaction-oriented
applications need this operation

Retrieve Next: This operation requires the retrieval of the record that is next in some logical sequence to
the most recently received record. for example : filling in forms

Retrieve Previous : Similar to retrieve next, but in this case the record that is previous to the currently
accessed record is retrieved

Insert_One: Insert a new record into the file. It may be necessary that the new record fit into a particular
position to preserve a sequencing of the file.

Delete_One: delete an existing record. Certain linkages or other data structures may need to be updated to
preserve the sequencing of the file.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Update_One: Retrieve a record, update one or more of its fields, and rewrite updated record back into the
file.

Retrieve_Few: Retrieve a number of records. For example, an application may wish to retrieve all records
that satisfy a certain set of criteria.

Access Rights:

None

User may not know of the existence of the file

User is not allowed to read the user directory that includes the file

Knowledge

User can only determine that the file exists and who its owner is

Execution

The user can load and execute a program but cannot copy it

Reading

The user can read the file for any purpose, including copying and execution

Appending

The user can add data to the file but cannot modify or delete any of the files contents

Updating

The user can modify, deleted, and add to the files data. This includes creating the file, rewriting it,
and removing all or part of the data

Changing protection

User can change access rights granted to other users

Deletion

User can delete the file

Allocation Methods:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

contiguous file allocation

chained allocation

indexed allocation

Contiguous File Allocation:

Each file occupies a contiguous address space on disk.

Assigned disk address is in linear order.

Easy to implement.

External fragmentation is a major issue with this type of allocation technique.

Chained Allocation:

Each file carries a list of links to disk blocks.

Directory contains link / pointer to first block of a file.

No external fragmentation

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Effectively used in sequential access file.

Inefficient in case of direct access file.

Indexed Allocation:

Provides solutions to problems of contiguous and linked allocation.

A index block is created having all pointers to files.

Each file has its own index block which stores the addresses of disk space occupied by the file.

Directory contains the addresses of index blocks of files.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Unit 1- Chapter 2- Programming Basics

OOPS concepts:
What is OOP Object Oriented Programming)?
OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a
different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in
OOP is grouped as self sustainable "objects". Hence, you gain reusability by means of four main object-oriented
programming concepts.
In order to clearly understand the object orientation model, lets take your hand as an example. The hand is a
class. Your body has two objects of the type "hand", named "left hand" and "right hand". Their main functions are
controlled or managed by a set of electrical signals sent through your shoulders (through an interface). So the
shoulder is an interface that your body uses to interact with your hands. The hand is a well-architected class. The
hand is being reused to create the left hand and the right hand by slightly changing the properties of it.
What is an Object?
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object
performs defines the object's behavior. For example, the Hand (object) can grip something, or a Student (object) can
give their name or address.
In pure OOP terms an object is an instance of a class.
OOPs (Object Oriented Programming System):
Java oops concepts Object mean a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software development and
maintenance by providing some concepts:
1. Object
2. Class
3. Inheritance
4 .Polymorphism
5. Abstraction
6. Encapsulation

1. Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc.
It can be physical and logical.
2. Class

Collection of objects is called class. It is a logical entity.

Example:-
public class Sudent{
String Name;
int age;
String Branch;
void getinput()
{
}
void display()

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

{
}
public static void main(String args[])
{
}
}

Inheritance:
Inheritance can be defined as the process where one object acquires the properties of another. With the use of
inheritance the information is made manageable in a hierarchical order.
The ability of a new class to be created, from an existing class by extending it, is called inheritance.
Example :-
class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
Now, based on the above example, In Object Oriented terms, the following are true:
Animal is the super class of Mammal class.
Animal is the super class of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes

Polymorphism:
When one task is performed by different ways i.e. known as polymorphism. For example: to convense the customer
differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Polymorphism is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to
request that the same operations be performed by a wide range of different types of things.
At times, I used to think that understanding Object Oriented Programming concepts have made it difficult since they
have grouped under four main concepts, while each concept is closely related with one another. Hence one has to be
extremely careful to correctly understand each concept separately, while understanding the way each related with

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

other concepts.
In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator
overloading, and method overriding,
What is Method Overloading?
Method overloading is the ability to define several methods all with the same name.

public class MyLogger


{
public void LogError(Exception e)
{
// Implementation goes here
} public bool LogError(Exception e, string message)
{
// Implementation goes here
}
}
What is Operator Overloading?
The operator overloading (less commonly known as ad-hoc polymorphisms) is a specific case of polymorphisms in
which some or all of operators like +, - or == are treated as polymorphic functions and as such have different
behaviors depending on the types of its arguments.
public class Complex
{
private int real;
public int Real
{ get { return real; } }

private int imaginary;


public int Imaginary
{ get { return imaginary; } }

public Complex(int real, int imaginary)


{
this.real = real;
this.imaginary = imaginary;
}

public static Complex operator +(Complex c1, Complex c2)


{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
}

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

In above example I have overloaded the plus operator for adding two complex numbers. There the two properties
named Real and Imaginary has been declared exposing only the required get method, while the objects constructor
is demanding for mandatory real and imaginary values with the user defined constructor of the class.

Encapsulation:

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and

abstraction.

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public

methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields

within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by

other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others

who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

Example:

Let us look at an example that depicts encapsulation:

/* File name : EncapTest.java */

public class EncapTest{

private String name;

private String idNum;

private int age;

public int getAge(){

return age;

public String getName(){

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

return name;

public String getIdNum(){

return idNum;

public void setAge( int newAge){

age = newAge;

public void setName(String newName){

name = newName;

public void setIdNum( String newId){

idNum = newId;

The public methods are the access points to this class' fields from the outside java world. Normally, these methods

are referred as getters and setters. Therefore any class that wants to access the variables should access them

through these getters and setters.

The variables of the EncapTest class can be access as below:

/* File name : RunEncap.java */

public class RunEncap{

public static void main(String args[]){

EncapTest encap = new EncapTest();

encap.setName("James");

encap.setAge(20);

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName()+

" Age : "+ encap.getAge());

Benefits of Encapsulation:

The fields of a class can be made read-only or write-only.

A class can have total control over what is stored in its fields.

The users of a class do not know how the class stores its data. A class can change the data type of a field

and users of the class do not need to change any of their code.

INTRODUCTION TO JAVA:

Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java

runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a

complete understanding of Java.

This reference will take you through simple and practical approach while learning Java Programming language.

Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively. Java is

guaranteed to be Write Once, Run Anywhere.

Java is:

Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the

Object model.

Platform independent: Unlike many other programming languages including C and C++, when Java is

compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is

being run.

Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be

easy to master.

Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication

techniques are based on public-key encryption.

Architectural-neutral : Java compiler generates an architecture-neutral object file format which makes the

compiled code to be executable on many processors, with the presence of Java runtime system.

Portable: Being architectural-neutral and having no implementation dependent aspects of the specification

makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary which is a

POSIX subset.

Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time

error checking and runtime checking.

Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks

simultaneously. This design feature allows developers to construct smoothly running interactive

applications.

Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored

anywhere. The development process is more rapid and analytical since the linking is an incremental and

light weight process.

High Performance: With the use of Just-In-Time compilers, Java enables high performance.

Distributed: Java is designed for the distributed environment of the internet.

Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an

evolving environment. Java programs can carry extensive amount of run-time information that can be used

to verify and resolve accesses to objects on run-time.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

When we consider a Java program it can be defined as a collection of objects that communicate via invoking each

other's methods. Let us now briefly look into what do class, object, methods and instance variables mean.

Object - Objects have states and behaviours. Example: A dog has states - colour, name, breed as well as

behaviours -wagging, barking, and eating. An object is an instance of a class.

Class - A class can be defined as a template/ blue print that describe the behaviours/states that object of its

type support.

Methods - A method is basically a behaviour. A class can contain many methods. It is in methods where the

logics are written, data is manipulated and all the actions are executed.

Instance Variables - Each object has its unique set of instance variables. An object's state is created by the

values assigned to these instance variables.

Variables are nothing but reserved memory locations to store values. This means that when you create a variable

you reserve some space in memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the

reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or

characters in these variables.

There are two data types available in Java:

Primitive Data Types

Reference/Object Data Types

Primitive Data Types:

There are eight primitive data types supported by Java. Primitive data types are predefined by the language and

named by a keyword. Let us now look into detail about the eight primitive data types.

Byte:

Byte data type is an 8-bit signed two's complement integer.

Minimum value is -128 (-2^7)

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Maximum value is 127 (inclusive)(2^7 -1)

Default value is 0

Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times

smaller than an int.

Example: byte a = 100 , byte b = -50

Short:

Short data type is a 16-bit signed two's complement integer.

Minimum value is -32,768 (-2^15)

Maximum value is 32,767 (inclusive) (2^15 -1)

Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int

Default value is 0.

Example: short s = 10000, short r = -20000

int:

Int data type is a 32-bit signed two's complement integer.

Minimum value is - 2,147,483,648.(-2^31)

Maximum value is 2,147,483,647(inclusive).(2^31 -1)

Int is generally used as the default data type for integral values unless there is a concern about memory.

The default value is 0.

Example: int a = 100000, int b = -200000

Long:

Long data type is a 64-bit signed two's complement integer.

Minimum value is -9,223,372,036,854,775,808.(-2^63)

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)

This type is used when a wider range than int is needed.

Default value is 0L.

Example: long a = 100000L, int b = -200000L

Float:

Float data type is a single-precision 32-bit IEEE 754 floating point.

Float is mainly used to save memory in large arrays of floating point numbers.

Default value is 0.0f.

Float data type is never used for precise values such as currency.

Example: float f1 = 234.5f

Double:

Double data type is a double-precision 64-bit IEEE 754 floating point.

This data type is generally used as the default data type for decimal values, generally the default choice.

Double data type should never be used for precise values such as currency.

Default value is 0.0d.

Example: double d1 = 123.4

Boolean:

Boolean data type represents one bit of information.

There are only two possible values: true and false.

This data type is used for simple flags that track true/false conditions.

Default value is false.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Example: boolean one = true

char:

char data type is a single 16-bit Unicode character.

Minimum value is '\u0000' (or 0).

Maximum value is '\uffff' (or 65,535 inclusive).

Char data type is used to store any character.

Example: char letterA ='A'

Reference Data Types:

Reference variables are created using defined constructors of the classes. They are used to access

objects. These variables are declared to be of a specific type that cannot be changed. For example,

Employee, Puppy etc.

Class objects, and various type of array variables come under reference data type.

Default value of any reference variable is null.

A reference variable can be used to refer to any object of the declared type or any compatible type.

Example: Animal animal = new Animal("giraffe");

Java language supports few special escape sequences for String and char literals as well. They are:

Notation Character represented

\n Newline

\b Backspace

\s Space

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

\t tab

\" Double quote

\' Single quote

\\ backslash

JAVA STRINGS:

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming

language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings:

The most direct way to create a string is to write:

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case,

"Hello world!'.

As with any other object, you can create String objects by using the new keyword and a constructor. The String

class has eleven constructors that allow you to provide the initial value of the string using different sources, such as

an array of characters.

public class StringDemo{

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

public static void main(String args[]){

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};

String helloString = new String(helloArray);

System.out.println( helloString );

This would produce the following result:

hello.

Note: The String class is immutable; so that once it is created a String object cannot be changed. If there is a

necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String

Builder Classes.

String Length:

Methods used to obtain information about an object are known as access or methods. One access or method that

you can use with strings is the length() method, which returns the number of characters contained in the string

object.

After the following two lines of code have been executed, len equals 17:

public class StringDemo {

public static void main(String args[]) {

String palindrome = "Dot saw I was Tod";

int len = palindrome.length();

System.out.println( "String Length is : " + len );

This would produce the following result:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

String Length is : 17

Concatenating Strings:

The String class includes a method for concatenating two strings:

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method

with string literals, as in:

"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in:

"Hello," + " world" + "!"

This results in:

"Hello, world!"

Let us look at the following example:

public class StringDemo {

public static void main(String args[]) {

String string1 = "saw I was ";

System.out.println("Dot " + string1 + "Tod");

This would produce the following result:

Dot saw I was Tod

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Creating Format Strings:

You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent

class method, format(), that returns a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a

one-time print statement. For example, instead of:

System.out.printf("The value of the float variable is " +

"%f, while the value of the integer " +

"variable is %d, and the string " +

"is %s", floatVar, intVar, stringVar);

You can write:

String fs;

fs = String.format("The value of the float variable is " +

"%f, while the value of the integer " +

"variable is %d, and the string " +

"is %s", floatVar, intVar, stringVar);

System.out.println(fs);

String Methods:

Here is the list of methods supported by String class:

SN Methods with Description

1
char charAt(int index)

Returns the character at the specified index.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

2
int compareTo(Object o)

Compares this String to another Object.

3
int compareTo(String anotherString)

Compares two strings lexicographically.

4
int compareToIgnoreCase(String str)

Compares two strings lexicographically, ignoring case differences.

5
String concat(String str)

Concatenates the specified string to the end of this string.

6
boolean contentEquals(StringBuffer sb)

Returns true if and only if this String represents the same sequence of characters as the specified

StringBuffer.

7
static String copyValueOf(char[] data)

Returns a String that represents the character sequence in the array specified.

8
static String copyValueOf(char[] data, int offset, int count)

Returns a String that represents the character sequence in the array specified.

9
boolean endsWith(String suffix)

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Tests if this string ends with the specified suffix.

10
boolean equals(Object anObject)

Compares this string to the specified object.

11
boolean equalsIgnoreCase(String anotherString)

Compares this String to another String, ignoring case considerations.

12
byte getBytes()

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into

a new byte array.

13
byte[] getBytes(String charsetName

Encodes this String into a sequence of bytes using the named charset, storing the result into a new

byte array.

14
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Copies characters from this string into the destination character array.

15
int hashCode()

Returns a hash code for this string.

16
int indexOf(int ch)

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Returns the index within this string of the first occurrence of the specified character.

17
int indexOf(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the specified character, starting the search

at the specified index.

18
int indexOf(String str)

Returns the index within this string of the first occurrence of the specified substring.

19
int indexOf(String str, int fromIndex)

Returns the index within this string of the first occurrence of the specified substring, starting at the

specified index

20
String intern()

Returns a canonical representation for the string object.

21
int lastIndexOf(int ch)

Returns the index within this string of the last occurrence of the specified character.

22
int lastIndexOf(int ch, int fromIndex)

Returns the index within this string of the last occurrence of the specified character, searching

backward starting at the specified index.

23
int lastIndexOf(String str)

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Returns the index within this string of the rightmost occurrence of the specified substring.

24
int lastIndexOf(String str, int fromIndex)

Returns the index within this string of the last occurrence of the specified substring, searching

backward starting at the specified index.

25
int length()

Returns the length of this string.

26
boolean matches(String regex)

Tells whether or not this string matches the given regular expression.

27
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

Tests if two string regions are equal.

28
boolean regionMatches(int toffset, String other, int ooffset, int len)

Tests if two string regions are equal

29
String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

30
String replaceAll(String regex, String replacement

Replaces each substring of this string that matches the given regular expression with the given

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

replacement.

31
String replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular expression with the given

replacement.

32
String[] split(String regex)

Splits this string around matches of the given regular expression.

33
String[] split(String regex, int limit)

Splits this string around matches of the given regular expression.

34
boolean startsWith(String prefix)

Tests if this string starts with the specified prefix.

35
boolean startsWith(String prefix, int toffset)

Tests if this string starts with the specified prefix beginning a specified index.

36
CharSequence subSequence(int beginIndex, int endIndex)

Returns a new character sequence that is a subsequence of this sequence.

37
String substring(int beginIndex)

Returns a new string that is a substring of this string.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

38
String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

39
char[] toCharArray()

Converts this string to a new character array.

40
String toLowerCase()

Converts all of the characters in this String to lower case using the rules of the default locale.

41
String toLowerCase(Locale locale)

Converts all of the characters in this String to lower case using the rules of the given Locale.

42
String toString()

This object (which is already a string!) is itself returned.

43
String toUpperCase()

Converts all of the characters in this String to upper case using the rules of the default locale.

44
String toUpperCase(Locale locale)

Converts all of the characters in this String to upper case using the rules of the given Locale.

45
String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

46
static String valueOf(primitive data type x)

Returns the string representation of the passed data type argument.

JAVA ARRAYS:

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same

type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of

variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array

variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

Declaring Array Variables:

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of

array the variable can reference. Here is the syntax for declaring an array variable:

dataType[] arrayRefVar; // preferred way.


or
dataType arrayRefVar[]; // works but not preferred way.

Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[]comes from the C/C++

language and was adopted in Java to accommodate C/C++ programmers.

Example:

The following code snippets are examples of this syntax:

double[] myList; // preferred way.

or

double myList[]; // works but not preferred way.

Creating Arrays:

You can create an array by using the new operator with the following syntax:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

arrayRefVar = new dataType[arraySize];

The above statement does two things:

It creates an array using new dataType[arraySize];

It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be

combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0

to arrayRefVar.length-1.

Example:

Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns

its reference to myList:

double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Processing Arrays:

When processing array elements, we often use either for loop or foreach loop because all of the elements in an

array are of the same type and the size of the array is known.

Example:

Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray {

public static void main(String[] args) {

double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements

for (int i = 0; i < myList.length; i++) {

System.out.println(myList[i] + " ");

// Summing all elements

double total = 0;

for (int i = 0; i < myList.length; i++) {

total += myList[i];

System.out.println("Total is " + total);

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

// Finding the largest element

double max = myList[0];

for (int i = 1; i < myList.length; i++) {

if (myList[i] > max) max = myList[i];

System.out.println("Max is " + max);

This would produce the following result:

1.9

2.9

3.4

3.5

Total is 11.7

Max is 3.5

The foreach Loops:

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the

complete array sequentially without using an index variable.

Example:

The following code displays all the elements in the array myList:

public class TestArray {

public static void main(String[] args) {

double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements

for (double element: myList) {

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

System.out.println(element);

This would produce the following result:

1.9

2.9

3.4

3.5

Passing Arrays to Methods:

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the

following method displays the elements in an int array:

public static void printArray(int[] array) {

for (int i = 0; i < array.length; i++) {

System.out.print(array[i] + " ");

You can invoke it by passing an array. For example, the following statement invokes the printArray method to display

3, 1, 2, 6, 4, and 2:

printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method:

A method may also return an array. For example, the method shown below returns an array that is the reversal of

another array:

public static int[] reverse(int[] list) {

int[] result = new int[list.length];

for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

result[j] = list[i];

return result;

The Arrays Class:


The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and

filling array elements. These methods are overloaded for all primitive types.

SN Methods with Description

1 public static int binarySearch(Object[] a, Object key)

Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary

search algorithm. The array must be sorted prior to making this call. This returns index of the search

key, if it is contained in the list; otherwise, (-(insertion point + 1).

2 public static boolean equals(long[] a, long[] a2)

Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered

equal if both arrays contain the same number of elements, and all corresponding pairs of elements in

the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by

all other primitive data types (Byte, short, Int, etc.)

3 public static void fill(int[] a, int val)

Assigns the specified int value to each element of the specified array of ints. Same method could be

used by all other primitive data types (Byte, short, Int etc.)

4 public static void sort(Object[] a)

Sorts the specified array of objects into ascending order, according to the natural ordering of its

elements. Same method could be used by all other primitive data types ( Byte, short, Int, etc.)

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

JAVA LOOPS:

There may be a situation when we need to execute a block of code several number of times, and is often referred to
as a loop.

Java has very flexible three looping mechanisms. You can use one of the following three loops:

while Loop

do...while Loop

for Loop

The while Loop:

A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:

The syntax of a while loop is:

while(Boolean_expression)
{
//Statements
}

When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will
continue as long as the expression result is true.

Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is
false, the loop body will be skipped and the first statement after the while loop will be executed.

Example:
public class Test {

public static void main(String args[]) {


int x = 10;

while( x < 20 ) {

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The do...while Loop:

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:

The syntax of a do...while loop is:

do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once
before the Boolean is tested.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute
again. This process repeats until the Boolean expression is false.

Example:
public class Test {
public static void main(String args[]){
int x = 10;

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The for Loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific
number of times.

A for loop is useful when you know how many times a task is to be repeated.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Syntax:

The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}

Here is the flow of control in a for loop:

The initialization step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement past the for loop.

After the body of the for loop executes, the flow of control jumps back up to the update statement. This
statement allows you to update any loop control variables. This statement can be left blank, as long as a
semicolon appears after the Boolean expression.

The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the
for loop terminates.

Example:
public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x+1) {


System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

This would produce the following result:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The break Keyword:

The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch
statement.

The break keyword will stop the execution of the innermost loop and start executing the next line of code after the
block.

Syntax:

The syntax of a break is a single statement inside any loop:

break;

Example:
public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

}
}

This would produce the following result:

10
20

The continue Keyword:

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to
the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.

In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax:

The syntax of a continue is a single statement inside any loop:

continue;

Example:
public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

This would produce the following result:

10
20
40
50

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Unit 1- Chapter 3- Classes and Objects


Class - A class can be defined as a template/blue print that describes the behaviors/states that object of its type
support.

public class Dog{


String breed;
int age;
String color;

void barking(){
}

void hungry(){
}

void sleeping(){
}
}

A class can contain any of the following variable types.

Local variables: Variables defined inside methods, constructors or blocks are called local variables. The
variable will be declared and initialized within the method and the variable will be destroyed when the
method has completed.

Instance variables: Instance variables are variables within a class but outside any method. These variables
are instantiated when the class is loaded. Instance variables can be accessed from inside any method,
constructor or blocks of that particular class.

Class variables: Class variables are variables declared with in a class, outside any method, with the static
keyword.

Access Specifiers:
Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and methods in
Java.These Specifiers determine whether a field or method in a class, can be used or invoked by another method in
another class or sub-class. Access Specifiers can be used to restrict access. Access Specifiers are an integral part of
object-oriented programming

In java we have four Access Specifiers and they are listed below.

1.public
2.private
3.protected
4. default(no specifier)

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Public Access Modifier - public:


A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields,
methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

public static void main(String[] arguments) {

// ...

Private Access Modifier - private:


Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables that are declared private can be accessed outside the class if public getter methods are present in the
class.

public class Logger {


private String format;
public String getFormat()
{
return this.format;
}
public void setFormat(String format)
{
this.format = format;
}
}

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Protected Access Modifier - protected:


Variables, methods and constructors which are declared protected in a superclass can be accessed only by the
subclasses in other package or any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected,
however methods and fields in a interface cannot be declared protected.

class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}

class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}

Default Access Modifier - No keyword:


Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.

A variable or method declared without any access control modifier is available to any other class in the same
package. The fields in an interface are implicitly public static final and the methods in an interface are by default
public

String version = "1.5.1";

boolean processOrder() {
return true;
}

Constructors:
Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that
is why it is known as constructor

class Car
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Types of java constructors

There are two types of constructors:

1. Default constructor (no-arg constructor)

2. Parameterized constructor

Car c = new Car() //Default constructor invoked


Car c = new Car(name); //Parameterized constructor invoked

Method overloading:
If two or more method in a class has same name but different parameters, it is known as method overloading.

Method overloading is one of the ways through which java supports polymorphism. Method overloading can be done
by changing number of arguments or by changing the data type of arguments. If two or more method have same
name and same parameter list but differs in return type are not said to be overloaded method

class Calculate
{
void sum (int a, int b)
{
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
System.out.println("sum is"+(a+b));
}
Public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6, 3.8); //sum(float a, float b) is called.
}
}

Static Keyword:
The static keyword in java is used for memory management mainly. We can apply java static keyword with
variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

The static can be:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

1. variable (also known as class variable)

2. method (also known as class method)

3. block

4. nested class

Java static variable:


If you declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects (that is not unique for each
object) e.g. company name of employees,college name of students etc.

The static variable gets memory only once in class area at the time of class loading.

class VariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}

Output:

Obj1: count is=2


Obj2: count is=2

Java static method:


If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than object of a class.

A static method can be invoked without the need for creating an instance of a class.

static method can access static data member and can change the value of it.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

class Languages {
public static void main(String[] args) {
display();
}

static void display() {


System.out.println("Java is my favorite programming language.");
}
}

1. Describe the relationship between an object and its defining class. How do you declare a class? How do you
declare an object reference variable?
ANS: The object is a instance of the class.It has all the properties of the class.An object is used to invoke all the
methods present in the code.

Declaration of class :-

Class class_name
{
data_types names;
}

Example:- class student


{
string Name;
Int ID;
}

Declaration of object reference variable :-


Int main()
{
Class_name object;
}

Example:
Int main()
{
Student s1;
}

2. How do you create an object? How do you declare and create an object in one statement?

There are three steps in creating an object from a class


Declaration:A variable declaration with a variable name with object type.
Insatantiation:The new new key word is used to create the object
Intialization:The newkeyword is followed by a call to a constructor.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

class_name obj_name= new class_name();

3. When gasoline is $100 per barrel, then the consumers price at the pump is between $3.50 and $4.00 per gallon.
Create a class named GasPrices . Its main() method holds an integer variable named pricePerBarrel to which you will
assign a value entered by a user at the keyboard. Create a method to which you pass pricePerBarrel . The method
displays the range of possible prices per gallon. For example, if gas is $120 per barrel, then the price at the pump
should be between $4.20 and $4.80. Save the application as GasPrices.java.

package javaapplication13;

import java.util.Scanner;

public class GasPrice

static void price(double priceperbarrel)


{
double a,b;
a=priceperbarrel*3.5;

b=priceperbarrel*4;

System.out.println("Range of possible prices per gallon");


System.out.println(a+"\t"+b);

public static void main(String[] args)

{
double priceperbarrel;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the price of gas per barrel");
priceperbarrel=sc.nextDouble();
price(priceperbarrel);
}

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

4. Create a class named FormLetterWriter that includes two overloaded methods named displaySalutation() . The
first method takes one String parameter that represents a customers last name, and it displays the salutation Dear
Mr. or Ms. followed by the last name. The second method accepts two String parameters that represent a first and
last name, and it displays the greeting Dear followed by the first name, a space, and the last name. After each
salutation, display the rest of a short business letter: Thank you for your recent order. Write a main() method that
tests each overloaded method. Save the file as FormLetterWriter.java

package javaapplication13;

public class FormLetterWriter


{

void displaySalutation(String a)
{
System.out.println("Dear Mr.or Ms "+a);
disp();

void displaySalutation(String a,String b)


{

System.out.println("Dear "+a+" "+b);


disp();
}

void disp()
{

System.out.println("\n");

System.out.println("Thank you for your recent order");


}

}
class apply
{

public static void main(String[] args)


{

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

FormLetterWriter a = new FormLetterWriter();


a.displaySalutation("Miller");
a.displaySalutation("John","Miller");

}
}

5. Create class SavingsAccount. Use a static variable annualInterestRate to store the annual interest rate for all
account holders. Each object of the class contains a private instance variable savingsBalanceindicating the amount
the saver currently has on deposit. Provide method calculateMonthlyInterest to calculate the monthly interest by
multiplying the savingsBalance by annualInterestRate divided by 12 this interest should be added to savingsBalance.
Provide a static method modifyInterestRate that sets theannualInterestRate to a new value. Write a program to test
class SavingsAccount. Instantiate two savingsAccount objects, saver1 and saver2, with balances of $2000.00 and
$3000.00, respectively. Set annualInterestRate to 4%, then calculate the monthly interest and print the new balances
for both savers. Then set the annualInterestRate to 5%, calculate the next month's interest and print the new
balances for both savers.

package javaapplication13;

import java.util.Scanner;

public class SavingsAccount


{
static double annualInterestRate;
private double savingsBalance;
double a;
Scanner sc=new Scanner(System.in);

void calculateMonthlyInterest()
{

a= savingsBalance*annualInterestRate/12;
savingsBalance=savingsBalance+a;

void disp()
{

System.out.println(savingsBalance);

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

static void modifyInterestRate()


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the new InterestRate");
annualInterestRate=sc.nextDouble();

void initializebalance()
{
System.out.println("Enter the balance amount");
savingsBalance=sc.nextDouble();

}
}

class apply1
{

public static void main(String[] args)


{
SavingsAccount saver1= new SavingsAccount();
SavingsAccount saver2= new SavingsAccount();
saver1.initializebalance();
saver2.initializebalance();

6. What are the differences between constructors and methods


Both method and Constructor can be overloaded or overridden in Java. Though calling mechanism of Constructor is
different than method. you can call an overloaded constructor as this(argument) or super(argument) based upon
whether its declared on same class or super class but for calling overloaded method or overridden method, you
simply use method name.
* You can make your constructor public, protected, private similar to your method in Java. By the way If you are not
familiar with access modifier in Java than see Difference between public, protected and private keyword in Java.

* First difference between method vs constructor in Java is that name of constructor must be same with name of
the Class but there is no such requirement for method in Java. methods can have any arbitrary name in Java.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

* Second difference between method and constructor in Java is that constructor doesn't have any return type but
method has return type and return something unless its void.

* Third difference between constructor and method in Java is that Constructors are chained and they are called in a
particular order, there is no such facility for methods.

7. How do we invoke a constructor? What is meant by constructor overloading? What is meant by method
overloading?
The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor
for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object
is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers
and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the
base class completes first and constructor for the most derived class completes last.
class A {

A() {
System.out.print("A");
}
}

class B extends A {
B() {
System.out.print("B");
}
}

class C extends B {
C() {
System.out.print("C");
}
}

public class My extends C {


My(){
super();
}
public static void main(String[] args) {
My m = new My();
}
}

like methods, constructors can also be overloaded. We will see constructor overloading with the help of an
example using this() and parameterized constructor. Constructor overloading is way of having more than one
constructor which does different-2 tasks.

Example:
package beginnersbook.com;

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

public class StudentData


{
private int stuID;
private String stuName;
private int stuAge;
StudentData()
{
//Default constructor
stuID = 100;
stuName = "New Student";
stuAge = 18;
}
StudentData(int num1, String str, int num2)
{
//Parameterized constructor
stuID = num1;
stuName = str;
stuAge = num2;
}
//Getter and setter methods
public int getStuID() {
return stuID;
}
public void setStuID(int stuID) {
this.stuID = stuID;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
}

class TestOverloading
{
public static void main(String args[])
{
//This object creation would call the default constructor
StudentData myobj = new StudentData();

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

System.out.println("Student Name is: "+myobj.getStuName());


System.out.println("Student Age is: "+myobj.getStuAge());
System.out.println("Student ID is: "+myobj.getStuID());

/*This object creation would call the parameterized


* constructor StudentData(int, String, int)*/
StudentData myobj2 = new StudentData(555, "Chaitanya", 25);
System.out.println("Student Name is: "+myobj2.getStuName());
System.out.println("Student Age is: "+myobj2.getStuAge());
System.out.println("Student ID is: "+myobj2.getStuID());
}
}

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Unit 2- Chapter 4- Data Structures

Data Structures

Introduction:

In computer science, a data structure is a particular way of organizing data in a computer so that it can be used
efficiently.

Data Structures is about rendering data elements in terms of some relationship, for better organization and storage.

For example, we have data player's name "Virat" and age 26. Here "Virat" is of String data type and 26 is of integer
data type. We can organize this data as a record like Player record. Now we can collect and store player's records in
a file or database as a data structure. For example: "Dhoni" 30, "Gambhir" 31, "Sehwag" 33
In simple language, Data Structures are structures programmed to store ordered data, so that various operations can
be performed on it easily.

Basic types of Data Structures:

As we discussed above, anything that can store data can be called as a data strucure, hence Integer, Float, Boolean,
Char etc, all are data structures. They are known as Primitive Data Structures.
Then we also have some complex Data Structures, which are used to store large and connected data. Some
example of Abstract Data Structure are :
Linked List
Tree
Graph
Stack, Queue etc.
All these data structures allow us to perform different operations on data. We select these data structures based on
which type of operation is required. We will look into these data structures in more details in our later lessons.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Linear Data Structures:

Linear Data Structure are :

Stack, Queue etc.


Linked List

Stack:

Stack is a linear data structure which follows a particular order in which the operations are performed. The
order may be LIFO(Last In First Out) or FILO(First In Last Out).

Mainly the following three basic operations are performed in the stack:

Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the
stack is empty, then it is said to be an Underflow condition.
Peek: Get the topmost item.

How to understand a stack practically?


There are many real life examples of stack. Consider the simple example of plates stacked over one another in
canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the
bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO/FILO
order.

There are two ways to implement a stack:


Using array

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Using linked list

Position of Top Status of Stack

-1 Stack is Empty

0 Only one element in Stack

N-1 Stack is Full

N Overflow state of Stack

Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default
constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its
own.

Apart from the methods inherited from its parent class Vector, Stack defines following methods:

SN Methods with Description

1 boolean empty()

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Tests if this stack is empty. Returns true if the stack is empty, and returns false if the
stack contains elements.

2 Object peek( )
Returns the element on the top of the stack, but does not remove it.

3 Object pop( )
Returns the element on the top of the stack, removing it in the process.

4 Object push(Object element)


Pushes element onto the stack. element is also returned.

5 int search(Object element)


Searches for element in the stack. If found, its offset from the top of the stack is
returned. Otherwise, .1 is returned.

Example for stack using java collections framework:

import java.util.*;

public class StackDemo {


static void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}

static void showpop(Stack st) {


System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}

public static void main(String args[]) {


Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}

The above code would produce the following result:

stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack

Note: Implementation is not there for syllabus. It is just for your reference how it work in coding.

Queue:

Queue is also an abstract data type or a linear data structure, in which the first element is inserted from one end
called REAR(also called tail), and the deletion of exisiting element takes place from the other end called
as FRONT(also called head). This makes queue as FIFO data structure, which means that element inserted first will
also be removed first.

The process to add an element into queue is called Enqueue and the process of removal of an element from queue
is called Dequeue.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Basic features of Queue:

1. Like Stack, Queue is also an ordered list of elements of similar data types.

2. Queue is a FIFO( First in First Out ) structure.

3. Once a new element is inserted into the Queue, all the elements inserted before the new element in the

queue must be removed, to remove the new element.

4. peek( ) function is oftenly used to return the value of first element without dequeuing it.

Applications of Queue:

Queue, as the name suggests is used whenever we need to have any group of objects in an order in which the first
one coming in, also gets out first while the others wait for there turn, like in the following scenarios :

1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.

2. In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until a

service representative is free.

3. Handling of interrupts in real-time systems. The interrupts are handled in the same order as they arrive, First

come first served.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Implementation of Queue:

Queue can be implemented using an Array, Stack or Linked List. The easiest way of implementing a queue is by
using an Array. Initially the head(FRONT) and the tail(REAR) of the queue points at the first index of the array
(starting the index of array from 0). As we add elements to the queue, the tail keeps on moving ahead, always
pointing to the position where the next element will be inserted, while the head remains at the first index.

When we remove element from Queue, we can follow two possible approaches (mentioned [A] and [B] in above
diagram). In [A] approach, we remove the element at head position, and then one by one move all the other elements
on position forward. In approach [B] we remove the element from head position and then move head to the next
position.

In approach [A] there is an overhead of shifting the elements one position forward every time we remove the first
element. In approach [B] there is no such overhead, but whener we move head one position ahead, after removal of
first element, the size on Queue is reduced by one space each time.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Example for queue using java collections framework:

Queue can be implemented by using two types of java collections framework

Linked list
Priority queue

1) LinkedList Implementation-

import java.util.*;
public class QueueDemo {
static String newLine = System.getProperty("line.separator");
public static void main(String[] args) {

System.out.println(newLine + "Queue in Java" + newLine);


System.out.println("-----------------------" + newLine);
System.out.println("Adding items to the Queue" + newLine);
//Creating queue would require you to create instannce of LinkedList and assign
//it to Queue
//Object. You cannot create an instance of Queue as it is abstract
Queue queue = new LinkedList();

//you add elements to queue using add method


queue.add("Java");
queue.add(".NET");

queue.add("Javascript");
queue.add("HTML5");
queue.add("Hadoop");

System.out.println(newLine + "Items in the queue..." + queue + newLine);

//You remove element from the queue using .remove method


//This would remove the first element added to the queue, here Java
System.out.println("remove element: " + queue.remove() + newLine);

//.element() returns the current element in the queue, here when "java" is removed

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

//the next most top element is .NET, so .NET would be printed.


System.out.println("retrieve element: " + queue.element() + newLine);

//.poll() method retrieves and removes the head of this queue


//or return null if this queue is empty. Here .NET would be printed and then would
//be removed
//from the queue
System.out.println("remove and retrieve element, null if empty: " + queue.poll() +
newLine);

//.peek() just returns the current element in the queue, null if empty
//Here it will print Javascript as .NET is removed above
System.out.println("retrieve element, null is empty " + queue.peek() + newLine);
}
}
Output-
Queue in Java
---------------------------
Adding items to the Queue

Items in the queue[Java, .NET, Javascript, HTML5, Hadoop]


remove element: Java
retrieve element: .NET
remove and retrieve element, null if empty: .NET
retrieve element, null is empty Javascript

2) PriorityQueue Implementation

Methods of Queue Interface :


public boolean add(object);
public boolean offer(object);
public remove();
public poll();
public element();
public peek();

import java.util.*;
class TestCollection12{
public static void main(String args[]){

PriorityQueue<String> queue=new PriorityQueue<String>();

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");

System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());

System.out.println("iterating the queue elements:");


Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

queue.remove();
queue.poll();

System.out.println("after removing two elements:");


Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}

}
}

Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
Linked list:

A linked list is a data structure consisting of a group of nodes which together represent a sequence.
Under the simplest form, each node is composed of data and a reference (in other words, a link) to the next node in
the sequence; more complex variants add additional links. This structure allows for efficient insertion or removal of
elements from any position in the sequence.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Each element (we will call it a node) of a list is comprising of two items - the data and a reference to the next node.
The last node has a reference to null. The entry point into a linked list is called the head of the list. It should be noted
that head is not a separate node, but the reference to the first node. If the list is empty then the head is a null
reference.

A linked list is a dynamic data structure. The number of nodes in a list is not fixed and can grow and shrink on
demand. Any application which has to deal with an unknown number of objects will need to use a linked list.

Types of Linked Lists

A singly linked list is described above


A doubly linked list is a list that has two references, one to the next node and another to previous node.

Another important type of a linked list is called a circular linked list where last node of the list points back to the first
node (or the head) of the list.

Linked List Operations

addFirst

The method creates a node and prepends it at the beginning of the list.

Traversing
Start with the head and access each node until you reach null. Do not change the head reference.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

addLast
The method appends the node to the end of the list. This requires traversing, but make sure you stop at the last node

Inserting "after"
Find a node containing "key" and insert a new node after it. In the picture below, we insert a new node after "e":

Inserting "before"
Find a node containing "key" and insert a new node before that node. In the picture below, we insert a new node
before "a":

Deletion
Find a node containing "key" and delete it. In the picture below we delete a node containing "A"

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Example for linked list using java collections framework:

import java.util.*;
public class TestCollection7{
public static void main(String args[]){

LinkedList<String> al=new LinkedList<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Output:Ravi
Vijay
Ravi
Ajay

Non Linear Data Structures:


Trees
Graphs
Hash Tables

Tree:

A tree is a collection of nodes connected by directed (or undirected) edges.

A tree is a nonlinear data structure, compared to arrays, linked lists, stacks and queues which are linear data
structures.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

A tree can be empty with no nodes or a tree is a structure consisting of one node called the root and zero or one or
more sub trees.

A tree has following general properties:

One node is distinguished as a root;


Every node (exclude a root) is connected by a directed edge from exactly one other node; A direction
is: parent -> children

A is a parent of B, C, D,
B is called a child of A.
on the other hand, B is a parent of E, F, K

In the above picture, the root has 3 subtrees.

Each node can have arbitrary number of children. Nodes with no children are called leaves, or external nodes. In the
above picture, C, E, F, L, G are leaves. Nodes, which are not leaves, are called internal nodes. Internal nodes have at
least one child.

Nodes with the same parent are called siblings. In the picture, B, C, D are called siblings. The depth of a node is the
number of edges from the root to the node. The depth of K is 2. The height of a node is the number of edges from
the node to the deepest leaf. The height of B is 2. The height of a tree is a height of a root.

Binary Tree:
A binary tree in which each node has exactly zero or two children is called a full binary tree. In a full tree, there are
no nodes with exactly one child.
A complete binary tree is a tree, which is completely filled, with the possible exception of the bottom level, which is
filled from left to right. A complete binary tree of the height h has between 2h and 2(h+1)-1 nodes.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Full binary tree complete binary tree

Binary Search Tree(BST):

A binary search tree is a rooted binary tree, whose internal nodes each store a key (and optionally, an associated
value) and each have two distinguished sub-trees, commonly denoted left and right. The tree additionally satisfies the
binary search tree property, which states that the key in each node must be greater than all keys stored in the left
sub-tree and smaller than all keys in right sub-tree.

Operations on a BST:

Searching;
Searching a binary search tree for a specific key can be a recursive or an iterative process.

We begin by examining the root node. If the tree is null, the key we are searching for does not exist in the tree.
Otherwise, if the key equals that of the root, the search is successful and we return the node. If the key is less than
that of the root, we search the left sub tree. Similarly, if the key is greater than that of the root, we search the right sub
tree. This process is repeated until the key is found or the remaining sub tree is null. If the searched key is not found
before a null sub tree is reached, then the item must not be present in the tree.

Insertion:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Insertion begins as a search would begin; if the key is not equal to that of the root, we search the left or right sub
trees as before. Eventually, we will reach an external node and add the new key-value pair (here encoded as a record
'newNode') as its right or left child, depending on the node's key. In other words, we examine the root and recursively
insert the new node to the left sub tree if its key is less than that of the root, or the right sub tree if its key is greater
than or equal to the root.

Deletion:

There are three possible cases to consider:

Deleting a node with no children: simply remove the node from the tree.

Deleting a node with one child: remove the node and replace it with its child.

Deleting a node with two children: call the node to be deleted N. Do not delete N. Instead, choose either
its in-order successor node or its in-order predecessor node, R. Copy the value of R to N, then recursively call
delete on R until reaching one of the first two cases. If you choose in-order successor of a node, as right sub
tree is not NIL (Our present case is node has 2 children), then its in-order successor is node with least value in
its right sub tree, which will have at a maximum of 1 sub tree, so deleting it would fall in one of first 2 cases.

Traversal:

Once the binary search tree has been created, its elements can be retrieved in-order by recursively traversing the left
sub tree of the root node, accessing the node itself, then recursively traversing the right sub tree of the node,
continuing this pattern with each node in the tree as it's recursively accessed.

There are three types of tree traversals:


Pre-order

1. Display the data part of root element (or current element)

2. Traverse the left sub tree by recursively calling the pre-order function.

3. Traverse the right sub tree by recursively calling the pre-order function.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Pre-order: F, B, A, D, C, E, G, I, H

In-order (symmetric)

1. Traverse the left sub tree by recursively calling the in-order function

2. Display the data part of root element (or current element)

3. Traverse the right sub tree by recursively calling the in-order function

In-order: A, B, C, D, E, F, G, H, I

Post-order

1. Traverse the left sub tree by recursively calling the post-order function.

2. Traverse the right sub tree by recursively calling the post-order function.

3. Display the data part of root element (or current element).

Post-order: A, C, E, D, B, H, I, G, F

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Unit 2- Chapter 5- Inheritance and Polymorphism

INHERITANCE:
Inheritance is a feature that is present in many object-oriented languages such as C++, Eiffel, Java, Ruby, and
Smalltalk, but each language implements it in its own way.
Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an
application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can
designate that the new class should inherit the members of an existing class. This existing class is called
the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal
hence dog IS-A animal as well and so on.

Base & Derived Classes:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

A class can be derived from more than one classes, which means it can inherit data and functions from multiple base
classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list
names one or more base classes and has the form:
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined
class. If the access-specifier is not used, then it is private by default.
Syntax:-
class Base
{
};
class Derived: public Base
{
};

Example:
#include <iostream>
using namespace std;
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape
{

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

public:
int getArea()
{
return (width * height);
}
};

int main(void)
{
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

return 0;
}

Derived Classes:-
Inheritance is a feature of an object-oriented language that allows classes or objects to be defined as extensions or
Specializations of other classes or objects. In C++, classes inherit from other classes. Inheritance is useful when a project contains many
similar, but not identical, types of objects. In this case, the task of the programmer/software engineer is to find commonality in this set of
similar objects, and create a class that can serve as an archetype for this set of classes. 1.1.2

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Examples
Squares, triangles, circles, and hexagons are all 2D shapes; hence a Shape class could be an archetype.
Faculty, administrators, office assistants, and technical support staff are all employees, so an Employee class could be an archetype.
Cars, trucks, motorcycles, and buses are all vehicles, so a Vehicle class could be an archetype. When this type of relationship exists
among classes, it is more efficient to create a class hierarchy rather than replicating member functions and p

When this type of relationship exists among classes, it is more efficient to create a class hierarchy rather than replicating member functions
and properties in each of the classes. Inheritance provides the mechanism for achieving this.

Access Control and Inheritance:


A derived class can access all the non-private members of its base class. Thus base-class members that should not
be accessible to the member functions of derived classes should be declared private in the base class.
We can summarize the different access types according to who can access them in the following way:

Access public protected private


Same class yes yes yes
Derived
yes yes no
classes
Outside
yes no no
classes

A derived class inherits all base class methods with the following exceptions:
Constructors, destructors and copy constructors of the base class.
Overloaded operators of the base class.
The friend functions of the base class.
. The derived class does not have access to the base class's private members.
The derived class has access to all public and protected members of the base class.
The friend functions and friend classes of the base class are not inherited.

Modes of Inheritance:
There are three types of inheritance in C++.
Private inheritance
Public inheritance
Protected inheritance

The access specifier private is not accessible outside the class. The access specifier publicis accessible outside the
class. The access specifier protected is accessible in the derived class with some restrictions, the explanation is
given later.

1. Private inheritance

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

In the derived class, the reserved word private is optional before the base class but for a good programming practice
it is a good idea to use it. Otherwise, it will be considered as private by default.
A member declared with the access specifier private could be accessed only be members of a class where it is
defined. The derived class is restricted to the private section.
For example
derived_calss:private base_class
{ };
Or
derived_class:base_class
{ };
2. Public inheritance
This type of inheritance must be explicitly mentioned. Instead of private, which is by default, simply use
public.
For example
Derive_class: public base_class
{};
3. Protected inheritance
The word protected in the derived class means that if another class is derived from this current derived class that is
derived_derived class, the protected members in the base class will be private in the first derived class instead of
public. This prohibits the derived_derived class from being access to the protected members of the base class.
that when a derived object is destroyed, the destructor it contains is called first, followed by the base class destructor,
if it exists.

Types of Inheritance:
In C++, we have 5 different types of Inheritance. Namely,
Single Inheritance

Multiple Inheritance

Hierarchical Inheritance

Multilevel Inheritance

Hybrid Inheritance (also known as Virtual Inheritance)

1) Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from one base class.

2) Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from multiple base
class(es).

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

3) Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherit from one base
class.

4) Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class for other
classes.

5) Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other four types of
inheritance.

Inheritance guidelines:
We know that inheritance is a relationship that is a way of relating two classes so that one class is capable of using
another class members without redefining them. Anything that is associated with an access specfier public is
accessible or visible to all derived classes of a base class. The information given to and taken from the member
function of the same access specifier is accessible by code outside the class. The next specifier comes private, which
is known as the highest level of data hidng. The private members of the base or super class remain inaccessible
even to the derived class or sub class. The third and last access specifier is the protected. Data member and member
function associated with this access specifier can be inherited by the sub class or child class or derived class. With
two objects of the same class, they are not allowed to use each other data member of the protected access specifier.
Both will have the same names with different data.
It is to be noted that when an object of a derived class is created, if there exist a constructor in the base class, it will
be called first, followed by the derived class constructor. It is also to be noted.

POLYMORPHISM:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

The word polymorphism means having many forms, Poly" means "many" and "morph" means "form". Polymorphism
is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object.

Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

C++ polymorphism means that a call to a member function will cause a different function to be executed depending

on the type of object that invokes the function.

Example:

1) Function overloading, function overriding, virtual functions


2) plus + sign, used for adding two integers or for using it to concatenate two strings.

Consider the following example where a base class has been derived by other two classes:

#include <iostream>

using namespace std;

class Shape {

protected:

int width, height;

public:

Shape( int a=0, int b=0)

width = a;

height = b;

int area()

cout << "Parent class area :" <<endl;

return 0;

};

class Rectangle: public Shape{

public:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Rectangle( int a=0, int b=0):Shape(a, b) { }

int area ()

cout << "Rectangle class area :" <<endl;

return (width * height);

};

class Triangle: public Shape{

public:

Triangle( int a=0, int b=0):Shape(a, b) { }

int area ()

cout << "Triangle class area :" <<endl;

return (width * height / 2);

};

// Main function for the program

int main( )

Shape *shape;

Rectangle rec(10,7);

Triangle tri(10,5);

// store the address of Rectangle

shape = &rec;

// call rectangle area.

shape->area();

// store the address of Triangle

shape = &tri;

// call triangle area.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

shape->area();

return 0;

When the above code is compiled and executed, it produces the following result:

Parent class area

Parent class area

The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the

version defined in the base class. This is called static resolution of the function call, or static linkage - the function

call is fixed before the program is executed. This is also sometimes called early binding because the area()

function is set during the compilation of the program.

But now, let's make a slight modification in our program and precede the declaration of area() in the Shape class

with the keyword virtual so that it looks like this:

class Shape {

protected:

int width, height;

public:

Shape( int a=0, int b=0)

width = a;

height = b;

virtual int area()

cout << "Parent class area :" <<endl;

return 0;

};

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

After this slight modification, when the previous example code is compiled and executed, it produces the following

result:

Rectangle class area

Triangle class area

This time, the compiler looks at the contents of the pointer instead of it's type. Hence, since addresses of objects of

tri and rec classes are stored in *shape the respective area() function is called.

As you can see, each of the child classes has a separate implementation for the function area(). This is

how polymorphism is generally used. You have different classes with a function of the same name, and even the

same parameters, but with different implementations.

Function Overloading:

Function overloading in C++: Function overloading means two or more functions can have the same name but either
the number of arguments or the data type of arguments has to be different. Return type has no role because function
will return a value when it is called and at compile time compiler will not be able to determine which function to call. In
the first example in our code we make two functions one for adding two integers and other for adding two floats but
they have same name and in the second program we make two functions with identical names but pass them
different number of arguments. Function overloading is also known as compile time polymorphism.

#include <iostream>

using namespace std;

/* Function arguments are of different data type */

long add(long, long);


float add(float, float);

int main()
{
long a, b, x;
float c, d, y;

cout << "Enter two integers\n";


cin >> a >> b;

x = add(a, b);

cout << "Sum of integers: " << x << endl;

cout << "Enter two floating point numbers\n";


cin >> c >> d;

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

y = add(c, d);

cout << "Sum of floats: " << y << endl;

return 0;
}

long add(long x, long y)


{
long sum;

sum = x + y;

return sum;
}

float add(float x, float y)


{
float sum;

sum = x + y;

return sum;
}

In the above program, we have created two functions "add" for two different data types you can create more than two
functions with same name according to requirement but making sure that compiler will be able to determine which
one to call. For example you can create add function for integers, doubles and other data types in above program. In
these functions you can see the code of functions is same except data type, C++ provides a solution to this problem
we can create a single function for different data types which reduces code size which is via templates.

Function Overriding:

If we inherit a class into the derived class and provide a definition for one of the base class's function again inside the

derived class, then that function is said to be overridden, and this mechanism is called Function Overriding

Requirements for Overriding:

1. Inheritance should be there. Function overriding cannot be done within a class. For this we require a derived

class and a base class.

2. Function that is redefined must have exactly the same declaration in both base and derived class, that

means same name, same return type and same parameter list.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Example of Function Overriding:

class Base

public:

void show()

cout << "Base class";

};

class Derived:public Base

public:

void show()

cout << "Derived Class";

In this example, function show() is overridden in the derived class. Now let us study how

these overridden functions are called in main() function.

Function Call Binding with class Objects:

Connecting the function call to the function body is called Binding. When it is done before the program is run, its

called Early Binding or Static Binding or Compile-time Binding.

class Base

public:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

void shaow()

cout << "Base class\t";

};

class Derived:public Base

public:

void show()

cout << "Derived Class";

int mian()

Base b; //Base class object

Derived d; //Derived class object

b.show(); //Early Binding Ocuurs

d.show();

Output : Base class Derived class

In the above example, we are calling the overrided function using Base class and Derived class object. Base class

object will call base version of the function and derived class's object will call the derived version of the function.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Function Call Binding using Base class Pointer:

But when we use a Base class's pointer or reference to hold Derived class's object, then Function call Binding gives

some unexpected results.

class Base

public:

void shaow()

cout << "Base class";

};

class Derived:public Base

public:

void show()

cout << "Derived Class";

int mian()

Base* b; //Base class pointer

Derived d; //Derived class object

b = &d;

b->show(); //Early Binding Occurs

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Output : Base class

In the above example, although, the object is of Derived class, still Base class's method is called. This happens due

to Early Binding.

Compiler on seeing Base class's pointer, set call to Base class's show() function, without knowing the actual object

type.

Runtime Polymorphism or Dynamic method dispatch:


Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how
java implements runtime polymorphism. When an overridden method is called by a reference, java determines which
version of that method to execute based on the type of object it refers to. In simple words the type of object which it
referred determines which version of overridden method will be called.

Compile-time binding (Static binding):

Compile-time binding is to associate a functions name with the entry point of the function at compile time.

Example:

#include<iostream>

using namespace std;

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

void sayHi();

int main()

sayHi(); // the compiler binds any invocation of sayHi() // to sayHi()s entry point.

void sayHi()

cout << Hello, World!\n;

In C, only compile-time binding is provided.

In C++, all non-virtual functions are bound at compile-time.

Run-time binding (Dynamic binding):

Run-time binding is to associate a functions name with the entry point at run-time.

C++ supports run-time binding through virtual functions.

Polymorphism is thus implemented by virtual functions and run-time binding mechanism in C++. A class is called
polymorphic if it contains virtual functions.

A typical scenario of polymorphism in C++:

There is an inheritance hierarchy

The first class that defines a virtual function is the base class of the hierarchy that uses dynamic binding for that
function name and signature.

Each of the derived classes in the hierarchy must have a virtual function with same name and signature.

There is a pointer of base class type; and this pointer is used to invoke virtual functions of derived class.

Example:

#include<iostream>

class Shape

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

public: virtual void sayHi()

{ Cout< <Just hi! \n;}

};

class Triangle : public Shape{

public:

virtual void sayHi()

cout <<Hi from a triangle! \n

};

class Rectangle : public Shape

public:

virtual void sayHi() { cout <<Hi from rectangle! \n;}

};

int main()

Shape *p;

int which;

cout << 1 -- shape, 2 -- triangle, 3 -- rectangle\n ; cin >> which;

switch ( which )

case 1: p = new Shape; break;

case 2: p = new Triangle; break;

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

case 3: p = new Rectangle; break;

p -> sayHi(); // dynamic binding of sayHi() delete p;

Unit 2- Chapter 6- Packages, Interface and Exceptions

Packages:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

A package allows a developer to group classes (and interfaces) together. It is easy to organize class files into
packages. All we need to do is put related class files in the same directory, give the directory a name that relates to
the purpose of the classes, and add a line to the top of each class file that declares the package name, which is the
same as the directory name where they reside.

Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and
usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations )
providing access protection and name space management.

Some of the existing packages in Java are::

java.lang - bundles the fundamental classes

java.io - classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to
group related classes implemented by you so that a programmer can easily determine that the classes, interfaces,
enumerations, annotations are related.

Since the package creates a new namespace there won't be any name conflicts with names in other packages.
Using packages, it is easier to provide access control and it is also easier to locate the related classes.

For example: java.lang, java.io, java.util etc.

Creating a package:

When creating a package, you should choose a name for the package and put a packagestatement with that name
at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you
want to include in the package.

The package statement should be the first line in the source file. There can be only one package statement in each
source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an
unnamed package.
package <package name>;

Example:

package tools; publicclassHammer {

publicvoid id () {

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

System.out.println ("Hammer");

Advantages of using a package:

Before discussing how to use them let see why we should use packages.

Reusability: Reusability of code is one of the most important requirements in the software industry.

Reusability saves time, effort and also ensures consistency. A class once developed can be reused by any

number of programs wishing to incorporate the class in that particular program.

Easy to locate the files.

In real life situation there may arise scenarios where we need to define files of the same name. This may

lead to name-space collisions. Packages are a way of avoiding name-space collisions.

Controlling Access to Members of a Class:

Access level modifiers determine whether other classes can use a particular field or invoke a particular method.
There are two levels of access control:

At the top levelpublic, or package-private (no explicit modifier).

At the member levelpublic, private, protected, or package-private (no explicit modifier).

A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a
class has no modifier (the default, also known as package-private), it is visible only within its own package.
The following table shows the access to members permitted by each modifier.

At the member level, you public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same
meaning. For members, there are two additional access modifiers: private and protected. The private modifier
specifies that the member can only be accessed in its own class. The protected modifier specifies that the member

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in
another package.

Access Levels

Modifier Class Package Subclass World

Interfaces:
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract

methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A

class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an interface:

Example:

Let us look at an example that depicts encapsulation:

import java.lang.*;

//Any number of import statements

publicinterfaceNameOfInterface{

//Any number of final, static fields

//Any number of abstract method declarations\

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the

specific behaviours of the interface. If a class does not perform all the behaviors of the interface, the class must

declare itself as abstract.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

A class uses the implements keyword to implement an interface. The implements keyword appears in the class

declaration following the extends portion of the declaration.

publicclassMammalIntimplementsAnimal{

publicvoid eat(){

System.out.println("Mammal eats");

publicvoid travel(){

System.out.println("Mammal travels");

publicint noOfLegs(){

return0;

publicstaticvoid main(String args[]){

MammalInt m =newMammalInt();

m.eat();

m.travel();}

This would produce the following result:

Mammal eats

Mammal travels

Exceptions:
An exception is a problem that arises during the execution of a program. An exception can occur for many different

reasons, including the following:

A user has entered invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or the JVM has run out of memory.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources

that have failed in some manner.

To understand how exception handling works in Java, you need to understand the three categories of exceptions:

Checked exceptions: A checked exception is an exception that is typically a user error or a problem that
cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found,
an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

Runtime exceptions: A runtime exception is an exception that occurs that probably could have been
avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time
of compilation.

Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error.
For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block is referred to as protected code,
and the syntax for using try/catch looks like the following:

try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in
protected code, the catch block (or blocks) that follow the try is checked. If the type of exception that occurred is
listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method
parameter.

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword. The
throws keyword appears at the end of a method's signature.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using
the throw keyword. Try to understand the different in throws and throw keywords.

Example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array
which throws an exception.

import java.io.*;

publicclassExcepTest {

publicstaticvoid main(String args[]) {

try{

int a[]=newint[2];

System.out.println("Access element three :"+ a[3]);

} catch(ArrayIndexOutOfBoundsException e) {System.out.println("Exception thrown :"+ e);

System.out.println("Out of the block");

This would produce the following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException:3

Out of the block

User defined Exception:

This example shows how to create user defined exception by extending Exception Class.

classWrongInputExceptionextendsException{

WrongInputException(String s){

super(s);

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

classInput{

void method()throwsWrongInputException{

thrownewWrongInputException("Wrong input");

classTestInput{

publicstaticvoid main(String[] args) {

try{

newInput().method();

catch(WrongInputException wie){System.out.println(wie.getMessage());

Result:

The above code sample will produce the following result.

Wrong input

Advantages of Exceptions:

Advantage 1: Separating Error-Handling Code from "Regular" Code

Advantage 2: Propagating Errors Up the Call Stack

Advantage 3: Grouping and Differentiating Error Types

Note the following:

A catch clause cannot exist without a try statement.

It is not compulsory to have finally clauses whenever a try/catch block is present.

The try block cannot be present without either catch clause or finally clause.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Any code cannot be present in between the try, catch, finally blocks.

Unit 3- Chapter 7- Database Design Process


Introduction:
Data: Known facts that can be recorded and that have implicit meaning is known as Data.
Database: Collection of related data can be called as a Database.
DBMS: Collection of programs that enables the user to create and maintain a database
is nothing but Data Base Management System.
DBMS: Data + set of programs to access/manipulate data.
Formal Definition:
DBMS: is a general purpose software system that facilitates the processes of defining, constructing,
manipulating, and sharing databases among various users and applications.

o Defining Defining a database involves specifying the datatypes, structures, and constraints of the
data that has to be stored in the database.
o Constructing Constructing the database is the process of storing the data itself on some storage
medium that is controlled by the DBMS.
o Manipulating Manipulating a database includes such functions as querying the database to
retrieve specific data, updating the database to reflect changes in the mini world, and generating
reports from the data.
o Sharing Sharing a database allows multiple users and programs to access the database
simultaneously.

Example :
University Database:
-Data about students, faculty, courses, research laboratories, course registration/ enrollment etc..
-It reflects the state of affairs of the academic aspects of the university.
Purpose : To keep an accurate track of the academic activities of the university.

Simplified database system environment:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Characteristics of DBMS:
There are a number of characteristics that distinguish the database approach with the file-based approach. Few are
listed below:

i. Self describing nature of Database System :

- DB system contains the complete definition of structure and the constraints which makes itself describing.

- The description of the structure and constraints of the data is termed as Meta-data.

- This information (meta-data) is used either by the DBMS software or database users who need information
about the database structures.

- On the other hand, in file based systems, the definition of the data is a part of application program that has
to be handled by the users.

ii. Insulation between Program and Data :

- In file based system, the structure of the data is stored in the application program. As a result, if we want to
change any definition of the data, then the program that accesses that data has to be changed.

- Whereas, in database systems, as the data structures are stored in the catalog and not in programs, we can
manipulate any one i.e. either program or data whichever is needed.

- Thus DBMS provides program and data independence.

iii. Support multiple views of the Data :

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

- View is a subset of the database. View contains virtual data that is derived from the database files but it is
not explicitly stored.

- Multiple users in the same Database system might have different views of that system. Each view might
contain only the data of interest to that user or a group of users.

- In this way DBMS supports multiple views of the data.

iv. Sharing of data and multi user transaction processing :

- Allows multiple users to access the data at the same time.

- The Concurrency Control Techniques of DBMS ensures that several users trying to access and update the
same data do so in a controlled manner.

- Thus DBMS provides multiple user transaction unlike the file based system where the transaction
processing is restricted for single user.

v. Enforcing Integrity Constraints :

- DBMS provides certain methodologies to define and enforce certain constraints such as data type, data

uniqueness, etc.

vi. Restricting unauthorized access :

- Not all users of the system have the same accessing privileges. DBMS provides a security sub system to

create and control the user accounts.

vii. Providing backup and recovery facilities

- If the computer system fails in the middle of a complex update process, the recovery subsystem is

responsible for making sure that the database is restored to the stage it was in before the process started

executing.

Entity- Relation Model:

- Entity - relation model (abbreviated as ER model) is the conceptual view of a database.

- At view level, the ER model is considered a good option for designing databases.

- Entity :

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

An entity can be a real-world object, that can be easily identifiable.

Example, in an university database, students, teachers, classes, and courses offered can be

considered as entities.

- Entity set :

An entity set is a collection of similar types of entities.

An entity set may contain entities with their properties sharing similar values.

For example, a Students set may contain all the students of university; likewise a Teachers set may

contain all the teachers of university from all faculties.

Entity sets need not be disjoint.

Attributes:

Entities are represented by means of their properties, called attributes.

All attributes have values.

For example, a student entity may have name, class, and age as attributes.

There exists a domain or range of values that can be assigned to attributes. For example,
a student's name cannot be a numeric value. It has to be alphabetic. A student's age
cannot be negative, etc.

Types of attributes :

o Simple attribute: The attributes with the atomic values which cannot be divided
further are classified as Simple attributes. For example, a student's phone
number is an atomic value of 10 digits.

o Composite attribute: Attributes made up of more than one simple attribute are
termed as Composite attributes. For example, a student's complete name may
have first_name , middle_name and last_name.

o Derived attribute: Derived attributes are the attributes that do not exist in the
physical database, but their values are derived from other attributes present in
the database. For example, average_salary in a department should not be
saved directly in the database, instead it can be derived. To quote another
example, age can be derived from data_of_birth.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

o Single value attribute: Single value attributes contain single value. For
example , Social_security_number of an employee, USN of a student etc..

o Multi value attribute: Multi value attributes may contain more than one values.
For example, a person can have more than one phone numbers, email
addresses etc ..

These attribute types can come together in a way like

simple single-valued attributes

simple multi-valued attributes

composite single-valued attributes

composite multi-valued attributes

Keys:

Key is an attribute or collection of attributes that uniquely identifies an entity

among entity set.

For example, the roll_number of a student makes him/her identifiable among

students.

o Super Key A set of attributes (one or more) that collectively identifies an entity in

an entity set.

o Candidate Key A minimal super key is called a candidate key. An entity set may

have more than one candidate key.

o Primary Key A primary key is one of the candidate keys chosen by the database

designer to uniquely identify the entity set.

Relationship:

The association among entities is called a relationship.

For example, an employee works_at department,a student enrolls in a course.

Here,Works_at and Enrolls are the relationships.

Degree of a relationship:

Number of entities participating in a relationship defines the degree of that


relationship.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Types :

- Binary -> degree=2

- Ternary -> degree=3

- n-ary -> degree=n

Mapping cardinalities:

Cardinality defines the number of entities in one entity set, which can be associated with

the number of entities of other entity set via relationship set.

Types of Cardinality :

I. One-to-one One entity from entity set A can be associated with at most one entity of

entity set B and vice versa.

II. One-to-many One entity from entity set A can be associated with more than one

entities of entity set B however an entity from entity set B, can be associated with at

most one entity.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

III. Many-to-one

More than one

entities from

entity set A can

be associated with

at most one entity

of entity set B,

however an

entity from entity set B can be associated with more than one entity from entity set A.

IV. Many-to-many One entity from A can be associated with more than one entity from B

and vice versa.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Mapping ER Model to Relational Schema:

Relational Schema:
o Relational Schema consists of relational name, and a set of attributes or field names or column
names.
o Each attribute is associated with its domain.
o Domain = Set of atomic values + Data types.

ER to Relational Schema Algorithm:


Steps involved in converting the ER model to relational Schema:
Step1: Mapping of Regular Entity Types:
For each regular (strong) entity type E in the ER schema, create a relation R that includes all the simple
attributes of E. Include only the simple component attributes of a composite attribute.
Choose one of the key attributes of E as primary key for R. If the chosen key of E is composite, the set
of simple attributes that form it will together form the primary key of R.

Step2: Mapping of Weak Entity Types :


For each weak entity type W in the ER schema with owner entity type E , create a relation R and
include all simple attributes (or simple components of composite attributes) of W as attributes of R.
In addition, include as foreign key attributes of R the primary key attribute(s) of the relation(s) that
correspond to the owner entity type(s); this takes care of the identifying relationship type of W.
The primary key of R is the combination of the primary key(s) of the owner(s) and the partial key of the
weak entity type W, if any.

Step3: Mapping of Binary 1:1 Relationship Types :


For each binary 1:1 relationship type R in the ER schema, identify the relations S and T that correspond
to the entity types participating in R.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Choose one of the relations S, say and include as a foreign key in S the primary key of T. It is better
to choose an entity type with total participation in R in the role of S.

Include all the simple attributes (or simple components of composite attributes) of the 1:1 relationship
type R as attributes of S.

Step4: Mapping of Binary 1:N Relationship Types :


For each regular binary 1:N relationship type R, identify the relation S that represents the participating
entity type at the N side of the relationship type.

Include as foreign key in S the primary key of the relation T that represents the other entity type
participating in R; (this is done because each entity instance on the N-side is related to at most one
entity instance on the 1-side of the relationship type).

Include any simple attributes (or simple components of composite attributes) of the 1:N relationship type
as attributes of S.

Step5: Mapping of Binary M:N Relationship Types :


For each binary M:N relationship type R, create a new relation S to represent R.

Include as foreign key attributes in S the primary keys of the relations that represent the participating
entity types; their combination will form the primary key of S.

Also include any simple attributes of the M:N relationship type (or simple components of composite
attributes) as attributes of S.

Step6: Mapping of Multi valued Attributes :


For each multi valued attribute A, create a new relation R. This relation R will include an
attribute corresponding to A, plus the primary key attribute K- as corresponding to A, plus the
primary key attribute K- as a foreign key in R- of the relation that represents the entity type
or relationship type that has A as an attribute.

The primary key of R is the combination of A and K. If the multi valued attribute is
composite, we include its simple components.

Step7: Mapping of N- ary Relationship Types :


For each n-ary relationship type R, where n>2, create a new relation S to represent R.

Include as foreign key attributes in S the primary keys of the relations that represent the
participating entity types.

Also include any simple attributes of the n-ary relationship type (or simple components of
composite attributes) as attributes of S.
The primary key of S is usually a combination of all the foreign keys that reference the
relations representing the participating entity types.
Normalization:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Informal design guidelines for Relational Schema:


Measures of quality:
1. Making sure attribute semantics (meanings) are clear.
2. Reducing redundant information in tuples (records).
3. Reducing NULL values in tuples.
4. Disallowing possibility of generating spurious tuples (unwanted additional tuples generated by some join of two
relations).

Normalization:
Normalization is the Formal technique for analyzing a relation based on
- Its primary key and
-The FDs between the attributes of that relation.

-A relation can be normalized to a specific form to prevent the possible occurrence of update anomalies.

- As normalization proceeds, the relations become progressively more restricted (stronger) in format and also less
vulnerable to update anomalies.

-Most commonly used normal forms are:


1NF
2NF
3NF
BCNF
4NF
5NF

First Normal Form :


Def: A relation schema R is in 1NF if every attribute of R takes only single and atomic values.
Example:
Student_Apply(RollNo, Name, Age, DeptName)

RollNo Name Age


DeptName
201 Amar 30
{ise, cse}
205 Akbar 32
{ece}
-This Violates 203 Anthony 31 1NF, because of DeptName
i.e. a single {auto, robo} student cannot belong to
two departments.
Solution1:
Use multiple tuples one per value.
Student_Apply(RollNo, DeptName, Name, Age)

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Solution2:
Split the Student table into two different tables.
Student(RollNo, Name, Age)
Apply(RollNo,DepName)
Second Normal Form:
Def: A relation schema R is in 2NF if and only if it is in 1NF and every non-prime attribute in R is fully functionally
dependent on key.
Example :
Consider:
Student (RollNo, Name, Dept, Gender, HostelName, RoomNo)
Assumption: Boys & girls are accommodated in separate hostels
Keys: RollNo, (HostelName, RoomNo)

Q: Is this relation in 2NF ?


A:Not in 2NF as HostelNameGender i.e.(not fully functionally dependent because HostelName is just a part of the
key)

Converting to 2NF: [Both the relations are in 2NF]


R1: Student (RollNo, Name, Dept, HostelName, RoomNo)
R2: HostelDetail(HostelName, Gender)

Third Normal Form :


Def: Relation schema R is in 3NF if it is in 2NF and no non-prime attribute of R is transitively dependent on any key
of R.
Example :
Student (rollNo,name,dept,hostelname,roomNo,headDept)
Is it in 3NF? [No]
Decompose:
R1 : Student(rollNo,name,dept,hostelName,roomNo)
R2 : deptInfo(dept,headDept)
Both R1 and R2 are in 3NF.Hence the Redundancy in data storage is removed.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Unit 3- Chapter 8- Structured Query Language

SQL (Structural Query Language)

SQL (Structured Query Language) is a standard supported by all the popular


Relational database management systems in the market place.
The basis data structure in RDBMS is a table.
SQL provides you the features to define tables, define constraints on tables, query for data in
table, and change the data in table by adding, modifying, and removing data.
SQL also supports grouping of data in multiple rows, combining tables and other features.
All these put together, SQL is a high-level query language standard to access and alter data in
RDBMS.

Clauses we have in SQL:

SELECT clause

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

FROM clause
WHERE clause
GROUP BY
HAVING

Clauses can be used:


To retrieve/insert/modify existing data from database.
Get all data from the table
Get selected columns from the table.
Get selected rows from the table.
Get selected columns of selected rows from the table.
Get computed columns using char, number, data functions, general functions, and aggregating
functions.
Get data in multiple rows grouped on an aggregating function applied on one or more columns.
Select specific aggregating data on multiple rows using having clause.
Apply set operations like Union and Intersection on data sets of the same cardinality and type.
Get data from multiple tables using Cartesian product, equality join, un-equal join, and outer
join.
Create views on physical data.

Data types in SQL:


1. Character data type : This data type is used when the data to be manipulated includes letters,
numbers, spaces and other symbols i.e. it can be stored as alpha-numerical values. This data
type is used when a fixed length character is required.
2. Varchar2 data type : This data type is used to store the same type of data say the character
data type. If a value less than the specified size is entered then the field is automatically fixed
to that length. If a value larger than the specified size is entered than the additional characters
are ignored. This data type can be used to save a lot of disk space.
3. Number data type : Data types that are restricted to pure numbers belong to this data type.
This data type includes a combination of digits 0 through 9, a decimal point and a minus sign if
necessary.
4. Date data type : This data type is used to store date and time in a table. The format of storage
varies with respect to database in use.

DBMS Languages
Data definition language (DDL)
Defines schemas
Storage definition language (SDL)
Specifies the internal schema
View definition language (VDL)
Specifies user views/mappings to conceptual schema
Data manipulation language (DML)
Allows retrieval, insertion, deletion, modification

Data Definition Language (DDL):


To do with altering the structure of data base.
Create tables.
Create Indexes on tables.
Alter tables
Add constraints to tables.
Drop tables.
Truncate tables.

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Drop indexes.
Create sequences.

Data Manipulation Language (DML):


To do with adding, updating, and deleting data from tables.
Insert Data
Update Data
Delete Data
Merge Tables.

Data Control Language (DCL):


To do with controlling access to data in tables.
Grant Permissions
Revoke Permissions
Create and update roles.
Add users to roles.

DDL commands:

1. The Create Table Command: It defines each column of the table uniquely. Each column has minimum
of three attributes, a name, data type and size.

Syntax:

Create table <table name> (<col1> <datatype>(<size>),<col2> <datatype><size>));

Ex:
create table emp(
empno number(4) primary key,
ename char(10));

2. Modifying the structure of tables.

a) add new columns

Syntax:
Alter table <tablename> add(<new col><datatype(size),<new col>datatype(size));

Ex:
alter table emp add(sal number(7,2));

3. Dropping a column from a table.

Syntax:
Alter table <tablename> drop column <col>;

Ex:
alter table emp drop column sal;

4.Modifying existing columns.

Syntax:
Alter table <tablename> modify(<col><newdatatype>(<newsize>));

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

Ex:
alter table emp modify(ename varchar2(15));

5. Renaming the tables

Syntax:
Rename <oldtable> to <new table>;

Ex:
rename emp to emp1;

6. Truncating the tables.

Syntax:
Truncate table <tablename>;

Ex:
trunc table emp1;

7. Destroying tables.

Syntax:
Drop table <tablename>;

Ex:
drop table emp;

DML commands:

1. Inserting Data into Tables: -

Once a table is created the most natural thing to do is load this table with data to be manipulated later.

Syntax 1:
insert into <tablename> (<col1>,<col2>.....<col n>) values(<val 1>, <val 2>.......<val n>);

Syntax 2:
insert into <tablename> values(&<col1>,&<col2>......,&<col n>);

Syntax 3:
insert into <tablename> values(<val 1>,<val 2>.......,<val n>);

Ex 1:
Insert into skc(sname,rollno,class,dob,fee_paid)values(sri,104B,cse,27-feb-05,10000.00);

Ex 2:
insert into skc values(&sname,&roll no,&class); enter sname:sri
enter roll no:104B enter class:cse

Ex 3:

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

insert into skc values(sri,104B,cse,27-feb-05,10000.00);

2. Delete operations.

a) Remove all rows

Syntax:
delete from <tablename>;

b) Removal of a specified row/s

Syntax:
delete from <tablename> where <condition>;

3. Updating the contents of a table.

a) updating all rows

Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp>;

b) updating seleted records.

Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp> where <condition>;

4. Types of data constrains.

a) not null constraint at column level.

Syntax:
<col><datatype>(size)not null

b) unique constraint

Syntax:
Unique constraint at column level. <col><datatype>(size)unique;

c) unique constraint at table level:

Syntax:
Create table
tablename(col=format,col=format,unique(<col1>,<col2>);

d) primary key constraint at column level

Syntax:
<col><datatype>(size)primary key;
e) primary key constraint at table level.

Syntax:
Create table tablename(

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

col=format,
col=format
primary key(col1>,<col2>);

f) foreign key constraint at column level.

Syntax:
<col><datatype>(size>) references <tablename>[<col>];

g) foreign key constraint at table level

Syntax:
foreign key(<col>[,<col>]) references <tablename>[(<col>,<col>)

h) check constraint

Syntax:
<col><datatype>(size) check(<logical expression>)

i) check constraint constraint at table level.

Syntax:
check(<logical expression>)

DCL commands:
Oracle provides extensive feature in order to safeguard information stored in its tables from
unauthoraised viewing and damage. The rights that allow the user of some or all oracle resources on the
server are called privileges.

a) Grant privileges using the GRANT statement


The grant statement provides various types of access to database objects such as tables,views and
sequences and so on.

Syntax:
GRANT <object privileges> ON <objectname> TO<username> [WITH GRANT OPTION];

b) Revoke permissions using the REVOKE statement:


The REVOKE statement is used to deny the Grant given on an object.

Syntax:
REVOKE<object privilege>
ON
FROM<user name>;

Example-1
CREATING A STUDENT RELATION TABLE WITH ALL DATATYPES:

Example:
create table student252(
sid number(5),
sname varchar(20),

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

sbranch char(5),
dob date,
spercent number(3,2));

INSERT THE RECORDS INTO STUDENT RELATION:


METHOD 1:
Insert into Student252(sid,sname,sbranch,dob,spercent) values(104,sri,,cse,27-
feb-05,70);
1 row created.

METHOD 2:
Insert into Student252 values(104,sri,,cse,27-feb-05,70);
1 row created.

METHOD 3:
Insert into Student252(sid,sname,sbranch,dob,spercent) values(&sid,
&sname,&sbranch,&dob,&spercent);
1 row created.

METHOD 4:
Insert into Student252(sid,sname,sbranch,dob,spercent) values(&sid,
&sname,&sbranch,&dob,&spercent);
1 row created.

To retrieve all data from the database.


Select * from Student252;

To retrieve data related to student with percent greater than 90%


Select * from Student252 where spercent = 90;

MODIFYING THE STRUCTURE OF TABLE

ADDING A NEW COLUMN


ALTER TABLE Emp252 ADD (age number(3), phno number(10));
Table altered.

MODIFYING EXISTING COLUMN


ALTER TABLE Emp252 MODIFY (phno varchar(20));
Table altered.

DROPING A COLUMN
ALTER TABLE Emp252 DROP COLUMN phno;
Table altered.

Operators in Database:
What is an Operator in SQL?

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform
operation(s), such as comparisons and arithmetic operations.

Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in
a statement.

Arithmetic operators

Comparison operators

Logical operators

Operators used to negate conditions

SQL Arithmetic Operators:


Assume variable a holds 10 and variable b holds 20, then:

Operator Description Example

+ Addition - Adds values on either side of the operator a + b will


give 30

- Subtraction - Subtracts right hand operand from left a - b will


hand operand give -10

* Multiplication - Multiplies values on either side of the a * b will


operator give 200

/ Division - Divides left hand operand by right hand b / a will


operand give 2

% Modulus - Divides left hand operand by right hand b%a


operand and returns remainder will give
0

SQL Comparison Operators:


Assume variable a holds 10 and variable b holds 20, then:

Operator Description Example

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

= Checks if the values of two operands are equal or not, if (a = b) is


yes then condition becomes true. not true.

!= Checks if the values of two operands are equal or not, if (a != b)


values are not equal then condition becomes true. is true.

<> Checks if the values of two operands are equal or not, if (a <> b)
values are not equal then condition becomes true. is true.

> Checks if the value of left operand is greater than the (a > b) is
value of right operand, if yes then condition becomes true. not true.

< Checks if the value of left operand is less than the value of (a < b) is
right operand, if yes then condition becomes true. true.

>= Checks if the value of left operand is greater than or equal (a >= b)
to the value of right operand, if yes then condition is not
becomes true. true.

<= Checks if the value of left operand is less than or equal to (a <= b)
the value of right operand, if yes then condition becomes is true.
true.

!< Checks if the value of left operand is not less than the (a !< b)
value of right operand, if yes then condition becomes true. is false.

!> Checks if the value of left operand is not greater than the (a !> b)
value of right operand, if yes then condition becomes true. is true.

SQL Logical Operators:


Here is a list of all the logical operators available in SQL.

Operator Description

ALL The ALL operator is used to compare a value to all values in another

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

value set.

AND The AND operator allows the existence of multiple conditions in an


SQL statement's WHERE clause.

ANY The ANY operator is used to compare a value to any applicable value
in the list according to the condition.

BETWEEN The BETWEEN operator is used to search for values that are within a
set of values, given the minimum value and the maximum value.

EXISTS The EXISTS operator is used to search for the presence of a row in a
specified table that meets certain criteria.

IN The IN operator is used to compare a value to a list of literal values


that have been specified.

LIKE The LIKE operator is used to compare a value to similar values using
wildcard operators.

NOT The NOT operator reverses the meaning of the logical operator with
which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN,
etc. This is a negate operator.

OR The OR operator is used to combine multiple conditions in an SQL


statement's WHERE clause.

IS NULL The NULL operator is used to compare a value with a NULL value.

UNIQUE The UNIQUE operator searches every row of a specified table for
uniqueness (no duplicates).

The ORDER BY Keyword:

The ORDER BY keyword is used to sort the result-setby a specified column.

Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DSC

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

SQL Aggregate Functions

SQL aggregate functions return a single value, calculated from values in a column.

Useful aggregate functions:


AVG() - Returns the average value
COUNT() - Returns the number of rows
FIRST() - Returns the first value
LAST() - Returns the last value
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum

The SUM() and AVG() Function

The SUM() function returns the total sum of a numeric column.

Syntax:
SELECT SUM(column_name) FROM table_name;

The AVG() function returns the average value of a numeric column.

SELECT AVG(column_name) <AS avg_Col_name> FROM table_name

The COUNT() Function

The COUNT(column_name) function returns the number of values (NULL values will not be counted) of
the specified column

Syntax:
SELECT COUNT(column_name) FROM table_name;

The COUNT(*) function returns the number of recordsin a table

Syntax:
SELECT COUNT(DISTINCT column_name) FROM table_name;

The MAX() and MIN() Function:

The MAX() function returns the largest value of the selected column.

Syntax:
SELECT MAX(column_name) FROM table_name;

The MIN() function returns the smallest value of the selected column.

Syntax:
SELECT MIN(column_name) FROM table_name;

Essential of Information Technology


K. L. E. Society's
B. V. Bhoomaraddi College of Engineering & Technology, Hubli.
Department of Information Science and Engineering

GROUP BY & Having Clause:

The GROUP BY statement is used in conjunction with the aggregate


functions to group the result-set by one or more columns.

Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name ;

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.

Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value ;

Nested Queries or Sub Queries :

What Is a Subquery?

A subquery is a SELECT statement embedded in a clause of another SQL


statement.

Syntax of nested query:

select <column(s)>
from table =>Outer Query
where <condn> operator
(select <column> =>Inner Query
from table);

Essential of Information Technology

You might also like