IT Professional Knowledge PDF
IT Professional Knowledge PDF
IT Professional Knowledge PDF
com
IT Officer
Professional
Knowledge Guide
By Ramandeep Singh and Deepak Arora
Ramandeep Singh
11/3/2016
IT Officer Professional Knowledge Guide
Table of Contents
Chapter – Networking ................................................................................................................................. 17
Network Infrastructure Devices and Topologies ........................................................................................ 17
Hub ............................................................................................................................................................. 17
Switch ......................................................................................................................................................... 17
Router ........................................................................................................................................................ 18
Differences between Hub, Switch and Router ..................................................................................... 18
Firewall ....................................................................................................................................................... 18
Network Topologies ................................................................................................................................. 19
Bus Topology ............................................................................................................................................ 19
Ring Topology ........................................................................................................................................... 19
Star Topology............................................................................................................................................ 19
Mesh Topology ......................................................................................................................................... 20
Advantages: .......................................................................................................................................... 20
Disadvantages: ..................................................................................................................................... 20
Tree Topology ............................................................................................................................................. 20
Hybrid Topology ....................................................................................................................................... 21
Advantages: .......................................................................................................................................... 21
Disadvantages: ..................................................................................................................................... 21
Peer to Peer Networks ............................................................................................................................ 21
Client Server Network .............................................................................................................................. 21
Centralized Network................................................................................................................................. 22
Distributed Network .................................................................................................................................. 22
Type of servers used in a network ......................................................................................................... 22
File Server ............................................................................................................................................. 22
Print Server ........................................................................................................................................... 22
Mail Server ............................................................................................................................................ 23
Application Server ................................................................................................................................ 23
Database Server................................................................................................................................... 23
Directory Server.................................................................................................................................... 23
Open System Interconnection (OSI) Model ......................................................................................... 23
Layer 1: The Physical Layer ................................................................................................................... 24
www.BankExamsToday.Com Page 1
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 2
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 3
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 4
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 5
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 6
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 7
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 8
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 9
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 10
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 11
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 12
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 13
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 14
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 15
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 16
IT Officer Professional Knowledge Guide
Chapter – Networking
Hub
Hub is a common connection point for devices in a network. Hubs are commonly used to
connect segments of a LAN. It contains multiple ports. When a packet arrives at one of its ports,
it transmits that packets to all the ports. Hence you may have poor response times in a network
where Hubs are used. If two network devices on the same network try to send packets at the
same time, a collision is said to occur. Hubs are considered to operate at physical layer (layer 1
of OSI model). Network switches are rapidly replacing Hubs.
Switch
A device that filters and forwards packets between LAN Segments. It receives incoming data
packets and redirects them to a particular destination. It uses hardware address (MAC) for
www.BankExamsToday.Com Page 17
IT Officer Professional Knowledge Guide
this purpose. A switch typically operates at data link layer (Layer 2) of OSI model but it can
support all types of packet protocols.
Router
It uses information from network layer (Layer 3) to direct packets through the network. Also it
uses a combination of hardware and software to route datafrom source to destination.It
segments large networks in to logical segments called subnets. We'll be dealing with subnetting
in a separate article.
Firewall
A firewall is used to protect network's data and resources from outside threats or unauthorized
access. Firewalls can be hardware of software but an ideal one is a combination of two.
www.BankExamsToday.Com Page 18
IT Officer Professional Knowledge Guide
Network Topologies
Bus Topology
A network type in which every computer and network device is connected to a single cable. It
transmits data in only one direction.
Advantages: cost effective, useful in small networks, easy to understand and expand joining 2
cables together.
Ring Topology
A network type in which each computer is connected to another computer forming a ring. Each
device will have 2 neighbors. Data transfer is sequential i.e bit by bit. Repeaters are used to
avoid packet loss and signal strength.
Advantages: Transmitting not affected by heavy traffic, cheap to install and expand.
Star Topology
All computers (nodes) are connected to a single hub (central node) through a cable. Each node
has a dedicated network to the hub. It can be set up with twisted pair, coaxial and optical fibre
cable, all.
Advantages: Easy troubleshooting (failed computer can be detected easily), Easy to set up and
modify, Fast performance.
www.BankExamsToday.Com Page 19
IT Officer Professional Knowledge Guide
Disadvantages: High cost of installation, problem in central node affects whole network,
performance based entirely on capacity of hub.
Mesh Topology
Point to point connection to other nodes and devices. Packets are transmitted only between
connected nodes. While setting up, partial mesh or full mesh can be implemented depending
upon if you want to connect all or some nodes.
Advantages: Each connection carries its own data load, easy to troubleshoot, provides security
and privacy.
Tree Topology
All nodes are connected to root node forming a hierarchy. It should have at least 3 levels to
hierarchy. It is mostly used in WANs.
www.BankExamsToday.Com Page 20
IT Officer Professional Knowledge Guide
Hybrid Topology
A network type where two or more topologies are mixed. Mostly used in WANs. Mostly used
hybrid topology is a combination of Star-Bus or Star-Ring networks.
www.BankExamsToday.Com Page 21
IT Officer Professional Knowledge Guide
Centralized Network
A network where all users connect to the central server. This server would usually store both
communications and user account information. This central server would usually be set up in
Head Office or Data Centres in a dedicated server room with multiple terminals attached to
central server. It provides better security over decentralized network due to all processing being
managed at a single location. Major disadvantage would be saving that central server from
catastrophes which might crash the entire system.
Difference between a client server and centralized network would be that in centralized network,
database having all the data is located at one place, not distributed among various databases
across different locations. A mainframe network architecture can be considered to be
centralized network
Distributed Network
The network resources are placed and managed from different geographical locations or spread
over more than one computer. Client Server architecture is an example of distributed network
only. These days most of the enterprise network are distributed networks.
File Server
File servers are used to store the documents and files centrally. An ideal file server should have
large amount of memory and storage space, fast hard disks, multiple processors, redundant
power supplies. A file server runs File Transfer Protocol (FTP) on port 20 usually for FTP data
transfer.
Print Server
It redirects print jobs from client computers to specific printers.
www.BankExamsToday.Com Page 22
IT Officer Professional Knowledge Guide
Mail Server
Main Servers are used to transmit emails using email protocols like SMTP on port 25 (simple
mail transfer protocol) which is an outgoing mail server. Incoming mail server is POP3 on port
110 (post office protocol, version 3)
Application Server
It provides the business logic for an application program.It is usually viewed as a part of 3 tier
application consisting of GUI at first layer, application server at second later and database
server at third layer. Application servers work with HTTP (Hyper text transfer protocol, port 80)
Database Server
It allows authorized clients to create, view, modify, update or delete an organization's data,
stored in common database. E.g. - IBM DB2, MySQL, Sybase, Oracle.
Directory Server
They allow the central administration and management of network users and network
resources. Directory servers provide the basic functions of network security, authentication,
authorization and accounting. E.g. - MS active directory, Open LDAP.
With this model, we can understand how software and hardware work with each other and
troubleshooting gets easier with known functions of respective layers.
www.BankExamsToday.Com Page 23
IT Officer Professional Knowledge Guide
Framing- breaks input data into frames, frame size and boundaries are also taken care of
by this layer.
Acknowledgement- from receiver to source confirming the frame received without error or
with error.
Retransmission- Frame is retransmitted if source fails to receive acknowledgement.
Sequence Numbering- to acknowledge which frame was received.
Error detection- Frames may be lost, damaged or duplicated leading to errors. Detection
is on a link to link basis.
Flow Control- Necessary for a fast transmitter to keep pace with a slower one.
Please note that network layer doesn't guarantee that packet will reach its intended destination.
www.BankExamsToday.Com Page 24
IT Officer Professional Knowledge Guide
TCP/IP
Transmission control protocol/Internet Protocol (TCP/IP) is suite of communication protocols
used to connect hosts on the internet. It uses several protocols, two main ones
being TCP and IP. Lets quickly understand the differences between OSI model and TCP/IP
model:
OSI is a generic, protocol independent standard while TCP/IP is the standard around
which Internet has developed.
TCP/IP has 4 in comparison to 7 layers of OSI.
OSI uses bottom up approach while TCP/IP uses top down approach.
TCP/IP combines the OSI Data link and Physical layer into Network access layer.
OSI is reference model while TCP/IP is an implementation of it.
Take a look at the diagram below to understand effectively.
www.BankExamsToday.Com Page 25
IT Officer Professional Knowledge Guide
The higher layer i.e TCP assembles the message into smaller packets. A header is added to the
data which includes source and destination addresses, a sequence number, acknowledgement
number and a checksum for error detection. At receiving end, TCP reassembles the packets in
the correct order and routes them up to application. It retransmits a packet if error occurs. TCP's
main job is to pack and unpack (encapsulation and decapsulation) the data and provide a
reliable transmission of error free data.
IP layer transmits the packets over a physical layer connection. IP adds its ownheader (IPv4) to
the packet, well known as IP address (32 bit addresses). This is the address assigned to device
by Internet Assigned Numbers Authority (IANA).
Encapsulation
Packing of data at each layer of TCP/IP protocol stack is known as encapsulation. When data
moves from upper to lower layers (outgoing), each layer includes some information (header) at
the start of the block which is repackaged at lower and further lower layers with their own
headers thus making data packet an encapsulated one.
Decapsulation
When data is received on destination's side, reverse process happens. Data moves up the
layers (incoming) and each layer unpacks the corresponding header and delivers the packet to
exact network application data waiting for it.
www.BankExamsToday.Com Page 26
IT Officer Professional Knowledge Guide
As you can see Host A initiates the connection request with SYN which is received and
acknowledged by Host B. A then sends acknowledgement for B's acknowledgement along with
data. Data transfer between the two begins then.
TCP connection is duplex. There is no difference between two sides once the connection is
established.
A typical IPv4 address looks like 192.168.0.2 (lowest value - 0, highest value- 255).
Class A
The range of class A addresses is from 0.0.0.0 to 127.255.255.255. The first octet is used to
identify the network and remaining three octets for identifying host (network.host.host.host).
This class is usually used for large networks. The address 127.0.0.1 is known as loopback
address (localhost) and is used for testing network testing.
Class A addressing can have 126 networks (27-2) and (224-2) hosts as here 8 bits are for
network and 24 bits are for hosts. we must also know that first IP of the network is network
www.BankExamsToday.Com Page 27
IT Officer Professional Knowledge Guide
number and last IP is reserved for broadcast IP. Hence we have decreased 2 IP addresses
above.
Class B
Class B includes addresses from 128.0.0.0 to 191.255.255.255. Here, first 16 bits are used to
identify network and remaining 16 bits for identifying hosts (network.network.host.host)
Class C
Class C includes addresses from 192.0.0.0 to 223.255..255.255. This class is used for small to
mid sized networks.
Class D
Class D includes addresses from 224.0.0.0 to 239.255.255.255. These are known as multicast
addresses. In multicasting, data is not destined for a particular host that is why no need to
extract host address from the IP address.
Class E
This class includes addresses from 240.0.0.0 to 255.255.255.255. These addresses are
reserved for future and experimental use and are largely not used.
www.BankExamsToday.Com Page 28
IT Officer Professional Knowledge Guide
Subnetting
Subnetting is used to divide a single physical network into more than smaller logical
subnetworks (Subnets). It allows more efficient utilization of the addresses. As we know an ip
address contains a network part and a host part. In subnetting, host bits are borrowed by
network bits to represent the sub networks inside a network. Class A,B and C have default
subnet masks as follows:
Example
Apply subnet mask 255.255.0.0 to IP 10.0.0.0 (A class). The 255.255.0.0 borrows borrows a
portion of host space of A and applies to network space thereby splitting one large network into
256 subnets from 10.0.0.0 to 10.255.0.0. Each subnetwork then will have 16 bits for host
addresses instead of 24 bits which is default for A class addresses.
Lets consider a case where we have a class C network 192.203.17.0. We are required to divide
it into 3 subnets for 3 diff departments of an office with 110, 45 and 50 hosts respectively.
We'll use the mask 255.255.255.128 to divide it into 2 subnets with 128 hosts each.
192.203.17.0 (.0 to .127) - 110 hosts for Dept 1 will be handled with this.
www.BankExamsToday.Com Page 29
IT Officer Professional Knowledge Guide
We'll now subnet the second one using a mask of 255.255.255.192 which will have 64 hosts for
each subnet of 2nd subnet.
Routing Algorithms
Bellman-Ford Algorithm
In this algorithm, routers know about their neighbors and their costs to different subnets that
they have to reach.
Dijkstra's Algorithm
In this algorithm, all the routers in a network have knowledge of complete network. This is also
called link state algorithm.
www.BankExamsToday.Com Page 30
IT Officer Professional Knowledge Guide
What is a Firewall?
A firewall is a device designed to control the flow of traffic into and out-of a network. In
general, firewalls are installed to prevent attacks. It disrupts free communication between a
trusted and un-
trusted network in order to mange the information flow and restrict unwarranted dangerous
access.
Hardware firewall is a physical device between internet and your computer while Software
firewall is installed as a program on computer.
Types of Firewalls
Packet Filtering Firewall
It applies a set of rules to each incoming packet and then forwards/discards(two default
policies) the packet. It filters packets going in both directions. The packet filter is typically set
up as a list of rules based on matches to fields in IP or TCP header. Some of the attacks that
can be made on packet filtering routers are: IP address spoofing, Source Routing attacks,
Tiny Fragment attacks.
www.BankExamsToday.Com Page 31
IT Officer Professional Knowledge Guide
In this, when a client establishes connection with the destination service, it connects to an
application gateway. It is also called a proxy server. The proxy then establishes the connection
with destination behind the firewall and acts on behalf of client, making all packet forwarding
decisions. It acts as a relay of application level traffic. Also, it needs separate proxies for
each service- SMTP, DNS and other custom services.
Advantages: Higher security than packet filters, Easy to log and audit all incoming traffic.
Disadvantages: Requires great memory and processor resources.
This firewall works at session layer of OSI model. Traffic is allowed only if a session request is
legitimate. It sets up two TCP connections. The gateway typically relays TCP segments from
one connection to other without examining the contents and security function determines
whether to allow it further or not. A proxy server as explained above is a security barrier
between internal and external computers while a circuit level gateway is a virtual circuit
between proxy server and internal hosts.
Advantages: Hides private network data, doesn't need a separate proxy server for each
www.BankExamsToday.Com Page 32
IT Officer Professional Knowledge Guide
Static NAT
It has one to one mapping between private and public addresses i.e one public IP for every
private IPs in private network. The only benefit is that it allows a server inside private network to
be reachable over internet through one to one translation.
Dynamic NAT
It has many to many mapping between private and public addresses. It maps an unregistered
IP address to a registered one from a pool of registered IP addresses in NAT router. Addresses
are assigned dynamically.
Suppose an internal host A tries to connect to a web server outside. NAT enabled router will
save private IP and source port from A's packet to an Address Translation Table (ATT). It then
www.BankExamsToday.Com Page 33
IT Officer Professional Knowledge Guide
replaces private IP with the router's IP address, generates a new port for new connection and
forwards the packet over internet. Now when the return packet from web server reaches the
router, it uses destination port to search ATT, obtains the private address and port numbers
mapped to it and sends it to original sender.
Pooling of IP addresses
Suppose a corporate network has many hosts but only a small number of public IP addresses. It
uses private address space for hosts and when a host send an IP datagram to a host in public
internet, NAT device picks up a public IP from the pool and binds it to private address of the
host.
www.BankExamsToday.Com Page 34
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 35
IT Officer Professional Knowledge Guide
One more important thing to learn is that NAT is not a proxy server. NAT is transparent to both
source and destination hosts but proxy server is not transparent. Also NAT is a layer 3 (network)
protocol while proxy server works at layer 4 (transport) or higher.
1. CPU
Central processing unit is that core element of a computer system that carries out instructions of
a computer program by performing basic arithmetic, logical, control and I/O operations.
2. Memory
Every computer has 2 types of main memories - RAM and ROM
Random Access Memory can be read and written to anytime the CPU instructs it. Contents of
RAM are erased when the computer is turned off whereas Read Only Memory is pre-loaded
with data and software that never changes. ROM is typically used to store computer's initial
start up instructions.
3. I/O unit
I/P refers to the communication between a computer and outer world. Input are signals/data
received by system and Output are signals sent by it. Peripheral devices provide input/output to
the system. Peripherals include input devices like keyboard, mouse and output devices like
www.BankExamsToday.Com Page 36
IT Officer Professional Knowledge Guide
display screen or printer. Hard disk and optical disk devices act as both input and output
devices.
Microprocessor
It is a programmable integrated device which has the capacity of computing & decision making.
It communicates with the system in binary numbers 0 &1. Every microprocessor has fixed set
of instruction in the form of binary patterns known as machine language. Various components of
a microprocessor are described below:
Control Unit
Its the circuit that controls the flow of information through processor and coordinates the
activities of other units within it. With a regular processor, control unit performs tasks of fetching,
decoding, managing execution and storing results.
Register Sets
Register sets temporarily store data and program codes until they are sent to ALU or control
section. More registers per cpu results in programming tasks easily. Registers are measured by
no of bits i.e 8 bit, 16 bit, 32 bit.
Accumulator
Its a register in which intermediate arithmetic and logical results are stored. Initially set to zero,
each number after operation is added into it and finally results are sent to main memory or to
another register.
www.BankExamsToday.Com Page 37
IT Officer Professional Knowledge Guide
Data Bus
A subsystem which transfer the data between different components of a computer. Its bi
directional in nature and depending upon the microprocessor it can handle 8 bit or 16 bit data.
Address Bus
It is unidirectional in nature over which microprocessor sends an address code to the memory
or I/O. The more bits in an address bus enables microprocessor to access more locations. A 16
bit address bus is capable of handling 64K addresses.
Control Bus
Control bus is used by microprocessor to send out or receive timing and controlsignals in
order to coordinate and regulate its operation and to communicate with other devices.
Microprocessor Clock
Its the speed at which microprocessor executes instructions, also called clock rate. Clock rate
is expressed in MHz or GHz.
www.BankExamsToday.Com Page 38
IT Officer Professional Knowledge Guide
Multiplexing
Its a technique by which different analog and digital streams of transmission can be
simultaneously processed over a shared link. All medias of communication i.e air, physical
media and light are capable of multiplexing.
A device called multiplexer divides the physical channel when multiple senders try to send over
a single medium and allocated one to each. On the other side, de-multiplexer receives,
identifies and sends to different receivers.
www.BankExamsToday.Com Page 39
IT Officer Professional Knowledge Guide
next time slot simultaneously. Imagine crudely that Red Fm can play from 9:00 to 10:00 only
and 10:00 to 11:00 is fixed for Radio Mirchi.
Wireless Transmission
Wireless communication doesn't involve any physical link between two or more devices. Signals
are spread in the air, received and interpreted by antennas. An antenna connected to circuit of a
www.BankExamsToday.Com Page 40
IT Officer Professional Knowledge Guide
computer converts digital data into wireless signals and on receiving end, another antenna will
reconvert it back to digital data.
1. Radio Transmission
Important points regarding Radio waves are as follows:
Can penetrate through walls and structures due to high wavelength and low frequency.
Sub divided into 6 bands, out of which VLF (very low freq), LF and MF can travel on
ground along the curvature of earth while HF and VHF bands use Ionosphere for use i.e
they are refracted back to earth.
wavelength range: 1 mm - 1,00,000 km, frequency range: 3 Hz to 300 GHz
2. Microwave Transmission
Travel in straight line and receiver must be strictly in line of sight.
Can't penetrate wall like obstacles due to high frequency
Depends upon weather conditions
wavelength range: 1 mm - 1 m, frequency range: 300 MHz - 300 GHz
3. Infrared Transmission
Lie between visible light spectrum and microwaves.
Used for very short range communication such as TV and Remote.
Travel in straight line and can't pass wall like obstacles
wavelength range: 700nm - 1 mm, frequency range: 300 GHz - 430 THz
www.BankExamsToday.Com Page 41
IT Officer Professional Knowledge Guide
4. Light Transmission
travels strictly in straight line e.g. LASER
Can't penetrate obstacles like walls or rain. Also distorted by wind or temperature.
LASER beam is generally 1 mm wide, difficult to tap hence comparatively safe for data
transmission.
What is Iptable?
Iptable is the building block of a framework inside the Linux Kernel. It is represented by a
generic table structure for definition of rulesets. Each rule with an Iptable consists of a number
of classifiers (iptable matches) and one connection action (iptable target). The security functions
that can be achieved with Iptables are as follows:
Build internet firewalls based on stateless and stateful packet filtering- In stateful filtering
ports are opened and closed as clients use the internet in such a way that it mostly
presents a blank wall to attackers.
NAT and masquerading for sharing internet access
NAT to implement transparent proxies - transparent proxies are intermediary systems that
sit between user and content providers. Upon request by a user, they perform functions
like caching, redirection and authentication.
Packet manipulation like altering the bits of IP header.
Provides for improved logging options by using user defined prefixes
Iptable Tables
1. Filter table
Its the default table i.e if you haven't defined your own one, you will be using the default. It has
following built in chains:
INPUT chain - for packets coming to local server.
OUTPUT chain - for packets going out of the server.
FORWARD chain - packets for another interface i.e packets routed through the server.
2. NAT table
www.BankExamsToday.Com Page 42
IT Officer Professional Knowledge Guide
3. Mangle Table
It is for specialized packet alteration. This alters QOS bits in TCP header. Quality of service
(QOS) is a group of components that can differentiate traffic flows so that high priority traffic
receives preferential treatment. Mangle table has following built in chains:
PREROUTING chain
OUTPUT chain
FORWARD chain
INPUT chain
POSTROUTING chain
4. Raw table
Iptable Rules
Rules contain a criteria and a target. If criteria is matched, it executes values mentioned in the
target and if criteria is not matched, it moves to the next rule.
Target Values
ACCEPT - firewall will accept the packet
DROP - drop the packet
QUEUE - pass the packet to user space
www.BankExamsToday.Com Page 43
IT Officer Professional Knowledge Guide
RETURN - stop executing next set of rules in current chain and control is returned to
calling chain.
Let's see some commands we use for Iptables:
Cryptography
Its a technique to encrypt the plain text data into cipher text using keys which makes it difficult to
understand and interpret. Decryption is the reverse of encryption. There are several
cryptographic algorithms available as described below:
Secret Key
Public Key
Message Digest
www.BankExamsToday.Com Page 44
IT Officer Professional Knowledge Guide
E.g.- Data Encryption Standard (DES), Advanced Encryption Standard (AES), International
data encryption algorithm (IDEA).
E.g.- RSA algorithm: Based on the principles of number theory, it involves 4 steps - key
generation, key distribution, encryption, decryption. This algorithm was invented in 1978 by
Rivest, Shamir and Adleman. DES is about 100 times faster than RSA.
3. Message Digest
In this method, actual data is not sent, instead a hash value (128 bits) is calculated and sent.
Receiver computes its own hash value and compare with the one it receives. If both hash
www.BankExamsToday.Com Page 45
IT Officer Professional Knowledge Guide
values match, message is accepted otherwise rejected. This method was designed by Ronald
Rivest in 1991.
E.g. - MD5 hashing - mostly used in authentication where user password is cross checked with
the one saved on server.
SSL handshake verifies the server and allows client and server to agree on anencryption
set before any data is send out.
Compression and decompression are functions of this record layer. Encryption of data occurs
after compression.
Alert protocol explains the severity of the message and a description (e.g. 'fatal' - then
terminate immediately).
Function of cipher spec protocol is to notify the other party to use a new cipher suite.
Some other sections of this topic will be covered in next article.
www.BankExamsToday.Com Page 46
IT Officer Professional Knowledge Guide
Telnet Protocol
It starts a remote session on another machine. Login and password are usually required to
gain entry to the remote system. Telnet is used mostly for accessing shared devices like Printer
etc on a remote host or for using software that are only available on a single secure system. By
default, connection is established over port 23.
FTP
File Transfer Protocol allows a person to transfer files between two computers. At the back
end, two connections are established. One control connection overport 21 which remains
throughout and other for file transfer, over port 22. Every time a new connection will be
established for transfer. Typical ftp commands are as follows:
ftp <ip address> - est. connection with ftp server
put, mput - send one/more files
get, mget - receive one/more files
hash - indicates progress of file transfer
prompt - prompts user before actual transfer of each file
bin, asc - selects binary/ascii mode of transfer
exit - terminates connection with ftp server
SMTP
Simple Mail Transfer Protocol is used when email is delivered from a mail agent like outlook
or gmail application to mail server . It send messages in simple text only. It uses port 25.
POP3
Post office Protocol allows a mail agent to download email from mail server. Two modes are
used in this - 1) Delete mode - read emails and delete them. 2) Keep mode - emails remain in
the mailbox. It normally uses port 110.
IMAP
Internet Message Access Protocol is similar in functions to that of POP3 but with some extra
features. A user can check email header before downloading, a user can search contents of
email for a specific string prior to downloading, a user can create, delete, or rename mailboxes
on mail server, a hierarchy of mailboxes can also be created. It requires more disk space and
more CPU resources than POP3 as all emails are stored on server. It normally uses port 143.
www.BankExamsToday.Com Page 47
IT Officer Professional Knowledge Guide
HTTP
Hyper Text Transfer Protocol is a protocol using which web browsers interact with the web
servers. Client opens socket connection to HTTP server on port 80and sends HTTP requests to
server. Server sends back response and closes the connection afterwards. Common status
codes for HTTP are: 401 - unauthorized, 403 - forbidden, 404 - Not Found, 500- Internal Server
Error.
UDP
User Datagram Protocol is used for sending packets that doesn't guarantee delivery. It also
doesn't guarantee against lost packets, duplicate packets or our of order packets. It is used for
transfer of bulk data where sequencing of packets doesn't matter much. It has a formal packet
structure though with details like source, destination and size of the packet.
LDAP
Lightweight Directory Access Protocol is an internet protocol that email and other programs
use to look up information from a server. It is mostly used by medium to large size organizations
for example if you want to look up contact info or email ids of persons in your organizations,
LDAP server comes into picture which fetches you all that information. It uses port 389 by
default.
www.BankExamsToday.Com Page 48
IT Officer Professional Knowledge Guide
What is a socket?
The socket is a BSD method for accomplishing IPC. It allows one process to speak to another
and works very similar to files i.e read/write on a socket is similar to that of files. A socket is
created using the socket( ) system call.
Types of Sockets
Two most common types are:
SOCK_STREAM: Stream sockets, which provide reliable two way connection oriented
communication streams. It uses TCP.
SOCK_DGRAM: Datagram sockets, which provide connectionless, unreliable service,
used for packet by packet transfer of information. It uses User Datagram Protocol (UDP)
www.BankExamsToday.Com Page 49
IT Officer Professional Knowledge Guide
5. accept( )- returns a new socket file descriptor for every single connection, -1 on error
Syntax:
#include <sys/socket.h>
int accept (int sockfd, void *addr, int *addrlen);
addr- pointer to a local structure sockaddr_in, here information about incoming connection will
be stored
addrlen- should be set to sizeof(struct sockaddr_in) before accept( ) is called.
Other systems calls along with rest of the topic will be covered in next article.
7. sendto( ) & recvfrom( )- transmit and receive data packets over unconnected datagram
sockets, -1 on error.
Syntax:
www.BankExamsToday.Com Page 50
IT Officer Professional Knowledge Guide
int sendto (int sockfd, char *buffer, int buf_len, int flags, const struct sockaddr *to, int tolen);
int recvfrom (int sockfd, char *buffer, int buf_len, int flags, struct sockaddr *from, int *fromlen);
to- address of the target
tolen- size of the structure pointed to by to
from- socket address structure from which data is received
fromlen- size of from in bytes
9. getpeername( ) - this will tell you who is at the other end of a connection stream socket
Syntax:
#include <sys/socket.h>
int getpeername (int sockfd, struct sockaddr *addr, int *addrlen)
addr - pointer to a structure that holds information about other side of connection
addrlen - pointer to an int that is initialized to sizeof(struct sockaddr)
10. gethostname( ) - returns name of the computer on which your program is running
Syntax:
#include <unistd.h> //header for standard symbolic constants and types
int gethostname (char *hostname, size_t size);
hostname- pointer to an array of chars which contains the hostname
size - length of hostname array in bytes
11. gethostbyname( ) - returns the IP address of a host given its name, invokes the DNS
Syntax:
#include <netdb.h> //header for network database operations
struct hostent *gethostbyname (const char *name); //returns a pointer to struct hostend
www.BankExamsToday.Com Page 51
IT Officer Professional Knowledge Guide
MCQs
www.BankExamsToday.Com Page 52
IT Officer Professional Knowledge Guide
a) UDP
b) TCP
c) SCTP
d) none of the above
www.BankExamsToday.Com Page 53
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 54
IT Officer Professional Knowledge Guide
What is a Firewall?
A firewall is a device designed to control the flow of traffic into and out-of a network. In
general, firewalls are installed to prevent attacks. It disrupts free communication between a
trusted and un-
trusted network in order to mange the information flow and restrict unwarranted dangerous
access.
Hardware firewall is a physical device between internet and your computer while Software
firewall is installed as a program on computer.
Types of Firewalls
Packet Filtering Firewall
It applies a set of rules to each incoming packet and then forwards/discards(two default
policies) the packet. It filters packets going in both directions. The packet filter is typically set
up as a list of rules based on matches to fields in IP or TCP header. Some of the attacks that
can be made on packet filtering routers are: IP address spoofing, Source Routing attacks,
www.BankExamsToday.Com Page 55
IT Officer Professional Knowledge Guide
In this, when a client establishes connection with the destination service, it connects to an
application gateway. It is also called a proxy server. The proxy then establishes the connection
with destination behind the firewall and acts on behalf of client, making all packet forwarding
decisions. It acts as a relay of application level traffic. Also, it needs separate proxies for
each service- SMTP, DNS and other custom services.
Advantages: Higher security than packet filters, Easy to log and audit all incoming traffic.
Disadvantages: Requires great memory and processor resources.
www.BankExamsToday.Com Page 56
IT Officer Professional Knowledge Guide
Advantages: Hides private network data, doesn't need a separate proxy server for each
application, simple to implement.
Disadvantages: Doesn't filter individual packets, attacker may take advantage after
establishing a connection.
www.BankExamsToday.Com Page 57
IT Officer Professional Knowledge Guide
DNS uses distributed database as there is one primary server for a domain and typically
a number of secondary servers containing replicated databases.
The organization that owns the domain name is responsible for running a DNS server that
provides for the mapping.
A DNS client is called a resolver.
Most Unix workstations have the file /etc/resolv.conf that contains local domain and
addresses of DNS servers for that domain.
nslookup, usually available on unix workstations, is an interactive resolver that allows the
user to communicate directly with a DNS server. (hit nslookup followed by yahoo.com for a
feel of it)
If a server is asked to provide the mapping for a host outside its domain, it finds the
nameserver for target domain and asks it to provide the translation.
Common DNS library functions - 'gethostbyname' & 'gethostbyaddr'
Uses port number 53
A DNS tree looks like:
www.BankExamsToday.Com Page 58
IT Officer Professional Knowledge Guide
Static NAT
It has one to one mapping between private and public addresses i.e one public IP for every
private IPs in private network. The only benefit is that it allows a server inside private network to
be reachable over internet through one to one translation.
Dynamic NAT
It has many to many mapping between private and public addresses. It maps an unregistered
IP address to a registered one from a pool of registered IP addresses in NAT router. Addresses
are assigned dynamically.
www.BankExamsToday.Com Page 59
IT Officer Professional Knowledge Guide
Suppose an internal host A tries to connect to a web server outside. NAT enabled router will
save private IP and source port from A's packet to an Address Translation Table (ATT). It then
replaces private IP with the router's IP address, generates a new port for new connection and
forwards the packet over internet. Now when the return packet from web server reaches the
router, it uses destination port to search ATT, obtains the private address and port numbers
mapped to it and sends it to original sender.
Pooling of IP addresses
Suppose a corporate network has many hosts but only a small number of public IP addresses. It
uses private address space for hosts and when a host send an IP datagram to a host in public
internet, NAT device picks up a public IP from the pool and binds it to private address of the
host.
www.BankExamsToday.Com Page 60
IT Officer Professional Knowledge Guide
Migration to a new service provider merely requires an update of NAT device and this migration
won't be noticeable to hosts on the network.
www.BankExamsToday.Com Page 61
IT Officer Professional Knowledge Guide
One more important thing to learn is that NAT is not a proxy server. NAT is transparent to both
source and destination hosts but proxy server is not transparent. Also NAT is a layer 3 (network)
protocol while proxy server works at layer 4 (transport) or higher.
What is Database?
A database is a collection of information that is organized so that it can easily be accessed,
managed and updated.
Advantages of a DBMS
1. Controls Data Redundancy: All of the data is integrated into a single centralized file and
no duplicates are created.
2. Data Sharing: Database administrator upon granting access allows for sharing of data
across different platforms and different users.
3. Data consistency: As a data item appears only once, update has to be done once only
and updated value is immediately available for use.
www.BankExamsToday.Com Page 62
IT Officer Professional Knowledge Guide
4. Integration of Data: In DBMS, data is stored in tabular form and various relationships can
be created among tables. This makes it easy to retrieve and update data.
5. Data Security: The access to critical information can be restricted and access privileges
are required for updating/manipulating important information. E.g.-access to financial data
is restricted providing for security of data.
6. Backup and Recovery: It has subsystems which deal with back up and recovery in case
of hardware/software failure or in case of a natural calamity which endangers the data in
any way.
7. Concurrent Access: It provides for concurrent access to multiple users at one time
making it more efficient for business applications.
Components of DBMS
A database system consists of 4 components usually:
Data
Hardware
Software
Users
1. Data: It is the most important component of a database which acts like a bridge between
hardware and software. Different types of data are- User data (actual/workable data stored in
tables), Metadata ( data about data i.e no of tables, no of fields), application metadata (structure
and format of queries)
2. Hardware: Storage devices on which data is stored with i/o operations (hard disks, optical
disks, magnetic tapes etc)
3. Software: It acts a bridge between user and database. It interacts with both user and
database and acts a medium for data exchange. For performing various operations on the data,
we use query languages like SQL etc.
4. Users: They are the ones who need information from a database to carry out their primary
business responsibilities. Various types of users are: Database administrators, Database
designers, End users, Application Programmers.
Levels of Abstraction
1. Physical Level
It describes how a record (e.g. customer) is stored in the database.
2. Logical Level
It describes the data stored in database and the relationships among themselves. Lets look at
the description of customer data below:
www.BankExamsToday.Com Page 63
IT Officer Professional Knowledge Guide
cust_id: int;
cust_name: string;
cust city: string;
3. View Level
At this level, application programs hide details of data types. Views can also hide information
such as employee salary for security purposes.
ER Model
ER model is a data model for describing the data or information, visually, as a collection of
entities and relationships. It was developed by Peter Chen in 1976.The symbols and notations
used in ER model are as follows:
Components of ER Diagram
E-R Diagram has 3 main components:
1. Entity
Entity is a thing in the real world with an independent existence, and entity set is a collection of
all entities of particular entity type in the database. E.g. Employees of a company can be
www.BankExamsToday.Com Page 64
IT Officer Professional Knowledge Guide
defined as entities and employees have same attributes can be put under an entity set. All
entities have some attributes that give them identity.
2. Attribute
An attribute describes a property or characteristic of an entity. E.g. Name, age , address can
be attributes of an employee. Types of attributes are discussed below:
Simple attribute- Its an atomic value which can not be divided further. E.g employee's
phone number.
Key Attribute - it represents main characteristic of an entity. It is used to represent
primary key.
Composite Attribute - An attribute can have its own attributes as well. E.g. Address
attribute is usually composed of city, state and zip code attributes.
Derived attribute - These attributes don't exist in the physical database and their values
are derived from other
3. Relationship
One to One: Let's say one student can enroll only in one course and one course will only
have one student. This type of relationship is rarely seen in real world.
One to Many - As per this relationship, one student can enroll to many courses but one
course will have one student only. Example might sound weird but this is for explanation
purpose.
www.BankExamsToday.Com Page 65
IT Officer Professional Knowledge Guide
Many to One - As per this, a student can enroll for one course only but a course can have
many students.
Many to Many - As per this, many students can enroll for more than one course.
b) Recursive Relationship: is when an entity is related with itself. E.g. each employee has a
manager in a organization which is further managed by a manager. Thus an employee
manages other
employees and is managed by some employee as well.
www.BankExamsToday.Com Page 66
IT Officer Professional Knowledge Guide
Keys
Key is an attribute or a collection of attributes that uniquely identifies an entity. Various types of
keys are discussed below:
Super key - a set of attributes ( one or more ) that collectively identifies an entity
Composite key- a key requiring more than one attribute
Candidate key - a minimal super key is called candidate key. An entity set may have more
than one candidate key.
Primary key - the candidate key chosen to be used for identifying entities and accessing
records. Key by default means primary key.
Alternate key - a candidate key not used for primary key
Secondary key - attribute or set of attributes commonly used for accessing records but
not necessarily unique
Foreign key - is a tern used in relational databases (not ER model) for an attribute that is
primary key of another table and is used to establish a relationship with that table
Relational Model
Some important points to note here about attributes in a relation are as follows:
2. The set of allowed values for each attribute is called the domain of the attribute
6. A relation is a set of n tuples (a1, a2, a3...) where each attribute belongs to corresponding
domain.
Relational Algebra
The basic operators used in relational algebra are as follows:
www.BankExamsToday.Com Page 67
IT Officer Professional Knowledge Guide
1. SELECT
It is used to obtain a subset of the tuples of a relation that satisfy a select condition. The
SELECT operator is denoted by symbol σ (sigma). The syntax for SELECT statement would be
as follows:
σ<Selection condition>(R) ( R would represent the relation or table from which selection is made )
Example:
2. PROJECT
It is used to select a subset of attributes of a relation by specifying the namesof required
attributes. The symbol used for PROJECT operator is ∏ (pie). The syntax is as follows:
∏<attribute list>(R)
Example:
3. UNION
UNION of two relations r and s designated as r s is a relation that includes all the tuples that
are either in r or in s or in both r and s. Duplicate tuples are eliminated.
4. INTERSECTION
INTERSECTION of two relations r and s denoted by r both r
and s
www.BankExamsToday.Com Page 68
IT Officer Professional Knowledge Guide
5. DIFFERENCE
DIFFERENCE of two relation r and s denoted by r - s, includes all tuples that are in r but not in
s
6. CARTESIAN PRODUCT
It is also referred to as cross product or cross join denoted by r x s, creates a relation that has
all attributes of r and s i.e allowing all combinations of tuples from r and s
www.BankExamsToday.Com Page 69
IT Officer Professional Knowledge Guide
7. JOIN
It is used to combine related tuples from two relations. It can be further studies in three forms:
a) Inner Join
It joins two tables according to matching of a certain criteria using a comparison operator.
SQL representation is as follows:
JOIN tab2
ON tab1.col_name = tab2.col_name
b) Equi Join
It joins two tables based on matching of certain criteria using equal sign (=) as the comparison
operator in WHERE clause.
SELECT col_name
c) Outer Join
It joins all rows from both tables which satisfy the join condition and which do not satisfy the join
condition thereby avoiding loss of information. It is of 3 types further:
www.BankExamsToday.Com Page 70
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 71
IT Officer Professional Knowledge Guide
The figures have been taken from the DBMS book by Korth, for a better understanding.
Normalization
Normalization is a refinement process where it helps in removing anomalies in insert, update
and delete operations. It is also called bottom up approach, because this technique requires
full knowledge of every participating attribute and its dependencies on key attributes. If you try
to add new attributes after normalization is done, it may change the normal form of database
design itself. It is mainly used for two purposes:
www.BankExamsToday.Com Page 72
IT Officer Professional Knowledge Guide
Now, for it to be in 1NF, any row must not have a column with more than one values in it. Such
data should be separated into multiple rows. So in 1NF, it will look like:
Look at the table in 1NF above, there are 2 rows for Adam to show different subjects he has
opted for. This is inefficient use of space. Also the candidate key is {student, subject} but age
depends only on student which doesn't follow 2NF rules. Therefore to make it in 2NF, its better
to split the subjects into a different table and match it up using student's name as foreign key.
Now, the new student table will look like:
www.BankExamsToday.Com Page 73
IT Officer Professional Knowledge Guide
Candidate key here is {student, subject}. This way the tables above would never suffer from
update anomalies.
student_id is primary key here but street, city, state depends on zip. This dependency between
zip and other fields is called transitive dependency. To make it in 3NF, we need to move street,
city and state into a new table with zip as primary key. Therefore, the new table will look like:
Zip table
Logically, for any course C, database should list all teachers anyone of whom can be the course
instructor and list of books to be followed for teaching.
www.BankExamsToday.Com Page 74
IT Officer Professional Knowledge Guide
But if Tom is new teacher who teaches database, then we might face an insertion anomaly i.e
we will need to insert two tuples (database, Tom, DB concepts) and (database, Tom, Ullman).
Therefore, its better to break classes into 2 tables:
SQL Commands
Basic SQL commands cane be classified in following groups based on their nature:
www.BankExamsToday.Com Page 75
IT Officer Professional Knowledge Guide
Clauses in SQL
1. WHERE clause
It is used to specify a condition while fetching data from single table or multiple tables. WHERE
clause is used with SELECT, UPDATE & DELETE statements.
Basic Syntax:
Condition can be specified using comparison or logical operators like >, <, =, NOT, LIKE etc.
2. LIKE clause
It is used to compare a value to similar values using wildcard operators. There are 2 wildcards
used in conjunction with LIKE operator:
www.BankExamsToday.Com Page 76
IT Officer Professional Knowledge Guide
3. TOP clause
It is used to fetch TOP N numbers or X percents records from a table. All the databases do not
support TOP clause. MySQL uses LIMIT to fetch limited number of records and Oracle uses
ROWNUM to produces similar results.
Basic Syntax:
SELECT TOP number|percent col_name
FROM table_name
WHERE <condition>
e.g. SELECT TOP 3 * FROM employee - this would fetch first 3 rows with all columns from
employee table
4. ORDER BY Clause
It is used to sort the data in ascending or descending order, based on one or more columns.
Usually ascending order is chosen by default.
Basic Syntax:
SELECT * from Employee
ORDER BY salary DESC;
5. GROUP BY Clause
It is used in combination with SELECT statement to arrange identical data into groups. It follows
the WHERE clause and precedes the ORDER BY clause.
Basic Syntax:
SELECT col_1 col_2
FROM table_name
WHERE <condition>
GROUP BY col_1 col_2
ORDER BY col_1
6. HAVING Clause
It enables you to specify conditions that filter which group results appear in final results.
WHERE clause places conditions on selected columns but HAVING clause places conditions on
groups created by GROUP BY clause.
Basic Syntax:
SELECT col1, col2
FROM tab1, tab2
WHERE <conditions>
GROUP BY col1, col2
www.BankExamsToday.Com Page 77
IT Officer Professional Knowledge Guide
HAVING <conditions>
ORDER BY col1, col2
SQL Transactions
Transactions are sequences of work accomplished in logical order whether manually or by a
database automatically.
All the transactions should maintain following properties/achieve following ends after occurring:
Atomicity
Consistency
Isolation
Durability
Following transaction control statements are used in SQL:
1. COMMIT command
It saves all changes to the database since the last COMMIT or ROLLBACK command.
syntax - COMMIT;
2. ROLLBACK command
It is used to undo transactions that have not already been saved to the database.
syntax - ROLLBACK;
3. SAVEPOINT command
It is a point in transaction control when you can roll the transaction back to a certain point
without rolling back the entire transaction
syntax - SAVEPOINT savepoint_name;
4. RELEASE_SAVEPOINT command
It removes a savepoint that you have created.
syntax - RELEASE SAVEPOINT savepoint_name;
www.BankExamsToday.Com Page 78
IT Officer Professional Knowledge Guide
Difference between both is that domains can have constraints, such as NOT NULL, on them.
We'll discuss constraints in next section.
Integrity Constraints
Integrity constraints protect against accidental damage to database, by ensuring the authorized
changes to database do not result in loss of data consistency. E.g - Employee must have NOT
NULL phone number, Number of leaves shouldn't be more than 20 etc.
Types of constraints
1. NOT NULL - indicates that a column can not store NULL value
Emp_name char(15) NOT NULL
2. UNIQUE - ensures that each row for a column must have a unique value
emp_id int NOT NULL UNIQUE
3. CHECK - ensures that value in a column meets a specific condition like limit the value range
etc
emp id int NOT NULL,
CHECK (emp_id >999)
4. DEFAULT - It is used to insert a default value into a column. It will be added to all new
records, if no other value is specified.
emp_id int NOT NULL,
city varchar(255) DEFAULT 'Mumbai'
5. Referential Integrity - It ensures that value that appears in one relation for a given set of
attributes also appears for a certain set of attributes in another relation. It is achieved through
primary key and unique key.
www.BankExamsToday.Com Page 79
IT Officer Professional Knowledge Guide
SQL Functions
Aggregate Functions
SQL aggregate functions return a single value calculated from values in the column. Some
important aggregate functions are as follows:
Scalar Functions
These return a single value based on input value. Important scalar functions are as follows:
www.BankExamsToday.Com Page 80
IT Officer Professional Knowledge Guide
can be found on almost all modern computing devices- from mobile phones to video game
consoles to web servers to supercomputers. E.g. MS DOS, UNIX, Windows 7, Windows 10,
Ubuntu etc
5. File management
OS handles the organization and tracking of files and directories. It keeps track of user's activity
as far as file creation, updation, deletion or movement is concerned. Two main types of file
systems are:
File Allocation Table (FAT/FAT32) - It uses a file allocation table maintained by OS on a
hard disk that provides a map of clusters (logical units of storage) that a file has been
stored in.
New Technology file system (NTFS) - File system introduced by Microsoft. It also allows
permissions (read, write, execute) to be set for individual files and directories.
www.BankExamsToday.Com Page 81
IT Officer Professional Knowledge Guide
3. Multi user OS
It allows many different users to take advantage of computer's resources simultaneously. OS
must allocate resources in a way that a problem with one user doesn't affect the entire
community of users. Main purpose is to maximize the resources. E.g. Mainframe systems.
4. Real time OS
It controls the environment as it has a data processing system. Time taken by system to
respond to an input and display the result is called a response time. It uses an advanced
algorithm for scheduling.
5. Time sharing OS
It enables many people located at various terminals, to use the system, at a particular time. In
other words, its a logical extension of multiprogramming. The main purpose is to minimize
response time.
6. Distributed OS
Distributed systems use a number of central processors to serve multiple real time applications
and different users. Data processing jobs are distributed among processors.
7. Network OS
This OS runs on a server. It is responsible for manaing data, users, groups, security,
applications and other networking functions. It allows shared file and printer access among
multiple computers in a network. E.g. Microsoft Windows Server 2003/2008, oivell NetWare.
8. Embedded OS
Its a specialized OS for use in computers which are built into larger systems. It is part of
different kind of machine. E.g. - Computers in cars, traffic lights, GPS navigation system,
elevators, ATMs etc. As compared to a general purpose OS, embedded OS has limited
functions but that single function/application is crucial to its operation.
9. Mobile OS
Its an OS specially designed to run on mobile devices such as smartphones, PDAs. E.g.-
Android, iOS etc.
www.BankExamsToday.Com Page 82
IT Officer Professional Knowledge Guide
1. Pointer - A symbol that appears on the display screen and which you move to select objects.
Text processing applications use an I-beam pointer that is shaped like capital I.
2. Pointing Device - A device such as mouse or trackball that enables you to select objects.
3. Icons - small pictures that represent commands, files or windows. By clicking on icons, you
execute commands
5. Windows - You can divide the screen into different areas and can display different
files/programs in each window.
6. Menus - Most GUIs let you execute commands by selecting a choice from menus.
Processes in OS
A program in execution is called a process. Process execution must progress in sequential
fashion. A process is an active entity and program is a passive entity. A program becomes a
process when executable file is loaded into memory. A process is represented by 'pid' in Linux.
Multiple parts of a process are as follows:
Program Code - text
Program Counter - contains address of next instruction
Stack -contains temporary data like return address and local variables
Heap - contains memory dynamically allocated during run time
Data Section - contains global variables
www.BankExamsToday.Com Page 83
IT Officer Professional Knowledge Guide
Process State
As a process executes, it changes states and at any given time, can be in any of the following
states:
New - Process is being created.
Ready - Process is waiting to be assigned to the processor.
Running - When instructions related to that process are executed by CPU
Waiting - Process is waiting for a resource to become available or for some event to
occur.
Terminated - Process has finished execution and released resources that it was using.
Diagram below will make it more clear.
Threads
A thread is a basic unit of CPU utilization, consisting of a program counter, a stack and set of
registers. It is also called a light weight process. Each thread belongs a process and can not
exist outside a process. They allow us to parallely executeapplication on shared
multiprocessors.
www.BankExamsToday.Com Page 84
IT Officer Professional Knowledge Guide
Like processes, threads share CPU and can create child threads using fork ( ) system call. All
threads can access every address in the task.
Types of Threads
1. Many to One
Basic features of this model are as follows:
www.BankExamsToday.Com Page 85
IT Officer Professional Knowledge Guide
2. One to One
Basic features are as follows:
3. Many to Many
Basic features are as follows:
Many user level threads are mapped to many kernel level threads.
If kernel system calls are blocked, it doesn't block the entire process.
Users have no restrictions on number of threads created.
www.BankExamsToday.Com Page 86
IT Officer Professional Knowledge Guide
Thread Libraries
A thread library provides an API to developer for creating and managing threads. There are 3
main thread libraries that are used across operating systems:
POSIX Pthreads
Windows threads
Java threads
2. Signal Handling
Signals in OS are used to notify a process that some event has occurred. A signal handler
processes all signals. Every signal has a default handler assigned by kernel. User defined
signals can over ride them.
3. Thread Cancellation
Threads can be terminated before they have finished in case they are not required anymore.
Two approaches are used for cancelling threads:
www.BankExamsToday.Com Page 87
IT Officer Professional Knowledge Guide
Critical Section
That part of the program where the shared memory is accessed is called critical section. This
part may not be concurrently executed by more than one process at a time. Each process must
ask permission to enter critical section with ENTRY section and then with EXIT section, comes
out of that and works with remainder section. Following code snippet shows the access of
shared memory by process:
1. Mutual Exclusion
If one process is executing in critical section, no other process is allowed entry to that.
2. Progress
If no process is currently in critical section and some processes want to enter then only those
processes which are not executing in their remainder section can participate in decision making
that which one will enter the critical section next.
3. Bounded Waiting
Once a process enters critical section, it can not enter again until a waiting process gets its turn.
Entry is managed as a queue.
Many systems even provide hardware support for implementing critical section code. They are
based on idea of locks. The algorithm for using locks looks something like as below:
www.BankExamsToday.Com Page 88
IT Officer Professional Knowledge Guide
Semaphores
A semaphore is a protected integer variable that can facilitate and restrict access to shared
resources in multi programming environment. They were invented by Edsger Djikstra. Two
most common kinds of semaphores are Binary and Counting semaphores.
Starvation is a situation where a process may never be removed from semaphore queue in
which it is suspended.
CPU Scheduling
CPU scheduler selects from among the processes in ready queue which are to be allocated
CPU next. CPU scheduling decision takes places when a process moves through following
states:
Running to Waiting
Running to Ready
Waiting to Ready
Termination
Scheduling for all of above transitions is non preemptive in nature. All of rest are preemptive in
nature. Non Preemptive scheduling is when CPU is given to a process, it can not be taken
away unless process finishes execution where as preemptive scheduling is when a high
priority task is allocated the CPU while interrupting the currently running process. It is based on
idea that highest priority process should always be the process that is currently utilized.
www.BankExamsToday.Com Page 89
IT Officer Professional Knowledge Guide
Dispatcher
Dispatcher gives control of CPU to process selected by the scheduler. It involves switching
context, switching to user mode and jumping to proper location to restart the
program. Dispatch latency is defined as the time it takes for dispatcher to stop one process
and start another.
Scheduling Algorithms
The algorithms used mostly in practice are discussed as follows:
www.BankExamsToday.Com Page 90
IT Officer Professional Knowledge Guide
3. Priority Scheduling
Major attributes are as follows:
www.BankExamsToday.Com Page 91
IT Officer Professional Knowledge Guide
www.BankExamsToday.Com Page 92
IT Officer Professional Knowledge Guide
In this, ready queue is partitioned into separate queues e.g queue 1 and queue 2.
One process remains permanently in one queue and can not shift queues.
Each queue can have its own scheduling algorithms.
Scheduling must be done between two queues and once CPU assigned to a queue,
process in that will be executed before moving to another queue.
6. Thread Scheduling
Major attributes are as follows:
Scheduler assigns CPU based on a distinction between user level threads and kernel
threads.
Competition is between threads inside a process for allocation of CPU.
Practice MCQs
1. Four jobs to be executed on a single processor system arrive at time 0 in the prder A, B, C,
D. Their CPU burst time requirements are 4,1,8,1 units respectively. The completion time of A
under RR scheduling with time quantum =1 would be?
a) 10 b) 4 c) 8 d) 9
2. Which of the follwing scheduling algorithms is non preemptive?
a) FCFS b) RR c) Priority Scheduling d) Multilevel queue
www.BankExamsToday.Com Page 93
IT Officer Professional Knowledge Guide
In Dynamic Linking, system libraries and program code are combined by loader at execution
time. When the libraries are combined at load time itself, it is called static linking.
Swapping
In this mechanism, a process can be temporarily swapped out of memory to a backing store
(usually a hard disk drive) and then brought back into memory for continuing with execution.
Whether or not, the swapped out process will be swapped back into same physical address,
depends on address binding method used. Diagrammatic representation of swapping is as
follows:
Paging
Paging mechanism divides physical memory into fixed size blocks called frames. And it divides
the logical memory into blocks of same size called pages. Logical addresses are mapped to a
real or physical memory addresses. Logical addresses are also called virtual addresses and are
generated by CPU.
Now whenever a process has to be executed, its corresponding pages are loaded in available
memory frames. Operating system sets up a page table to translatelogical to physical
addresses. Logical addresses are divided into page number and page offset. Page number is
used as an index to page table and page offset defines the physical address associated. Page
tables are of two types further- hashed and inverted.
www.BankExamsToday.Com Page 94
IT Officer Professional Knowledge Guide
Virtual Memory
It allows separation of logical memory from physical memory. Large programs store
themselves in form of pages here and at execution, not entire programs but required pages are
loaded into main memory. It allows address space to be shared by several processes. Virtual
memory can be implemented via demand paging and demand segmentation.
Demand Paging
In this concept, pages are brought into memory only when they are needed. It provides are less
I/O and more faster response. How this works - whenever a page is needed, a reference is
made to it and brought into memory. If invalid reference, instruction is aborted and if required
page is not in memory- it is brought into it and referenced again. When the page required is not
available - an interrupt called trap is issued to operating system, this process is called page
fault.
Page Replacement
As we discussed earlier that whenever a page fault occurs, referenced page is brought into
memory. Now let's say memory has no free space and some other page needs to be swapped
out for that. This process is called page replacement.This swapped out page when referenced
later will have to be read from disk and this might involve waiting for I/O completion. This is what
defines the quality of page replacement algorithm used. Various algorithms used are as follows:
www.BankExamsToday.Com Page 95
IT Officer Professional Knowledge Guide
What is a file?
A file is a collection of data or information which has a name. A file system is the way in which
files are named and stored and retrieved logically. Attributes of a file are listed as below:
1. Sequential Access
In this, information in the file is processed in a specific order i.e one record after another.
Compilers access files sequentially.
2. Direct Access
In this, records need not to be accessed in any sequence. Each record has its own
address and thus can be directly accessed by referencing that address.
www.BankExamsToday.Com Page 96
IT Officer Professional Knowledge Guide
Its an extension of sequential access in which an index is create for a file which
contains pointers to memory blocks. These pointers are used to access files directly.
1. Device Drivers
They manage I/O devices at I/O control layer.
5. Application Programs
They use the information with in a file and manipulate it.
www.BankExamsToday.Com Page 97
IT Officer Professional Knowledge Guide
Chapter: C Programming
C Programming
C Programming is an ANSI/ISO standard and powerful programming language for developing
real time applications. C programming language was invented by Dennis Ritchie at the Bell
Laboratories in 1972. It was invented for implementing UNIX operating system. C is most widely
used programming language even today. All other programming languages were derived
directly or indirectly from C programming concepts. This tutorial explains all basic concepts in C
like history of C language, data types, keywords, constants, variables, operators, expressions,
control statements, array, pointer, string, library functions, structures and unions etc.
This C programming tutorial is designed for the new learners, students and also for the
corporate level developers who want to learn and refresh their C programming skills.
The C programming language is a structure oriented programming language, developed at Bell
Laboratories in 1972 by Dennis Ritchie
C programming language features were derived from an earlier language called “B” (Basic
Combined Programming Language – BCPL)
C language was invented for implementing UNIX operating system
In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming
Language” and commonly known as K&R C
In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”,
was completed late 1988.
www.BankExamsToday.Com Page 98
IT Officer Professional Knowledge Guide
C language is one of the powerful language. Below are some of the features of C language.
Reliability
Portability
Flexibility
Interactivity
Modularity
Efficiency and Effectiveness
The C programming language is used for developing system applications that forms a major
portion of operating systems such as Windows, UNIX and Linux. Below are some examples of
C being used.
Database systems
Graphics packages
Word processors
Spreadsheets
Operating system development
Compilers and Assemblers
Network drivers
Interpreters
www.BankExamsToday.Com Page 99
IT Officer Professional Knowledge Guide
1. MiddleLevellanguages:
Middle level languages don‟t provide all the built-in functions found in high level languages, but
provides all building blocks that we need to produce the result we want. Examples: C, C++
2. HighLevellanguages:
High level languages provide almost everything that the programmer might need to do as
already built into the language. Example: Java, Python
3. LowLevellanguages:
Low level languages provides nothing other than access to the machines basic instruction
set. Example: Assembler
In this type of language, large programs are divided into small programs called functions
Prime focus is on functions and procedures that operate on the data
Data moves freely around the systems from one function to another
Program structure follows “Top Down Approach”
Examples: C, Pascal, ALGOL and Modula-2
Object oriented language:
There is no specific structure for programming this language. Examples: BASIC, COBOL,
FORTRAN
C – Programming Basics
This C programming basics section explains a simple “Hello World” C program. Also, it covers
below basic topics as well, which are to be known by any C programmer before writing a C
program.
1. C programming basic commands to write a C program
2. A simple C program with output and explanation
3. Steps to write C programs and get the output\
Below are few commands and syntax used in C programming to write a simple C program. Let‟s
see all the sections of a simple C program line by line.
return 0;
This command terminates C program
2. A SIMPLE C PROGRAM:
Below C program is a very simple and basic program in C programming language. This C
program displays “Hello World!” in the output window. And, all syntax and commands in C
programming are case sensitive. Also, each statement should be ended with semicolon (;)
which is a statement terminator.
1 #include <stdio.h>
2 int main()
3{
6 getch();
7 return 0;
8}
OUTPUT:
Hello World!
Below are the steps to be followed for any C program to create and get the output. This is
common to all C program and there is no exception whether its a very small C program or very
large C program.
1. Create
2. Compile
3. Execute or Run
4. Get the Output
Prerequisite:
If you want to create, compile and execute C programs by your own, you have to install C
compiler in your machine. Then, you can start to execute your own C programs in your
machine.
You can refer below link for how to install C compiler and compile and execute C programs in
your machine.
Once C compiler is installed in your machine, you can create, compile and execute C programs
as shown in below link.
If you don‟t want to install C/C++ compilers in your machine, you can refer online compilers
which will compile and execute C/C++ and many other programming languages online and
display outputs on the screen. Please search for online C/C++ compilers in Google for more
details.
C – Environment Setup Using IDE tool
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section
You can compare all the sections of a C program with the below C program.
1 /*
2 Documentation section
4 Author: fresh2refresh.com
5 Date : 01/01/2012
6 */
12 {
16 return 0;
17 }
18
20 {
22 }
OUTPUT:
This is a C basic
program
Sum of two numbers : 2
Sections Description
DATA TYPES:
There are four data types in C language. They are,
Types Data Types
1. FLOAT:
Float data type allows a variable to store decimal values.
Storage size of float data type is 4. This also varies depend upon the processor in the CPU as
“int” data type.
We can use up-to 6 digits after decimal using float data type.
For example, 10.456789 can be stored in a variable using float data type.
2. DOUBLE:
Double data type is also same as float data type which allows up-to 10 digits after decimal.
The range for double datatype is from 1E–37 to 1E+37.
int main() {
printf("%d", sizeof(ivar));
printf("%d", sizeof(cvar));
printf("%d", sizeof(fvar));
return 0;
}
output : #include<stdio.h>
int main() {
printf("%d", sizeof(int));
printf("%d", sizeof(char));
printf("%d", sizeof(float));
return 0;
1.3.2. MODIFIERS IN C:
The amount of memory space to be allocated for a variable is derived by modifiers.
Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.
For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is 2
byte.
There are 5 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
5. long long
Below table gives the detail about the storage size of each C basic data type in 16 bit processor.
Please keep in mind that storage size and range for int and float datatype will vary depend on
the CPU processor (8,16, 32 and 64 bit)
C Data types
/ storage Size Range
–2,147,483,647 to
long int / 4 2,147,483,647
–(2power(63) –1) to
long long int / 8 2(power)63 –1
–2,147,483,647 to
signed long int / 4 2,147,483,647
2. ENUMERATION DATA TYPE IN C: Enumerated data type variables can only assume values
which have been previously declared.
enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };
enum month this_month;
this_month = feb;
In the above declaration, month is declared as an enumerated data type. It consists of a set of
values, jan to dec. Numerically, jan is given the value 1, feb the value 2, and so on. The
variable this_month is declared to be of the same type as month, then is assigned the value
associated with feb. This_month cannot be assigned any values outside those specified in the
initialization list for the declaration of month.
#include <stdio.h>
main()
direction = east;
The variables defined in the enumerated variable location should be assigned initial values.
Declaration of Variable
Declaration of variable in c can be done using following syntax:
data_type variable name;
or
data_type variable1, variable2,…,variablen;
Where data_type is any valid c data type and variable_name is any valid identifier.
For example,
int a;
float variable;
float a, b;
Initialization of Variable
C variables declared can be initialized with the help of assignment operator „=‟.
Syntax
data_type variable name=constant/literal/expression;
or
variable name=constant/literal/expression;
Example
int a=10;
int a=b+c;
a=10;
a=b+c;
multiiple variables can be initialized in a single statement by single value, for example,
a=b=c=d=e=10;
NOTE: C variables must be declared before they are used in the c program. Also, since c is a
case sensitive programming language, therefore the c variables, abc, Abc and ABC are all
different.
Constant and Volatile Variables
Constant Variables
C variables having same or unchanged value during the execution of a program are called
constant variables. A variable can be declared as constant using keyword const.
For example,
NOTE: If the value of a variable in the current program is to be maintained constant and desired
not to be changed by any other external operation, then the variable declaration will be volatile
const d=10;
C – Array
C Array is a collection of variables belongings to the same data type. You can store group of
data of same data type in an array.
Array might be belonging to any of the data types
Array size must be a constant value.
Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
It is a best practice to initialize an array to zero or null while declaring, if we don‟t assign any
values to array.
EXAMPLE FOR C ARRAYS:
int a[10]; // integer array
char b[10]; // character array i.e. string
TYPES OF C ARRAYS:
There are 2 types of C arrays. They are,
One dimensional array
Multi dimensional array
Two dimensional array
Three dimensional array
four dimensional array etc…
Integer array
Array declaration example:
syntax:
data_type arr_name int age [5];
[arr_size]; int age[5]={0, 1, 2,
Array initialization 3, 4};
syntax: age[0]; /*0 is
data_type arr_name accessed*/
[arr_size]=(value1, age[1]; /*1 is
value2, value3,….); accessed*/
Array accessing age[2]; /*2 is
syntax: accessed*/
char str[10];
char
str[10]={„H‟,„a‟,„i‟};
(or)
char str[0] = „H‟;
char str[1] = „a‟;
char str[2] = „i;
str[0]; /*H is
accessed*/
str[1]; /*a is
accessed*/
str[2]; /*i is
accessed*/
3 int main()
4 {
5 int i;
11 arr[0] = 10;
12 arr[1] = 20;
13 arr[2] = 30;
14 arr[3] = 40;
15 arr[4] = 50; */
16
17 for (i=0;i<5;i++)
18 {
21 }
22
23 }
OUTPUT:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
Array declaration,
initialization and accessing Example
Integer array
Array declaration syntax: example:
data_type arr_name
[num_of_rows][num_of_column]; int arr[2][2];
int arr[2][2] = {1,2, 3,
Array initialization syntax: 4};
data_type arr_name[2][2] = arr [0] [0] = 1;
{{0,0},{0,1},{1,0},{1,1}}; arr [0] ]1] = 2;
Array accessing syntax: arr [1][0] = 3;
arr_name[index]; arr [1] [1] = 4;
1. MALLOC() FUNCTION IN C:
malloc () function is used to allocate space in memory during the execution of the program.
malloc () does not initialize the memory allocated during execution. It carries garbage value.
malloc () function returns null pointer if it couldn‟t able to allocate requested amount of memory.
2 #include <string.h>
3 #include <stdlib.h>
5 int main()
6 {
7 char *mem_allocation;
11 {
13 }
14 else
15 {
16 strcpy( mem_allocation,"fresh2refresh.com");
17 }
19 "%s\n", mem_allocation );
20 free(mem_allocation);
21 }
OUTPUT:
2. CALLOC() FUNCTION IN C:
calloc () function is also like malloc () function. But calloc () initializes the allocated memory to
zero. But, malloc() doesn‟t.
2 #include <string.h>
3 #include <stdlib.h>
5 int main()
6 {
7 char *mem_allocation;
11 {
13 }
14 else
15 {
16 strcpy( mem_allocation,"fresh2refresh.com");
17 }
19 "%s\n", mem_allocation );
20 free(mem_allocation);
21 }
OUTPUT
3. REALLOC() FUNCTION IN C:
realloc () function modifies the allocated memory size by malloc () and calloc () functions to new
size.
If enough space doesn‟t exist in memory of current block to extend, new block is allocated for
the full size of reallocation, then copies the existing data to new block and then frees the old
block.
4. FREE() FUNCTION IN C:
free () function frees the allocated memory by malloc (), calloc (), realloc () functions and returns
the memory to the system.
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
5 int main()
6 {
7 char *mem_allocation;
11 {
13 }
14 else
15 {
16 strcpy( mem_allocation,"fresh2refresh.com");
17 }
19 "%s\n", mem_allocation );
20 mem_allocation=realloc(mem_allocation,100*sizeof(char));
22 {
24 }
25 else
26 {
28 „100 characters");
29 }
31 free(mem_allocation);
32 }
It allocates multiple
It allocates only single block of blocks of requested
requested memory memory
Library Functions :
Library functions in C language are inbuilt functions which are grouped together and placed in a
common place called library.
Each library function in C performs specific operation.
We can make use of these library functions to get the pre-defined output instead of writing our
own code to get those outputs.
These library functions are created by the persons who designed and created C compilers.
All C standard library functions are declared in many header files which are saved as
file_name.h.
Actually, function declaration, definition for macros are given in all header files.
We are including these header files in our C program using “#include<file_name.h>” command
to make use of the functions those are declared in the header files.
When we include header files in our C program using “#include<filename.h>” command, all C
code of the header files are included in C program. Then, this C program is compiled by
compiler and executed.
Please check the below links for actual C source code for the respective C header files.
1. C – stdio.h source code
2. C – conio.h source code
3. C – string.h source code
4. C – stdlib.h source code
5. C – math.h source code
6. C – time.h source code
7. C – ctype.h source code
If you want to check source code for all header files, you can check inside “include” directory
after C compiler is installed in your machine.
For example, if you install DevC++ compiler in C directory in your machine, “C:\Dev-
Cpp\include” is the path where all header files will be available.
Typedef:
Typedef is a keyword that is used to give a new symbolic name for the existing name in a C
program. This is same like defining alias for the commands.
Consider the below structure.
structstudent
{
intmark[2];
charname[10];
floataverage;
}
Variable for the above structure can be declared in two ways.
1st way :
structstudentrecord;/*fornormalvariable*/
struct student *record; /* for pointer variable */
2nd way :
typedef struct student status;
When we use “typedef” keyword before struct <tag_name> like above, after that we can simply
use type definition “status” in the C program to declare structure variable.
Now, structure variable declaration will be, “status record”.
This is equal to “struct student record”. Type definition for “struct student” is status. i.e. status =
“struct student”
2
#include <stdio.h>
3
#include <string.h>
4
5
typedef struct student
6
{
7
int id;
8
char name[20];
9
float percentage;
10
} status;
11
12
int main()
13
{
14
status record;
15
record.id=1;
16
strcpy(record.name, "Raju");
17
record.percentage = 86.5;
18
printf(" Id is: %d \n", record.id);
19
printf(" Name is: %s \n", record.name);
20
printf(" Percentage is: %f \n", record.percentage);
21
return 0;
22
}
23
C++ PROGRAMMING
Intoduction: C++ is a middle-level programming language developed by Bjarne Stroustrup
starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX.
This reference will take you through simple and practical approach while learning C++
Programming language.
Audience:
This reference has been prepared for the beginners to help them understand the basic to
advanced concepts related to C++ Programming languages.
Prerequisites
Before you start doing practice with various types of examples given in this reference, I'm
making an assumption that you are already aware about what is a computer program and what
is a computer programming language?
For most of the examples given in this tutorial you will find Try it option, so just make use of this
option to execute your C++ programs at the spot and enjoy your learning.
Try following example using Try it option available at the top right corner of the below sample
code box −
#include <iostream>
int main()
return 0;
Let us try to understand a little about all these, through a simple example. Human Beings are
living forms, broadly categorized into two types, Male and Female. Right? Its true. Every Human
being(Male or Female) has two legs, two hands, two eyes, one nose, one heart etc. There are
body parts that are common for Male and Female, but then there are some specific body parts,
present in a Male which are not present in a Female, and some body parts present in Female
but not in Males.
All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female, performs
some common functions, but there are some specifics to both, which is not valid for the other
For example : A Female can give birth, while a Male cannot, so this is only for the Female.
Human Anatomy is interesting, isn't it? But let's see how all this is related to C++ and OOPS.
Here we will try to explain all the OOPS concepts through this example and later we will have
the technical definitons for all this.
Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which
defines its properties and its functions. Like Human Being, having body parts, and performing
various actions.
Inheritance
Considering Human Being a class, which has properties like hands, legs, eyes etc, and
functions like walk, talk, eat, see etc. Male and Female are also classes, but most of the
properties and functions are included in Human Being, hence they can inherit everything from
class Human Being using the concept of Inheritance.
Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being,
Male or Female, we just mean a kind, you, your friend, me we are the forms of these classes.
We have a physical existence while a class is just a logical definition. We are the objects.
Abstraction
Abstraction means, showcasing only the required things to the outside workd while hiding the
details. Continuing our example, Human Being's can talk, walk, hear, eat, but the details are
hidden from the outside world. We can take our skin as the Abstraction factor in our case, hiding
the inside mechanism.
Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk.
Our hands, help us hold things. This binding of the properties to functions is called
Encapsulation.
Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either
changing how it is done or by changing the parts using which it is done. Both the ways have
different terms for them.
If we walk using our hands, and not legs, here we will change the parts used to perform
something. Hence this is called Overloading.
And if there is a defined way of walking, but I wish to walk differently, but using my legs, like
everyone else. Then I can walk like I want, this will be calles as Overriding.
Now, let us discuss some of the main features of Object Oriented Programming which you will
be using in C++(technically).
1. Objects
2. Classes
3. Abstraction
4. Encapsulation
5. Inheritance
6. Overloading
7. Exception Handling
Objects
Objects are the basic unit of OOP. They are instances of class, which have data members and
uses various member functions to perform tasks.
Class
It is similar to structures in C language. Class can also be defined as user defined data type but
it also contains functions in it. So, class is basically a blueprint for object. It declare & defines
what data variables the object will have and what operations can be performed on the class's
object.
Abstraction
Abstraction refers to showing only the essential features of the application and hiding the
details. In C++, classes provide methods to the outside world to access & use the data
variables, but the variables are hidden from direct access. This can be done access specifiers.
Encapsulation
It can also be said data binding. Encapsulation is all about binding the data variables and
functions together in class.
Inheritance
Inheritance is a way to reuse once written code again and again. The class which is inherited is
called base calls & the class which inherits is called derived class. So when, a derived class
inherits a base class, the derived class can use all the functions which are defined in base
class, hence making code reusable.
Polymorphism
It is a feature, which lets us create functions with same name but different arguments, which will
perform differently. That is function with same name, functioning in different way. Or, it also
allows us to redefine a function to provide its new definition. You will learn how to do this in
details soon in coming lessons.
Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at
runtime.
All C++ programs are composed of the following two fundamental elements:
Program statements (code): This is the part of a program that performs actions and they are
called functions.
Program data: The data is the information of the program which affected by the program
functions.
Encapsulation is an Object Oriented Programming concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and
misuse. Data encapsulation led to the important OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them
and data abstraction is a mechanism of exposing only the interfaces and hiding the
implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of user-
defined types, called classes. We already have studied that a class can contain private,
protected and public members. By default, all items defined in a class are private. For
example:
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The variables length, breadth, and height are private. This means that they can be accessed
only by other members of the Box class, and not by any other part of your program. This is one
way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you must
declare them after the public keyword. All variables or functions defined after the public
specifier are accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces
encapsulation. The ideal is to keep as many of the details of each class hidden from all other
classes as possible.
Any C++ program where you implement a class with public and private members is an example
of data encapsulation and data abstraction. Consider the following example:
#include <iostream>
using namespace std;
class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
Inheritance:
One of the most important concepts in object-oriented programming is that of inheritance.
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 baseclass, 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.
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.
Consider a base class Shape and its derived class Rectangle as follows:
#include <iostream>
// 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
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
}
We can summarize the different access types according to who can access them in the
following way:
A derived class inherits all base class methods with the following exceptions:
Type of Inheritance:
When deriving a class from a base class, the base class may be inherited through public,
protected or private inheritance. The type of inheritance is specified by the access-specifier as
explained above.
We hardly use protected or private inheritance, but public inheritance is commonly used.
While using different type of inheritance, following rules are applied:
Public Inheritance: When deriving a class from a public base class,public members of the
base class become public members of the derived class and protected members of the base
class becomeprotected members of the derived class. A base class's privatemembers are
never accessible directly from a derived class, but can be accessed through calls to
the public and protected members of the base class.
Private Inheritance: When deriving from a private base class,public and protected members
of the base class become privatemembers of the derived class.
Multiple Inheritances:
A C++ class can inherit members from more than one class and here is the extended syntax:
Where access is one of public, protected, or private and would be given for every base class
and they will be separated by comma as shown above. Let us try the following example:
#include <iostream>
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
return 0;
}
When the above code is compiled and executed, it produces the following result:
Parameterized Constructor:
A default constructor does not have any parameter, but if you need, a constructor can have
parameters. This helps you to assign initial value to an object at the time of its creation as
shown in the following example:
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
When the above code is compiled and executed, it produces the following result:
In case of parameterized constructor, you can use following syntax to initialize the fields:
Line::Line( double len): length(len)
{
cout << "Object is being created, length = " << len << endl;
}
Above syntax is equal to the following syntax:
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
If for a class C, you have multiple fields X, Y, Z, etc., to be initialized, then use can use same
syntax and separate the fields by comma as follows:
A destructor is a special member function of a class that is executed whenever an object of it's
class goes out of scope or whenever the delete expression is applied to a pointer to the object
of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither
return a value nor can it take any parameters. Destructor can be very useful for releasing
resources before coming out of the program like closing files, releasing memories etc.
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void)
{
cout << "Object is being created" << endl;
}
Line::~Line(void)
{
cout << "Object is being deleted" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
File handling:
ofstream This data type represents the output file stream and
is used to create files and to write information to
files.
ifstream This data type represents the input file stream and
is used to read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.
Opening a File:
A file must be opened before you can read from it or write to it. Either the of stream or f
stream object may be used to open a file for writing and ifstream object is used to open a file for
reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream,
and of stream objects.
void open(const char *filename, ios::open mode mode);
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open() member function defines the mode in which the file should be opened.
Mode Flag Description
Closing a File
When a C++ program terminates it automatically closes flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream,
and ofstream objects.
void close();
Writing to a File:
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the screen.
The only difference is that you use anofstream or fstream object instead of the cout object.
Reading from a File:
You read information from a file into your program using the stream extraction operator (>>) just
as you use that operator to input information from the keyboard. The only difference is that you
use an ifstream or fstream object instead of the cin object.
Read & Write Example:
Following is the C++ program which opens a file in reading and writing mode. After writing
information inputted by the user to a file named afile.dat, the program reads information from the
file and outputs it onto the screen:
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
return 0;
}
When the above code is compiled and executed, it produces the following sample input and
output:
$./a.out
You can redefine or overload most of the built-in operators available in C++. Thus a
programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator followed by the
symbol for the operator being defined. Like any other function, an overloaded operator has a
return type and a parameter list.
declares the addition operator that can be used to add two Box objects and returns final Box
object. Most overloaded operators may be defined as ordinary non-member functions or as
class member functions. In case we define above function as non-member function of a class
then we would have to pass two arguments for each operand as follows:
Following is the example to show the concept of operator over loading using a member function.
Here an object is passed as an argument whose properties will be accessed using this object,
the object which will call this operator can be accessed using this operator as explained below:
#include <iostream>
using namespace std;
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box
When the above code is compiled and executed, it produces the following result:
Overloadable/Non-overloadableOperators:
+ - * / % ^
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
You can have multiple definitions for the same function name in the same scope. The definition
of the function must differ from each other by the types and/or the number of arguments in the
argument list. You can not overload function declarations that differ only by return type.
Following is the example where same function print() is being used to print different data types:
#include <iostream>
using namespace std;
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void)
{
printData pd;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing character: Hello C+
Friend Function : A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though the prototypes for
friend functions appear in the class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or class template,
in which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the class definition
with keyword friend as follows:
class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne, place a
following declaration in the definition of class ClassOne:
#include <iostream>
class Box
{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
return 0;
}
Template: Templates are the foundation of generic programming, which involves writing code in
a way that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library
containers like iterators and algorithms are examples of generic programming and have been
developed using template concept.
There is a single definition of each container, such as vector, but we can define many different
kinds of vectors for example, vector <int> or vector <string>.
You can use templates to define functions as well as classes, let us see how do they work:
Function Template:
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be used
within the function definition.
The following is the example of a function template that returns the maximum of two values:
#include <iostream>
#include <string>
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
If we compile and run above code, this would produce the following result:
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
Class Template:
Just as we can define function templates, we can also define class templates. The general form
of a generic class declaration is shown here:
template <class type> class class-name {
.
.
.
}
Here, type is the placeholder type name, which will be specified when a class is instantiated.
You can define more than one generic data type by using a comma-separated list.
Following is the example to define class Stack<> and implement generic methods to push and
pop the elements from the stack:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const{ // return true if empty.
return elems.empty();
}
};
}
// remove last element
elems.pop_back();
}
int main()
{
try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings
Exceptions:
An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, andthrow.
throw: A program throws an exception when a problem shows up. This is done using
a throw keyword.
catch: A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. Thecatch keyword indicates the catching of an
exception.
try: A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.
Assuming a block will raise an exception, 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
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in case
your try block raises more than one exception in different situations.
Throwing Exceptions:
Exceptions can be thrown anywhere within a code block using throwstatements. The operand
of the throw statements determines a type for the exception and can be any expression and the
type of the result of the expression determines the type of exception thrown.
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions:
The catch block following the try block catches any exception. You can specify what type of
exception you want to catch and this is determined by the exception declaration that appears in
parentheses following the keyword catch.
try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify that a catch
block should handle any type of exception that is thrown in a try block, you must put an ellipsis,
..., between the parentheses enclosing the exception declaration as follows:
try
{
// protected code
}catch(...)
{
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch it in catch
block.
#include <iostream>
using namespace std;
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Because we are raising an exception of type const char*, so while catching this exception, we
have to use const char* in catch block. If we compile and run above code, this would produce
the following result:
Division by zero condition!
C++ provides a list of standard exceptions defined in <exception> which we can use in our
programs. These are arranged in a parent-child class hierarchy shown below:
Here is the small description of each exception mentioned in the above hierarchy:
Exception Description
Memory Management: A good understanding of how dynamic memory really works in C++ is
essential to becoming a good C++ programmer. Memory in your C++ program is divided into
two parts:
The stack: All variables declared inside the function will take up memory from the stack.
The heap: This is unused memory of the program and can be used to allocate the memory
dynamically when program runs.
Many times, you are not aware in advance how much memory you will need to store particular
information in a defined variable and the size of required memory can be determined at run
time.
You can allocate memory at run time within the heap for the variable of a given type using a
special operator in C++ which returns the address of the space allocated. This operator is
called new operator.
If you are not in need of dynamically allocated memory anymore, you can use delete operator,
which de-allocates memory previously allocated by new operator.
new data-type;
Here, data-type could be any built-in data type including an array or any user defined data
types include class or structure. Let us start with built-in data types. For example we can define
a pointer to type double and then request that the memory be allocated at execution time. We
can do this using the newoperator with the following statements:
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
The memory may not have been allocated successfully, if the free store had been used up. So it
is good practice to check if new operator is returning NULL pointer and take appropriate action
as below:
The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc()
function. The main advantage of new over malloc() is that new doesn't just allocate memory, it
constructs objects which is prime purpose of C++.
At any point, when you feel a variable that has been dynamically allocated is not anymore
required, you can free up the memory that it occupies in the free store with the delete operator
as follows:
Let us put above concepts and form the following example to show how new and delete work:
#include <iostream>
using namespace std;
int main ()
{
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
return 0;
}
If we compile and run above code, this would produce the following result:
delete[] pvalue[i];
}
delete [] pvalue;
Objects are no different from simple data types. For example, consider the following code where
we are going to use an array of objects to clarify the concept:
#include <iostream>
using namespace std;
class Box
{
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};
int main( )
{
Box* myBoxArray = new Box[4];
return 0;
}
Java Tutorial
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 approaches while learning Java
Programming language.
Audience
This tutorial has been prepared for the beginners to help them understand the basic to
advanced concepts related to Java Programming language.
Prerequisites
Before you start practicing various types of examples given in this reference, we assume that
you are already aware about computer programs and computer programming languages.
Java – classes
Nested Classes
In Java, just like methods, variables of a class too can have another class as its member.
Writing a class within another is allowed in Java. The class written within is called the nested
class, and the class that holds the inner class is called the outer class.
Syntax
Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class
and the class Inner_Demo is the nested class.
class Outer_Demo { class Nested_Demo { }}
Nested classes are divided into two types −
Non-static nested classes− These are the non-static members of a class.
Static nested classes− These are the static members of a class.
Inner Classes (Non-static Nested Classes)
Inner classes are a security mechanism in Java. We know a class cannot be associated with the
access modifier private, but if we have the class as a member of other class, then the inner
class can be made private. And this is also used to access the private members of a class.
Inner classes are of three types depending on how and where you define them. They are −
Inner Class
Method-local Inner Class
Anonymous Inner Class
Inner Class
Creating an inner class is quite simple. You just need to write a class within a class. Unlike a
class, an inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside the class.
Following is the program to create an inner class and access it. In the given example, we make
the inner class private and access the class through a method.
Example
class Outer_Demo { int num; // inner class private class Inner_Demo { public void
print() { System.out.println("This is an inner class"); } } // Accessing he inner class
from the method within void display_Inner() { Inner_Demo inner = new
Inner_Demo(); inner.print(); }} public class My_class { public static void main(String
args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); //
Accessing the display_Inner() method. outer.display_Inner(); }}
Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner
class, display_Inner() is the method inside which we are instantiating the inner class, and this
method is invoked from the mainmethod.
If you compile and execute the above program, you will get the following result −
Output
This is an inner class.
As mentioned earlier, inner classes are also used to access the private members of a class.
Suppose, a class is having private members to access them. Write an inner class in it, return
the private members from a method within the inner class, say, getValue(), and finally from
another class (from which you want to access the private members) call the getValue() method
of the inner class.
To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using
the object of the outer class, following is the way in which you can instantiate the inner class.
Outer_Demo outer = new Outer_Demo();Outer_Demo.Inner_Demo inner = outer.new
Inner_Demo();
The following program shows how to access the private members of a class using inner class.
Example
class Outer_Demo { // private variable of the outer class private int num = 175; // inner
class public class Inner_Demo { public int getNum() { System.out.println("This is the
getnum method of the inner class"); return num; } }} public class My_class2 { public
static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new
Outer_Demo(); // Instantiating the inner class Outer_Demo.Inner_Demo inner =
outer.new Inner_Demo(); System.out.println(inner.getNum()); }}
If you compile and execute the above program, you will get the following result –
Output
The value of num in the class Test is: 175
Example
public class Outerclass { // instance method of the outer class void my_Method() { int num
= 23; // method-local inner class class MethodInner_Demo { public void print()
{ System.out.println("This is method inner class "+num); } } // end of
inner class // Accessing the inner class MethodInner_Demo inner = new
MethodInner_Demo(); inner.print(); } public static void main(String args[])
{ Outerclass outer = new Outerclass(); outer.my_Method(); }}
If you compile and execute the above program, you will get the following result –
Output
This is method inner class 23
Inner Class
Creating an inner class is quite simple. You just need to write a class within a class. Unlike a
class, an inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside the class.
Following is the program to create an inner class and access it. In the given example, we make
the inner class private and access the class through a method.
Example
class Outer_Demo { int num; // inner class private class Inner_Demo { public void
print() { System.out.println("This is an inner class"); } } // Accessing he inner class
from the method within void display_Inner() { Inner_Demo inner = new
Inner_Demo(); inner.print(); }} public class My_class { public static void main(String
args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); //
Accessing the display_Inner() method. outer.display_Inner(); }}
Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner
class, display_Inner() is the method inside which we are instantiating the inner class, and this
method is invoked from the mainmethod.
If you compile and execute the above program, you will get the following result −
Output
This is an inner class.
As mentioned earlier, inner classes are also used to access the private members of a class.
Suppose, a class is having private members to access them. Write an inner class in it, return
the private members from a method within the inner class, say, getValue(), and finally from
another class (from which you want to access the private members) call the getValue() method
of the inner class.
To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using
the object of the outer class, following is the way in which you can instantiate the inner class.
Outer_Demo outer = new Outer_Demo();Outer_Demo.Inner_Demo inner = outer.new
Inner_Demo();
The following program shows how to access the private members of a class using inner class.
Example
class Outer_Demo { // private variable of the outer class private int num = 175; // inner
class public class Inner_Demo { public int getNum() { System.out.println("This is the
getnum method of the inner class"); return num; } }} public class My_class2 { public
static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new
Outer_Demo(); // Instantiating the inner class Outer_Demo.Inner_Demo inner =
outer.new Inner_Demo(); System.out.println(inner.getNum()); }}
If you compile and execute the above program, you will get the following result −
Output
The value of num in the class Test is: 175
Method-local Inner Class
In Java, we can write a class within a method and this will be a local type. Like local variables,
the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the inner class is
defined. The following program shows how to use a method-local inner class.
Example
public class Outerclass { // instance method of the outer class void my_Method() { int num
= 23; // method-local inner class class MethodInner_Demo { public void print()
{ System.out.println("This is method inner class "+num); } } // end of
inner class // Accessing the inner class MethodInner_Demo inner = new
MethodInner_Demo(); inner.print(); } public static void main(String args[])
{ Outerclass outer = new Outerclass(); outer.my_Method(); }}
If you compile and execute the above program, you will get the following result −
Output
This is method inner class 23
Anonymous Inner Class
An inner class declared without a class name is known as an anonymous inner class. In case
of anonymous inner classes, we declare and instantiate them at the same time. Generally, they
are used whenever you need to override the method of a class or an interface. The syntax of an
anonymous inner class is as follows −
Syntax
AnonymousInner an_inner = new AnonymousInner() { public void my_method()
{ ........ ........ } };
The following program shows how to override the method of a class using anonymous inner
class.
Example
abstract class AnonymousInner { public abstract void mymethod();} public class Outer_class
{ public static void main(String args[]) { AnonymousInner inner = new AnonymousInner()
{ public void mymethod() { System.out.println("This is an example of anonymous
inner class"); } }; inner.mymethod(); }}
If you compile and execute the above program, you will get the following result −
Output
This is an example of anonymous inner class
In the same way, you can override the methods of the concrete class as well as the interface
using an anonymous inner class.
Anonymous Inner Class as Argument
Generally, if a method accepts an object of an interface, an abstract class, or a concrete class,
then we can implement the interface, extend the abstract class, and pass the object to the
method. If it is a class, then we can directly pass it to the method.
But in all the three cases, you can pass an anonymous inner class to the method. Here is the
syntax of passing an anonymous inner class as a method argument −
obj.my_Method(new My_Class() { public void Do() { ..... ..... }});
The following program shows how to pass an anonymous inner class as a method argument.
Example
// interfaceinterface Message { String greet();} public class My_class { // method which
accepts the object of interface Message public void displayMessage(Message m)
{ System.out.println(m.greet() + ", This is an example of anonymous inner class as an
argument"); } public static void main(String args[]) { // Instantiating the class My_class
obj = new My_class(); // Passing an anonymous inner class as an
argument obj.displayMessage(new Message() { public String greet() { return
"Hello"; } }); }}
If you compile and execute the above program, it gives you the following result −
Output
Hello This is an example of anonymous inner class as an argument
Static Nested Class
A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods of
the outer class. The syntax of static nested class is as follows −
Syntax
class MyOuter { static class Nested_Demo { }}
Instantiating a static nested class is a bit different from instantiating an inner class. The following
program shows how to use a static nested class.
Example
public class Outer { static class Nested_Demo { public void my_method()
{ System.out.println("This is my nested class"); } } public static void main(String
args[]) { Outer.Nested_Demo nested = new
Outer.Nested_Demo(); nested.my_method(); }}
Loop Control
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
Java programming language provides the following types of loop to handle looping
requirements. Click the following links to check their detail.
Syntax
Example
Output
Multithreading
Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java. A multi-threaded program contains two or more parts that can run
concurrently and each part can handle a different task at the same time making optimal use of
the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources
such as a CPU. Multi-threading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads. Each of the
threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed concurrently
in the same program.
New− A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as aborn thread.
Runnable− After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
Waiting− Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task. A thread transitions back to the runnable state only when another
thread signals the waiting thread to continue executing.
Timed Waiting− A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval expires
or when the event it is waiting for occurs.
Terminated (Dead)− A runnable thread enters the terminated state when it completes its task
or otherwise terminates.
Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY
(a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in
which threads execute and are very much platform dependent
Step 1
As a first step, you need to implement a run() method provided by a Runnableinterface. This
method provides an entry point for the thread and you will put your complete business logic
inside this method. Following is a simple syntax of the run() method −
public void run( )
Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnableinterface
and threadName is the name given to the new thread.
Step 3
Once a Thread object is created, you can start it by calling start() method, which executes a call
to run( ) method. Following is a simple syntax of start() method −
void start();
Example
Output
Access Modifiers
Java provides a number of access modifiers to set access levels for classes, variables,
methods, and constructors. The four access levels are −
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Example
Variables and methods can be declared without any modifiers, as in the following examples −
String version = "1.5.1"; boolean processOrder() { return true;}
Example
Example
Protected access gives the subclass a chance to use the helper method or variable, while
preventing a nonrelated class from trying to use it.
Example
The following parent class uses protected access control, to allow its child class
override openSpeaker() method −
class AudioPlayer { protected boolean openSpeaker(Speaker sp) { // implementation
details }} class StreamingAudioPlayer { boolean openSpeaker(Speaker sp) { //
implementation details }}
Here, if we define openSpeaker() method as private, then it would not be accessible from any
other class other than AudioPlayer. If we define it as public, then it would become accessible to
all the outside world. But our intention is to expose this method to its subclass only, that‟s why
we have used protected modifier.
Assignment Operators
The following program is a simple example that demonstrates the assignment operators. Copy
and paste the following Java program in Test.java file. Compile and run this program –
Example
public class Test { public static void main(String args[]) { int a = 10; int b = 20; int c =
0; c = a + b; System.out.println("c = a + b = " + c ); c += a ; System.out.println("c
+= a = " + c ); c -= a ; System.out.println("c -= a = " + c ); c *= a
; System.out.println("c *= a = " + c ); a = 10; c = 15; c /= a ; System.out.println("c
/= a = " + c ); a = 10; c = 15; c %= a ; System.out.println("c %= a = " + c ); c
<<= 2 ; System.out.println("c <<= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = "
+ c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c &= a ; System.out.println("c
&= a = " + c ); c ^= a ; System.out.println("c ^= a = " + c ); c |= a
; System.out.println("c |= a = " + c ); }}
This will produce the following result –
Output
c = a + b = 30c += a = 40c -= a = 30c *= a = 300c /= a = 1c %= a = 5c <<= 2 = 20c >>= 2 = 5c
>>= 2 = 1c &= a = 0c ^= a = 10
Java Garbage Collection
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
1) By nulling a reference:
1. Employee e=newEmployee();
2. e=null;
1. Employee e1=newEmployee();
2. Employee e2=newEmployee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection
3) By annonymous object:
1. newEmployee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
1. protectedvoid finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to perform
cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
1. publicclass TestGarbage1{
2. public void finalize(){System.out.println("object is garbage collected");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. gc();
9. }
Exceptions
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
A network connection has been lost in the middle of communications or the JVM has run out of
memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions. You need to understand them to know
how exception handling works in Java.
Checked exceptions− A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions. These exceptions cannot simply be ignored at
the time of compilation, the programmer should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then aFileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
Example
Output
For example, if you have declared an array of size 5 in your program, and trying to call the
6th element of the array then anArrayIndexOutOfBoundsExceptionexception occurs.
Example
public class Unchecked_Demo { public static void main(String args[]) { int num[] = {1, 2, 3,
4}; System.out.println(num[5]); }}
If you compile and execute the above program, you will get the following exception.
Output
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.
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the Java programs. Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of memory. Normally, programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
Following is a list of most common checked and unchecked Java's Built-in Exceptions.
Exceptions Methods
Following is the list of important methods available in the Throwable class.
Sr.No. Method & Description
public String getMessage()
1 Returns a detailed message about the exception that has occurred.
This message is initialized in the Throwable constructor.
public Throwable getCause()
2 Returns the cause of the exception as represented by a Throwable
object.
public String toString()
3 Returns the name of the class concatenated with the result of
getMessage().
public void printStackTrace()
4 Prints the result of toString() along with the stack trace to System.err,
the error output stream.
Catching Exceptions
A method catches an exception using a combination of the try and catchkeywords. 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 −
Syntax
Example
The following is an array declared with 2 elements. Then the code tries to access the
3rd element of the array which throws an exception.
// File Name : ExcepTest.javaimport java.io.*; public class ExcepTest { public static void
main(String args[]) { try { int a[] = new int[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 will produce the following result −
Output
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following −
Syntax
Example
Example
Example
Syntax
Example
public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try
{ System.out.println("Access element three :" +
a[3]); }catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception
thrown :" + e); }finally { a[0] = 6; System.out.println("First element value: " +
a[0]); System.out.println("The finally statement is executed"); } }}
This will produce the following result −
Output
The try-with-resources
Generally, when we use any resources like streams, connections, etc. we have to close them
explicitly using finally block. In the following program, we are reading data from a file
using FileReader and we are closing it using finally block.
Example
Syntax
Example
Example
Output
Depositing $500... Withdrawing $100... Withdrawing $600...Sorry, but you are short
$200.0InsufficientFundsException at
CheckingAccount.withdraw(CheckingAccount.java:25) at
BankDemo.main(BankDemo.java:13)
Common Exceptions
In Java, it is possible to define two catergories of Exceptions and Errors.
JVM Exceptions− These are exceptions/errors that are exclusively or logically thrown by the
JVM. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException.
Programmatic Exceptions− These exceptions are thrown explicitly by the application or the
API programmers. Examples: IllegalArgumentException, IllegalStateException.
Link− Each link of a linked list can store a data called an element.
Next− Each link of a linked list contains a link to the next link called Next.
LinkedList− A Linked List contains the connection link to the first link called First.
Basic Operations
Following are the basic operations supported by a list.
Insertion− Adds an element at the beginning of the list.
Deletion− Deletes an element at the beginning of the list.
Display− Displays the complete list.
Search− Searches an element using the given key.
Delete− Deletes an element using the given key.
Insertion Operation
Adding a new node in linked list is a more than one step activity. We shall learn this with
diagrams here. First, create a node using the same structure and find the location where it has
to be inserted.
Imagine that we are inserting a node B (NewNode), between A (LeftNode) andC (RightNode).
Then point B.next to C −
NewNode.next −> RightNode;
It should look like this −
Now, the next node at the left should point to the new node.
LeftNode.next −> NewNode;
This will put the new node in the middle of the two. The new list should look like this −
Similar steps should be taken if the node is being inserted at the beginning of the list. While
inserting it at the end, the second last node of the list should point to the new node and the new
node will point to NULL.
Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial representation. First,
locate the target node to be removed, by using searching algorithms.
The left (previous) node of the target node now should point to the next node of the target node
−
LeftNode.next −> TargetNode.next;
This will remove the link that was pointing to the target node. Now, using the following code, we
will remove what the target node is pointing at.
TargetNode.next −> NULL;
We need to use the deleted node. We can keep that in memory otherwise we can simply
deallocate memory and wipe off the target node completely.
Reverse Operation
This operation is a thorough one. We need to make the last node to be pointed by the head
node and reverse the whole linked list.
First, we traverse to the end of the list. It should be pointing to NULL. Now, we shall make it
point to its previous node −
We have to make sure that the last node is not the lost node. So we'll have some temp node,
which looks like the head node pointing to the last node. Now, we shall make all left side nodes
point to their previous nodes one by one.
Except the node (first node) pointed by the head node, all nodes should point to their
predecessor, making them their new successor. The first node will point to NULL.
We'll make the head node point to the new first node by using the temp node.
The linked list is now reversed.
What is a Stack?
If you've ever put something on top of something else of the same type (e.g. sheets of paper),
you have created a stack! In terms of programming, stacks mean just that.
Since Stacks are practically identical to Queues (with one major difference), this article builds on
the amazing Queues tutorial. I advise you to read it first if you feel a bit confused.
The following is a list of operations that can generally be performed on a stack. This of course
will depend on your implementation.
Method names for my implementation are in blue.
Descriptions are in green.
pop() - Removes the object from the top of the stack and returns
it to the caller.
Queues in Java
There is more than one way of implementing a queue. The most common
way is to use linked lists (see Linked Lists Tutorial). My implementation
uses linked lists.
The purpose of this article is to help you understand how queues are
implemented. These days, it makes more sense to use the queues from the
Java library, unless you are doing something very custom.
--------------------
q.enqueue(alice);
System.out.println(((Person)q.peek()).getName());
q.enqueue(bob);
free.
q.dequeue();
System.out.println(((Person)q.peek()).getName());
q.dequeue();
This is my Queue.java:
// Queue constructor
public Queue()
list.add(item);
// not met.
list.remove(1);
return item;
/ not met.
return list.get(1);
Tree represents the nodes connected by edges. We will discuss binary tree or binary search
tree specifically.
Binary Tree is a special datastructure used for data storage purposes. A binary tree has a
special condition that each node can have a maximum of two children. A binary tree has the
benefits of both an ordered array and a linked list as search is as quick as in a sorted array and
insertion or deletion operation are as fast as in linked list.
Important Terms:
Path− Path refers to the sequence of nodes along the edges of a tree.
Root− The node at the top of the tree is called root. There is only one root per tree and one
path from the root node to any node.
Parent− Any node except the root node has one edge upward to a node called parent.
Child− The node below a given node connected by its edge downward is called its child node.
Leaf− The node which does not have any child node is called the leaf node.
Visiting− Visiting refers to checking the value of a node when control is on the node.
Levels− Level of a node represents the generation of a node. If the root node is at level 0, then
its next child node is at level 1, its grandchild is at level 2, and so on.
keys− Key represents a value of a node based on which a search operation is to be carried out
for a node.
Binary Search tree exhibits a special behavior. A node's left child must have a value less than
its parent's value and the node's right child must have a value greater than its parent value.
We're going to implement tree using node object and connecting them through references.
Tree Node
The code to write a tree node would be similar to what is given below. It has a data part and
references to its left and right child nodes.
struct node { int data; struct node *leftChild; struct node *rightChild;};
The basic operations that can be performed on a binary search tree data structure, are the
following –
We shall learn creating (inserting into) a tree structure and searching a data item in a tree in this
chapter. We shall learn about tree traversing methods in the coming chapter.
Insert Operation
The very first insertion creates the tree. Afterwards, whenever an element is to be inserted, first
locate its proper location. Start searching from the root node, then if the data is less than the key
value, search for the empty location in the left subtree and insert the data. Otherwise, search for
the empty location in the right subtree and insert the data.
Algorithm
If root is NULL then create root nodereturn If root exists then compare the data with
node.data while until insertion position is located If data is greater than
node.data goto right subtree else goto left subtree endwhile insert
data end If
Implementation
Search Operation
Whenever an element is to be searched, start searching from the root node, then if the data is
less than the key value, search for the element in the left subtree. Otherwise, search for the
element in the right subtree. Follow the same algorithm for each node.
Algorithm
If root.data is equal to search.data return rootelse while data not found If data is greater
than node.data goto right subtree else goto left subtree If data
found return node endwhile return data not found end if
struct node* search(int data) { struct node *current = root; printf("Visiting elements:
"); while(current->data != data) { if(current != NULL) printf("%d ",current-
>data); //go to left tree if(current->data > data) { current = current-
>leftChild; } //else go to right tree else { current = current-
>rightChild; } //not found if(current == NULL) { return NULL; } return
current; } }
key(α) ≥ key(β)
As the value of parent is greater than that of child, this property generates Max Heap. Based on
this criteria, a heap can be of two types –
For Input → 35 33 42 10 14 19 27 44 26 31
Min-Heap − Where the value of the root node is less than or equal to either of its children.
Max-Heap − Where the value of the root node is greater than or equal to either of its children.
Both trees are constructed using the same input and order of arrival.
Step 1 − Create a new node at the end of heap.Step 2 − Assign new value to the node.Step
3 − Compare the value of this child node with its parent.Step 4 − If value of parent is less than
child, then swap them.Step 5 − Repeat step 3 & 4 until Heap property holds.
Note − In Min Heap construction algorithm, we expect the value of the parent node to be less
than that of the child node.
Let's understand Max Heap construction by an animated illustration. We consider the same
input sample that we used earlier.
Step 1 − Remove root node.Step 2 − Move the last element of last level to root.Step 3 −
Compare the value of this child node with its parent.Step 4 − If value of parent is less than child,
then swap them.Step 5 − Repeat step 3 & 4 until Heap property holds.
Hashing is the process of mapping large amount of data item to a smaller table with the help
of a hashing function. The essence of hashing is to facilitate the next level searching method
when compared with the linear or binary search. The advantage of this searching method is its
efficiency to hand vast amount of data items in a given collection (i.e. collection size).
Due to this hashing process, the result is a Hash data structure that can store or retrieve data
items in an average time disregard to the collection size.
Hash Table is the result of storing the hash data structure in a smaller table which incorporates
the hash function within itself. The Hash Function primarily is responsible to map between the
original data item and the smaller table itself. Here the mapping takes place with the help of an
output integer in a consistent range produced when a given data item (any data type) is
provided for storage and this output integer range determines the location in the smaller table
for the data item. In terms of implementation, the hash table is constructed with the help of an
array and the indices of this array are associated to the output integer range.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of edges,
connecting the pairs of vertices. Take a look at the following graph −
In the above graph,
V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}
Vertex− Each node of the graph is represented as a vertex. In the following example, the
labeled circle represents vertices. Thus, A to G are vertices. We can represent them using an
array as shown in the following image. Here A can be identified by index 0. B can be identified
using index 1 and so on.
Edge− Edge represents a path between two vertices or a line between two vertices. In the
following example, the lines from A to B, B to C, and so on represents edges. We can use a
two-dimensional array to represent an array as shown in the following image. Here AB can be
represented as 1 at row 0, column 1, BC as 1 at row 1, column 2 and so on, keeping other
combinations as 0.
Adjacency− Two node or vertices are adjacent if they are connected to each other through an
edge. In the following example, B is adjacent to A, C is adjacent to B, and so on.
Path− Path represents a sequence of edges between the two vertices. In the following example,
ABCD represents a path from A to D.
Basic Operations
Following are basic primary operations of a Graph –
Add Vertex− Adds a vertex to the graph.
Add Edge− Adds an edge between the two vertices of the graph.
Display Vertex− Displays a vertex of the graph.
Audience
This tutorial is designed for Computer Science graduates as well as Software Professionals who
are willing to learn data structures and algorithm programming in simple and easy steps.
After completing this tutorial you will be at intermediate level of expertise from where you can
take yourself to higher level of expertise.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of C programming
language, text editor, and execution of programs, etc.
Array Matrix :
In general, array is a built-in data structure that holds a set of elements of the same type.
Arrays are useful and indispensable in programming.
All numbers are initialized to zeroes by default. That means the above array numbers contain 10
numbers which are all zeroes, even we haven‟t initialized the array yet.
Boolean elements are initialized to false by default.
Then we initialize values for each element of the array like this:
1 numbers[0] = 10;
2 numbers[1] = 500;
3 numbers[2] = 1000;
4 ...
This array holds 5 String objects. And by default, all elements of Object type are initialized to
null.
NOTE: In Java, you can place the brackets [] either after the type or after the variable name.
Hence these declarations are both correct:
1 String[] names = new String[5];
However, it‟s recommended to use the [] after the type for readability: You can easily realize this
is an array of Strings, or that is an array of integer numbers.
You can also declare and initialize elements of an array in one statement. For example:
1 int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
This creates an array with 10 integer numbers which are initialized up declaration. This is a
handy shortcut for declaring arrays whose elements are already known at compile time.
This statement declares and initializes an array of Strings:
2. Multi-dimensional arrays
We can create an array of arrays (2-dimension array). For instance:
1 float[][] matrix = new float[5][3];
6 };
3. Arrays Manipulation
We access elements in the array by index (remember 0-based):
1 String firstColumn = columnNames[0];
This statement takes value of the first element in the String array columnNamesand assigns it to
the variable firstColumn.
This gets the first element in the sampleData array, which returns an array.
The following statement takes the element at 3rd row and 2nd column in the above 2D array:
1 String letter = sampleData[4][3];
3 numbers[4] = 1024;
4 sampleData[4][2] = “xyz”;
A common operation is iterating an array using a loop statement like the for statement. The
following example uses the forloop to iterate over all elements in an array of integer numbers,
and prints value of each element:
4 System.out.println(numbers[i]);
5 }
For arrays of objects you can use the for each syntax to iterate. For example:
1 String[] nameList = {"Tom", "Mary", "Peter", "John", "Adam", "Justin"};
4 System.out.println(aName);
5 }
Besides the fundamental operations like getting and setting, Java provides various functions to
manipulate arrays in theArrays class.
The Arrays is a utility class which can be found in the java.util package. Here are some
noteworthy methods it provides:
asList(): returns a fixed-size list backed by an array.
binarySearch(): searches for a specific value in an array. Returns the index of the element if
found, or -1 if not found. Note that the array must be sorted first.
copyOf(): copies a portion of the specified array to a new one.
copyOfRange(): copies a specified range of an array to a new one.
equals(): compares two arrays to determine if they are equal or not.
fill(): fills same values to all or some elements in an array.
sort(): sorts an array into ascending order.
And other methods you can find in the Arrays class Javadoc.
In addition, the System.arraycopy() is an efficient method for copying elements from one array
to another. Remember using this method instead of writing your own procedure because this
method is very efficient.
So far I have walked you through a tour of arrays in Java. Here‟s the summary for today:
An array is an object.
Elements in an array are accessed by index (0-based).
Advantage of array: very fast access to elements.
Disadvantage of array: fixed length, not appropriate if a dynamic container is required.
The java.util.Arrays class provides useful utility methods for working with arrays such as filling,
searching and sorting.
The System.arraycopy() method provides an efficient mechanism for copying elements from
one array to another.
Algorithms Basics
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a
certain order to get the desired output. Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be implemented in more than one programming
language.
From the data structure point of view, following are some important categories of algorithms –
Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have the following
characteristics −
Unambiguous− Algorithm should be clear and unambiguous. Each of its steps (or phases), and
their inputs/outputs should be clear and must lead to only one meaning.
Input− An algorithm should have 0 or more well-defined inputs.
Output− An algorithm should have 1 or more well-defined outputs, and should match the
desired output.
Finiteness− Algorithms must terminate after a finite number of steps.
Feasibility− Should be feasible with the available resources.
Independent− An algorithm should have step-by-step directions, which should be independent
of any programming code.
Example
Problem − Design an algorithm to add two numbers and display the result.
step 1 − STARTstep 2 − declare three integers a, b & cstep 3 − define values of a & bstep 4 −
add values of a & bstep 5 − store output of step 4 to cstep 6 − print cstep 7 − STOP
Algorithms tell the programmers how to code the program. Alternatively, the algorithm can be
written as –
step 1 − START ADDstep 2 − get values of a & bstep 3 − c ← a + bstep 4 − display cstep 5 −
STOP
In design and analysis of algorithms, usually the second method is used to describe an
algorithm. It makes it easy for the analyst to analyze the algorithm ignoring all unwanted
definitions. He can observe what operations are being used and how the process is flowing.
Algorithm Analysis
Efficiency of an algorithm can be analyzed at two different stages, before implementation and
after implementation. They are the following –
Space Complexity
Space complexity of an algorithm represents the amount of memory space required by the
algorithm in its life cycle. The space required by an algorithm is equal to the sum of the following
two components –
A fixed part that is a space required to store certain data and variables, that are independent of
the size of the problem. For example, simple variables and constants used, program size, etc.
A variable part is a space required by variables, whose size depends on the size of the problem.
For example, dynamic memory allocation, recursion stack space, etc.
Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I)
is the variable part of the algorithm, which depends on instance characteristic I. Following is a
simple example that tries to explain the concept –
Time Complexity
Time complexity of an algorithm represents the amount of time required by the algorithm to run
to completion. Time requirements can be defined as a numerical function T(n), where T(n) can
be measured as the number of steps, provided each step consumes constant time.
Telephone Directory− The telephone directory stores the telephone numbers of people sorted
by their names, so that the names can be searched easily.
Dictionary− The dictionary stores words in an alphabetical order so that searching of any word
becomes easy.
However, in some sorting algorithms, the program requires space which is more than or equal
to the elements being sorted. Sorting which uses equal or more space is called not-in-place
sorting. Merge-sort is an example of not-in-place sorting.
If a sorting algorithm, after sorting the contents, changes the sequence of similar content in
which they appear, it is called unstable sorting.
Stability of an algorithm matters when we wish to maintain the sequence of original elements,
like in a tuple for example.
Important Terms
Some terms are generally coined while discussing sorting techniques, here is a brief
introduction to them –
Increasing Order
Decreasing Order
A sequence of values is said to be in decreasing order, if the successive element is less than
the current one. For example, 9, 8, 6, 4, 3, 1 are in decreasing order, as every next element is
less than the previous element.
Non-Increasing Order
Non-Decreasing Order