Notes EIT
Notes EIT
Notes EIT
BVBCET
[ESSENTIALS OF
INFORMATION TECHNOLOGY]
Client Computer:
A client computer is an individual computer that accesses the information and programs stored on a server as part
of a network environment.
Server Computer:
"Servers" are computer programs running to serve the requests of other programs, the "clients".
1. Microprocessor - This is the brain of your computer. It performs commands and instructions and controls
the operation of the computer.
2. Memory - The RAM in your system is mounted on the motherboard. This is memory that must be powered
on to retain its contents.
3. Drive controllers - The drive controllers control the interface of your system to your hard drives. The
controllers let your hard drives work by controlling their operation. On most systems, they are included on
the motherboard, however you may add additional controllers for faster or other types of drives.
Hard disk drive(s) - This is where your files are permanently stored on your computer. Also, normally, your
operating system is installed here.
CD-ROM drive(s) - This is normally a read only drive where files are permanently stored. There are now
read/write CD-ROM drives that use special software to allow users to read from and write to these drives.
Floppy drive(s) - A floppy is a small disk storage device that today typically has about 1.4 Megabytes of
memory capacity.
Other possible file storage devices include DVD devices, Tape backup devices, and some others
Monitor - This device which operates like a TV set lets the user see how the computer is responding to their
commands.
Keyboard - This is where the user enters text commands into the computer.
Mouse - A point and click interface for entering commands which works well in graphical environments.
Computer Networks:
A computer network or data network is a telecommunications network which allows computers to exchange data. In
computer networks, networked computing devices pass data to each other along network links (data connections).
The connections between nodes are established using either cable media or wireless media. The best-known
computer network is the Internet.
Network computer devices that originate, route and terminate the data are called network nodes. Nodes can include
hosts such as personal computers, phones, servers as well as networking hardware. Two such devices can be said
to be networked together when one device is able to exchange information with the other device, whether or not they
have a direct connection to each other.
Computer networks differ in the transmission media used to carry their signals, the communications protocols to
organize network traffic, the network's size, topology and organizational intent. In most cases, communications
protocols are layered on (i.e. work using) other more specific or more general communications protocols, except for
the physical layer that directly deals with the transmission media.
Create files and store them in one computer, access those files from the other computer(s) connected over
the network
Connect a printer, scanner, or a fax machine to one computer within the network and let other computers of
the network use the machines available over network.
LAN:
A computer network spanned inside a building and operated under single administrative system is generally termed
as Local Area Network (LAN). Usually, LAN covers an organization offices, schools, colleges or universities. Number
of systems connected in LAN may vary from as least as two to as much as 16 million.
LAN provides a useful way of sharing the resources between end users. The resources such as printers, file
servers, scanners, and internet are easily sharable among computers.
MAN:
The Metropolitan Area Network (MAN) generally expands throughout a city such as cable TV network. It can be in the
form of Ethernet,Token-ring, ATM, or Fiber Distributed Data Interface (FDDI).
Metro Ethernet is a service which is provided by ISPs. This service enables its users to expand their Local Area
Networks. For example, MAN can help an organization to connect all of its offices in a city.
Backbone of MAN is high-capacity and high-speed fiber optics. MAN works in between Local Area Network and
Wide Area Network. MAN provides uplink for LANs to WANs or internet.
WAN:
As the name suggests, the Wide Area Network (WAN) covers a wide area which may span across provinces and
even a whole country. Generally, telecommunication networks are Wide Area Network. These networks provide
connectivity to MANs and LANs. Since they are equipped with very high speed backbone, WANs use very expensive
network equipment.
Software is a set of programs, which is designed to perform a well-defined function. A program is a sequence of
instructions written to solve a particular problem.
System Software
Application Software
System Software:
The system software is collection of programs designed to operate, control, and extend the processing capabilities
of the computer itself. System software are generally prepared by computer manufactures. These software products
comprise of programs written in low-level languages which interact with the hardware at a very basic level. System
software serves as the interface between hardware and the end users.
Some examples of system software are Operating System, Compilers, Interpreter, Assemblers etc.
Close to system
Fast in speed
Difficult to design
Difficult to understand
Less interactive
Smaller in size
Difficult to manipulate
Application Software:
Application software products are designed to satisfy a particular need of a particular environment. All software
applications prepared in the computer lab can come under the category of Application software.
Application software may consist of a single program, such as a Microsoft's notepad for writing and editing simple
text. It may also consist of a collection of programs, often called a software package, which work together to
accomplish a task, such as a spreadsheet package.
Payroll Software
Microsoft Word
Microsoft Excel
Microsoft PowerPoint
Close to user
Easy to design
More interactive
Slow in speed
Easy to understand
Hardware and software are mutually dependent on each other. Both of them must work together to make a
computer produce a useful output.
Hardware without set of programs to operate upon cannot be utilized and is useless.
To get a particular job done on the computer, relevant software should be loaded into the hardware
If hardware is the 'heart' of a computer system, then software is its 'soul'. Both are complimentary to each
other.
Operating System:
An operating system (OS) is a collection of software that manages computer hardware resources and provides
common services for computer programs. The operating system is a vital component of the system software in a
computer system.
An operating System (OS) is an intermediary between users and computer hardware. It provides users an
environment in which a user can execute programs conveniently and efficiently.
In technical terms, It is a software which manages hardware. An operating System controls the allocation of
resources and services such as memory, processors, devices and information.
Definition:
An operating system is a program that acts as an interface between the user and the computer hardware and
controls the execution of all kinds of programs.
Memory Management
Processor Management
Device Management
File Management
Security
Job accounting
Memory Management:
Memory management refers to management of Primary Memory or Main Memory. Main memory is a large array of
words or bytes where each word or byte has its own address.
Main memory provides a fast storage that can be access directly by the CPU. So for a program to be executed, it
must in the main memory. Operating System does the following activities for memory management.
Keeps tracks of primary memory i.e. what part of it are in use by whom, what part are not in use.
In multiprogramming, OS decides which process will get memory when and how much.
De-allocates the memory when the process no longer needs it or has been terminated.
Swapping, or paging, between main memory and disk, when disk is too small to hold all current processes.
Address binding of instructions and data to memory addresses can happen at three different stages.
Compile time: If memory location known a priori, absolute (complete) code can be generated; must
recompile code if starting location changes.
Load time: Must generate re-locatable code if memory location is not known at compile time.
Execution time: Binding delayed until run time if the process can be moved during its execution from one
memory segment to another. Need hardware support for address maps (e.g., base and limit registers).
The concept of a logical address space that is bound to a separate physical address space is central to
proper memory management.
Logical and physical addresses are the same in compile-time and load-time address-binding schemes;
logical (virtual) and physical addresses differ in execution-time address-binding scheme.
In MMU scheme, the value in the relocation register is added to every address generated by a user process
at the time it is sent to memory.
The user program deals with logical addresses; it never sees the real physical addresses.
Dynamic Loading:
Dynamic loading is a mechanism by which a computer program can, at run time, load a library (or other binary) into
memory, retrieve the addresses of functions and variables contained in the library, execute those functions or access
those variables, and unload the library from memory.
Features:
Useful when large amounts of code are needed to handle infrequently occurring cases.
No special support from the operating system is required implemented through program design.
Dynamic Linking:
Linking is often referred to as a process that is performed when the executable is compiled, while a dynamic linker is
a special part of an operating system that loads external shared libraries into a running process and then binds those
shared libraries dynamically to the running process. This approach is also called dynamic linking or late linking.
Features:
Small piece of code, stub, used to locate the appropriate memory-resident library routine.
Stub replaces itself with the address of the routine, and executes the routine.
Best-fit: Allocate the smallest hole that is big enough; must search entire list, unless ordered by size.
Produces the smallest leftover hole.
Worst-fit: Allocate the largest hole; must also search entire list. Produces the largest leftover hole.
Note: First-fit and best-fit better than worst-fit in terms of speed and storage utilization.
Fig 7: Example
Fragmentation:
Fragmentation is a phenomenon in which storage space is used inefficiently, reducing capacity or performance and
often both. In many cases, fragmentation leads to storage space being "wasted", and in that case the term also
refers to the wasted space itself.
There are three different but related forms of fragmentation: external fragmentation, internal fragmentation, and data
fragmentation,
External Fragmentation total memory space exists to satisfy a request, but it is not contiguous.
Internal Fragmentation allocated memory may be slightly larger than requested memory; this size
difference is memory internal to a partition, but not being used.
Data Fragmentation - occurs when a collection of data in memory is broken up into many pieces that are
not close together.
Compaction
Shuffle memory contents to place all free memory together in one large block
Fig 8: Example
Paging:
paging is one of the memory management schemes by which a computer stores and retrieves data from the
secondary storage for use in main memory. In the paging memory-management scheme, the operating system
retrieves data from secondary storage in same-size blocks called pages. The main advantage of paging
over memory segmentation is that it allows the physical address space of a process to be non contiguous.
Lets organize physical address spaced (main memory) into equal (small) sized chunks called frames.
And divide logical (virtual) address space into chunks of the same size called pages
The pages of a program can thus be mapped to the available frames in main memory, not necessarily
contiguous
Within each program, each logical address consists of a page number and an offset within the page
A Memory Management Unit (MMU) is put between the CPU address bus and physical memory bus
A MMU register holds the starting physical address of the page table of the process currently running
Presented with a logical address (page number, offset) the MMU accesses the page table to obtain the
physical address (frame number, offset)
Paging Hardware:
Segmentation:
Segmentation is the division of a computer's primary memory into segments or sections. A program is a collection of
segments. A segment is a logical unit such as:
main program,
procedure,
function,
method,
object,
common block,
stack,
Segmentation Hardware:
Process Management:
Process: A process is a program in execution. The execution of a process must progress in a sequential fashion.
Definition of process is following.
A process is defined as an entity which represents the basic unit of work to be implemented in the system.
1 Object Program
Code to be executed.
2 Data
Data to be used for executing the program.
3 Resources
While executing the program, it may require some resources.
4 Status
Verifies the status of the process execution. A process can run to
completion only when all requested resources have been allocated to
the process. Two or more processes could be executing the same
program, each using their own data and resources.
Process States:
As a process executes, it changes state. The state of a process is defined as the current activity of the process.
1 New
The process is being created.
2 Ready
The process is waiting to be assigned to a processor. Ready
processes are waiting to have the processor allocated to them by the
operating system so that they can run.
3 Running
Process instructions are being executed (i.e. The process that is
currently being executed).
4 Waiting
The process is waiting for some event to occur (such as the
completion of an I/O operation).
5 Terminated
The process has finished execution.
State Diagram:
Process scheduling:
The process scheduling is the activity of the process manager that handles the removal of the running process from
the CPU and the selection of another process on the basis of a particular strategy.
Process scheduling is an essential part of a Multiprogramming operating system. Such operating systems allow
more than one process to be loaded into the executable memory at a time and loaded process shares the CPU
using time multiplexing.
Scheduling Queues
Scheduling queues refers to queues of processes or devices. When the process enters into the system, then this
process is put into a job queue. This queue consists of all processes in the system. The operating system also
maintains other queues such as device queue. Device queue is a queue for which multiple processes are waiting for
a particular I/O device. Each device has its own device queue.
Ready queue
Device queue
A newly arrived process is put in the ready queue. Processes waits in ready queue for allocating the CPU. Once the
CPU is assigned to a process, then that process will execute. While executing the process, any one of the following
events can occur.
The process could issue an I/O request and then it would be placed in an I/O queue.
The process could create new sub process and will wait for its termination.
The process could be removed forcibly from the CPU, as a result of interrupt and put back in the ready
queue.
Two state process models refer to running and non-running states which are described below.
1 Running
When new process is created by Operating System that process
enters into the system as in the running state.
2 Not Running
Processes that are not running are kept in queue, waiting for their
turn to execute. Each entry in the queue is a pointer to a particular
process. Queue is implemented by using linked list. Use of
dispatcher is as follows. When a process is interrupted, that process
is transferred in the waiting queue. If the process has completed or
aborted, the process is discarded. In either case, the dispatcher then
selects a process from the queue to execute.
Schedulers:
Schedulers are special system softwares which handles process scheduling in various ways.Their main task is to
select the jobs to be submitted into the system and to decide which process to run. Schedulers are of three types
It is also called job scheduler. Long term scheduler determines which programs are admitted to the system for
processing. Job scheduler selects processes from the queue and loads them into memory for execution. Process
loads into the memory for CPU scheduling. The primary objective of the job scheduler is to provide a balanced mix
of jobs, such as I/O bound and processor bound. It also controls the degree of multiprogramming. If the degree of
multiprogramming is stable, then the average rate of process creation must be equal to the average departure rate
of processes leaving the system.
On some systems, the long term scheduler may not be available or minimal. Time-sharing operating systems have
no long term scheduler. When process changes the state from new to ready, then there is use of long term
scheduler.
It is also called CPU scheduler. Main objective is increasing system performance in accordance with the chosen set
of criteria. It is the change of ready state to running state of the process. CPU scheduler selects process among the
processes that are ready to execute and allocates CPU to one of them.
Short term scheduler also known as dispatcher, execute most frequently and makes the fine grained decision of
which process to execute next. Short term scheduler is faster than long term scheduler.
Medium term scheduling is part of the swapping. It removes the processes from the memory. It reduces the degree
of multiprogramming. The medium term scheduler is in-charge of handling the swapped out-processes.
Running process may become suspended if it makes an I/O request. Suspended processes cannot make any
progress towards completion. In this condition, to remove the process from memory and make space for other
process, the suspended process is moved to the secondary storage. This process is called swapping, and the
process is said to be swapped out or rolled out. Swapping may be necessary to improve the process mix.
Scheduling Algorithms:
Priority Scheduling
P0 0-0=0
P1 5-1=4
P2 8-2=6
P3 16 - 3 = 13
Impossible to implement
Processer should know in advance how much time process will take.
P0 3-0=3
P1 0-0=0
P2 16 - 2 = 14
P3 8-3=5
Each process is assigned a priority. Process with highest priority is to be executed first and so on.
Processes with same priority are executed on first come first serve basis.
Priority can be decided based on memory requirements, time requirements or any other resource
requirement.
P0 9-0=9
P1 6-1=5
P2 14 - 2 = 12
P3 0-0=0
Once a process is executed for given time period. Process is preempted and other process executes for
given time period.
P0 (0-0) + (12-3) = 9
P1 (3-1) = 2
P3 (9-3) + (17-12) = 11
File: A file is a collection of related information defined by its creator. Files represent programs (both source and
object forms) and data.
Naming Convention:
drive name
directory name(s)
file name
Extension
File Management:
The operating system is responsible for the following activities in connections with file management:
Use a directory to describe the location of all files plus their attributes
The file manager handles all files on secondary storage media. To perform these tasks, file management must:
maintain a list telling where exactly each file is stored, how many sectors on the medium it occupies, and in
which order those sectors make up the file
provide users and programs with simple commands for file handling
File Operations:
Create
Delete
Open
Close
Read
Write
Typical Operations:
Retrieve All: Retrieve all the records of a file. This operation will be required for an application that must
process all the information in the file at one time.
Retrieve One: This operation requires the retrieval of just a single record. Interactive, transaction-oriented
applications need this operation
Retrieve Next: This operation requires the retrieval of the record that is next in some logical sequence to
the most recently received record. for example : filling in forms
Retrieve Previous : Similar to retrieve next, but in this case the record that is previous to the currently
accessed record is retrieved
Insert_One: Insert a new record into the file. It may be necessary that the new record fit into a particular
position to preserve a sequencing of the file.
Delete_One: delete an existing record. Certain linkages or other data structures may need to be updated to
preserve the sequencing of the file.
Update_One: Retrieve a record, update one or more of its fields, and rewrite updated record back into the
file.
Retrieve_Few: Retrieve a number of records. For example, an application may wish to retrieve all records
that satisfy a certain set of criteria.
Access Rights:
None
User is not allowed to read the user directory that includes the file
Knowledge
User can only determine that the file exists and who its owner is
Execution
The user can load and execute a program but cannot copy it
Reading
The user can read the file for any purpose, including copying and execution
Appending
The user can add data to the file but cannot modify or delete any of the files contents
Updating
The user can modify, deleted, and add to the files data. This includes creating the file, rewriting it,
and removing all or part of the data
Changing protection
Deletion
Allocation Methods:
chained allocation
indexed allocation
Easy to implement.
Chained Allocation:
No external fragmentation
Indexed Allocation:
Each file has its own index block which stores the addresses of disk space occupied by the file.
OOPS concepts:
What is OOP Object Oriented Programming)?
OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a
different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in
OOP is grouped as self sustainable "objects". Hence, you gain reusability by means of four main object-oriented
programming concepts.
In order to clearly understand the object orientation model, lets take your hand as an example. The hand is a
class. Your body has two objects of the type "hand", named "left hand" and "right hand". Their main functions are
controlled or managed by a set of electrical signals sent through your shoulders (through an interface). So the
shoulder is an interface that your body uses to interact with your hands. The hand is a well-architected class. The
hand is being reused to create the left hand and the right hand by slightly changing the properties of it.
What is an Object?
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object
performs defines the object's behavior. For example, the Hand (object) can grip something, or a Student (object) can
give their name or address.
In pure OOP terms an object is an instance of a class.
OOPs (Object Oriented Programming System):
Java oops concepts Object mean a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software development and
maintenance by providing some concepts:
1. Object
2. Class
3. Inheritance
4 .Polymorphism
5. Abstraction
6. Encapsulation
1. Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc.
It can be physical and logical.
2. Class
Example:-
public class Sudent{
String Name;
int age;
String Branch;
void getinput()
{
}
void display()
{
}
public static void main(String args[])
{
}
}
Inheritance:
Inheritance can be defined as the process where one object acquires the properties of another. With the use of
inheritance the information is made manageable in a hierarchical order.
The ability of a new class to be created, from an existing class by extending it, is called inheritance.
Example :-
class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
Now, based on the above example, In Object Oriented terms, the following are true:
Animal is the super class of Mammal class.
Animal is the super class of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes
Polymorphism:
When one task is performed by different ways i.e. known as polymorphism. For example: to convense the customer
differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Polymorphism is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to
request that the same operations be performed by a wide range of different types of things.
At times, I used to think that understanding Object Oriented Programming concepts have made it difficult since they
have grouped under four main concepts, while each concept is closely related with one another. Hence one has to be
extremely careful to correctly understand each concept separately, while understanding the way each related with
other concepts.
In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator
overloading, and method overriding,
What is Method Overloading?
Method overloading is the ability to define several methods all with the same name.
In above example I have overloaded the plus operator for adding two complex numbers. There the two properties
named Real and Imaginary has been declared exposing only the required get method, while the objects constructor
is demanding for mandatory real and imaginary values with the user defined constructor of the class.
Encapsulation:
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and
abstraction.
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public
methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields
within the class. For this reason, encapsulation is also referred to as data hiding.
Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by
other code defined outside the class. Access to the data and code is tightly controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others
who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
Example:
return age;
return name;
return idNum;
age = newAge;
name = newName;
idNum = newId;
The public methods are the access points to this class' fields from the outside java world. Normally, these methods
are referred as getters and setters. Therefore any class that wants to access the variables should access them
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
Benefits of Encapsulation:
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data. A class can change the data type of a field
and users of the class do not need to change any of their code.
INTRODUCTION TO JAVA:
Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java
runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a
This reference will take you through simple and practical approach while learning Java Programming language.
Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively. Java is
Java is:
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the
Object model.
Platform independent: Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This
byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is
being run.
Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be
easy to master.
Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
Architectural-neutral : Java compiler generates an architecture-neutral object file format which makes the
compiled code to be executable on many processors, with the presence of Java runtime system.
Portable: Being architectural-neutral and having no implementation dependent aspects of the specification
makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary which is a
POSIX subset.
Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time
Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks
simultaneously. This design feature allows developers to construct smoothly running interactive
applications.
Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an incremental and
High Performance: With the use of Just-In-Time compilers, Java enables high performance.
Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry extensive amount of run-time information that can be used
When we consider a Java program it can be defined as a collection of objects that communicate via invoking each
other's methods. Let us now briefly look into what do class, object, methods and instance variables mean.
Object - Objects have states and behaviours. Example: A dog has states - colour, name, breed as well as
Class - A class can be defined as a template/ blue print that describe the behaviours/states that object of its
type support.
Methods - A method is basically a behaviour. A class can contain many methods. It is in methods where the
logics are written, data is manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of instance variables. An object's state is created by the
Variables are nothing but reserved memory locations to store values. This means that when you create a variable
Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or
There are eight primitive data types supported by Java. Primitive data types are predefined by the language and
named by a keyword. Let us now look into detail about the eight primitive data types.
Byte:
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times
Short:
Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int
Default value is 0.
int:
Int is generally used as the default data type for integral values unless there is a concern about memory.
Long:
Float:
Float is mainly used to save memory in large arrays of floating point numbers.
Float data type is never used for precise values such as currency.
Double:
This data type is generally used as the default data type for decimal values, generally the default choice.
Double data type should never be used for precise values such as currency.
Boolean:
This data type is used for simple flags that track true/false conditions.
char:
Reference variables are created using defined constructors of the classes. They are used to access
objects. These variables are declared to be of a specific type that cannot be changed. For example,
Class objects, and various type of array variables come under reference data type.
A reference variable can be used to refer to any object of the declared type or any compatible type.
Java language supports few special escape sequences for String and char literals as well. They are:
\n Newline
\b Backspace
\s Space
\t tab
\\ backslash
JAVA STRINGS:
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming
The Java platform provides the String class to create and manipulate strings.
Creating Strings:
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case,
"Hello world!'.
As with any other object, you can create String objects by using the new keyword and a constructor. The String
class has eleven constructors that allow you to provide the initial value of the string using different sources, such as
an array of characters.
System.out.println( helloString );
hello.
Note: The String class is immutable; so that once it is created a String object cannot be changed. If there is a
necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String
Builder Classes.
String Length:
Methods used to obtain information about an object are known as access or methods. One access or method that
you can use with strings is the length() method, which returns the number of characters contained in the string
object.
After the following two lines of code have been executed, len equals 17:
String Length is : 17
Concatenating Strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method
"Hello, world!"
You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent
class method, format(), that returns a String object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a
String fs;
System.out.println(fs);
String Methods:
1
char charAt(int index)
2
int compareTo(Object o)
3
int compareTo(String anotherString)
4
int compareToIgnoreCase(String str)
5
String concat(String str)
6
boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as the specified
StringBuffer.
7
static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
8
static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
9
boolean endsWith(String suffix)
10
boolean equals(Object anObject)
11
boolean equalsIgnoreCase(String anotherString)
12
byte getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into
13
byte[] getBytes(String charsetName
Encodes this String into a sequence of bytes using the named charset, storing the result into a new
byte array.
14
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
15
int hashCode()
16
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
17
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search
18
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
19
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the
specified index
20
String intern()
21
int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
22
int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching
23
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
24
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching
25
int length()
26
boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
27
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
28
boolean regionMatches(int toffset, String other, int ooffset, int len)
29
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
30
String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given
replacement.
31
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given
replacement.
32
String[] split(String regex)
33
String[] split(String regex, int limit)
34
boolean startsWith(String prefix)
35
boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
36
CharSequence subSequence(int beginIndex, int endIndex)
37
String substring(int beginIndex)
38
String substring(int beginIndex, int endIndex)
39
char[] toCharArray()
40
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
41
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
42
String toString()
43
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
44
String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
45
String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
46
static String valueOf(primitive data type x)
JAVA ARRAYS:
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same
type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of
array the variable can reference. Here is the syntax for declaring an array variable:
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[]comes from the C/C++
Example:
or
Creating Arrays:
You can create an array by using the new operator with the following syntax:
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0
to arrayRefVar.length-1.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns
Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of the elements in an
array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
double total = 0;
total += myList[i];
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the
Example:
The following code displays all the elements in the array myList:
System.out.println(element);
1.9
2.9
3.4
3.5
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the
You can invoke it by passing an array. For example, the following statement invokes the printArray method to display
3, 1, 2, 6, 4, and 2:
A method may also return an array. For example, the method shown below returns an array that is the reversal of
another array:
result[j] = list[i];
return result;
filling array elements. These methods are overloaded for all primitive types.
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary
search algorithm. The array must be sorted prior to making this call. This returns index of the search
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered
equal if both arrays contain the same number of elements, and all corresponding pairs of elements in
the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by
Assigns the specified int value to each element of the specified array of ints. Same method could be
used by all other primitive data types (Byte, short, Int etc.)
Sorts the specified array of objects into ascending order, according to the natural ordering of its
elements. Same method could be used by all other primitive data types ( Byte, short, Int, etc.)
JAVA LOOPS:
There may be a situation when we need to execute a block of code several number of times, and is often referred to
as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will
continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is
false, the loop body will be skipped and the first statement after the while loop will be executed.
Example:
public class Test {
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
Syntax:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once
before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute
again. This process repeats until the Boolean expression is false.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific
number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the update statement. This
statement allows you to update any loop control variables. This statement can be left blank, as long as a
semicolon appears after the Boolean expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the
for loop terminates.
Example:
public class Test {
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch
statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of code after the
block.
Syntax:
break;
Example:
public class Test {
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
10
20
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to
the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax:
continue;
Example:
public class Test {
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
10
20
40
50
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
Local variables: Variables defined inside methods, constructors or blocks are called local variables. The
variable will be declared and initialized within the method and the variable will be destroyed when the
method has completed.
Instance variables: Instance variables are variables within a class but outside any method. These variables
are instantiated when the class is loaded. Instance variables can be accessed from inside any method,
constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any method, with the static
keyword.
Access Specifiers:
Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and methods in
Java.These Specifiers determine whether a field or method in a class, can be used or invoked by another method in
another class or sub-class. Access Specifiers can be used to restrict access. Access Specifiers are an integral part of
object-oriented programming
In java we have four Access Specifiers and they are listed below.
1.public
2.private
3.protected
4. default(no specifier)
// ...
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public getter methods are present in the
class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected,
however methods and fields in a interface cannot be declared protected.
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}
A variable or method declared without any access control modifier is available to any other class in the same
package. The fields in an interface are implicitly public static final and the methods in an interface are by default
public
boolean processOrder() {
return true;
}
Constructors:
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that
is why it is known as constructor
class Car
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}
2. Parameterized constructor
Method overloading:
If two or more method in a class has same name but different parameters, it is known as method overloading.
Method overloading is one of the ways through which java supports polymorphism. Method overloading can be done
by changing number of arguments or by changing the data type of arguments. If two or more method have same
name and same parameter list but differs in return type are not said to be overloaded method
class Calculate
{
void sum (int a, int b)
{
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
System.out.println("sum is"+(a+b));
}
Public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6, 3.8); //sum(float a, float b) is called.
}
}
Static Keyword:
The static keyword in java is used for memory management mainly. We can apply java static keyword with
variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
3. block
4. nested class
The static variable can be used to refer the common property of all objects (that is not unique for each
object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
class VariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Output:
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
class Languages {
public static void main(String[] args) {
display();
}
1. Describe the relationship between an object and its defining class. How do you declare a class? How do you
declare an object reference variable?
ANS: The object is a instance of the class.It has all the properties of the class.An object is used to invoke all the
methods present in the code.
Declaration of class :-
Class class_name
{
data_types names;
}
Example:
Int main()
{
Student s1;
}
2. How do you create an object? How do you declare and create an object in one statement?
3. When gasoline is $100 per barrel, then the consumers price at the pump is between $3.50 and $4.00 per gallon.
Create a class named GasPrices . Its main() method holds an integer variable named pricePerBarrel to which you will
assign a value entered by a user at the keyboard. Create a method to which you pass pricePerBarrel . The method
displays the range of possible prices per gallon. For example, if gas is $120 per barrel, then the price at the pump
should be between $4.20 and $4.80. Save the application as GasPrices.java.
package javaapplication13;
import java.util.Scanner;
b=priceperbarrel*4;
{
double priceperbarrel;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the price of gas per barrel");
priceperbarrel=sc.nextDouble();
price(priceperbarrel);
}
4. Create a class named FormLetterWriter that includes two overloaded methods named displaySalutation() . The
first method takes one String parameter that represents a customers last name, and it displays the salutation Dear
Mr. or Ms. followed by the last name. The second method accepts two String parameters that represent a first and
last name, and it displays the greeting Dear followed by the first name, a space, and the last name. After each
salutation, display the rest of a short business letter: Thank you for your recent order. Write a main() method that
tests each overloaded method. Save the file as FormLetterWriter.java
package javaapplication13;
void displaySalutation(String a)
{
System.out.println("Dear Mr.or Ms "+a);
disp();
void disp()
{
System.out.println("\n");
}
class apply
{
}
}
5. Create class SavingsAccount. Use a static variable annualInterestRate to store the annual interest rate for all
account holders. Each object of the class contains a private instance variable savingsBalanceindicating the amount
the saver currently has on deposit. Provide method calculateMonthlyInterest to calculate the monthly interest by
multiplying the savingsBalance by annualInterestRate divided by 12 this interest should be added to savingsBalance.
Provide a static method modifyInterestRate that sets theannualInterestRate to a new value. Write a program to test
class SavingsAccount. Instantiate two savingsAccount objects, saver1 and saver2, with balances of $2000.00 and
$3000.00, respectively. Set annualInterestRate to 4%, then calculate the monthly interest and print the new balances
for both savers. Then set the annualInterestRate to 5%, calculate the next month's interest and print the new
balances for both savers.
package javaapplication13;
import java.util.Scanner;
void calculateMonthlyInterest()
{
a= savingsBalance*annualInterestRate/12;
savingsBalance=savingsBalance+a;
void disp()
{
System.out.println(savingsBalance);
void initializebalance()
{
System.out.println("Enter the balance amount");
savingsBalance=sc.nextDouble();
}
}
class apply1
{
* First difference between method vs constructor in Java is that name of constructor must be same with name of
the Class but there is no such requirement for method in Java. methods can have any arbitrary name in Java.
* Second difference between method and constructor in Java is that constructor doesn't have any return type but
method has return type and return something unless its void.
* Third difference between constructor and method in Java is that Constructors are chained and they are called in a
particular order, there is no such facility for methods.
7. How do we invoke a constructor? What is meant by constructor overloading? What is meant by method
overloading?
The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor
for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object
is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers
and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the
base class completes first and constructor for the most derived class completes last.
class A {
A() {
System.out.print("A");
}
}
class B extends A {
B() {
System.out.print("B");
}
}
class C extends B {
C() {
System.out.print("C");
}
}
like methods, constructors can also be overloaded. We will see constructor overloading with the help of an
example using this() and parameterized constructor. Constructor overloading is way of having more than one
constructor which does different-2 tasks.
Example:
package beginnersbook.com;
class TestOverloading
{
public static void main(String args[])
{
//This object creation would call the default constructor
StudentData myobj = new StudentData();
Data Structures
Introduction:
In computer science, a data structure is a particular way of organizing data in a computer so that it can be used
efficiently.
Data Structures is about rendering data elements in terms of some relationship, for better organization and storage.
For example, we have data player's name "Virat" and age 26. Here "Virat" is of String data type and 26 is of integer
data type. We can organize this data as a record like Player record. Now we can collect and store player's records in
a file or database as a data structure. For example: "Dhoni" 30, "Gambhir" 31, "Sehwag" 33
In simple language, Data Structures are structures programmed to store ordered data, so that various operations can
be performed on it easily.
As we discussed above, anything that can store data can be called as a data strucure, hence Integer, Float, Boolean,
Char etc, all are data structures. They are known as Primitive Data Structures.
Then we also have some complex Data Structures, which are used to store large and connected data. Some
example of Abstract Data Structure are :
Linked List
Tree
Graph
Stack, Queue etc.
All these data structures allow us to perform different operations on data. We select these data structures based on
which type of operation is required. We will look into these data structures in more details in our later lessons.
Stack:
Stack is a linear data structure which follows a particular order in which the operations are performed. The
order may be LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the stack:
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the
stack is empty, then it is said to be an Underflow condition.
Peek: Get the topmost item.
-1 Stack is Empty
Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default
constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its
own.
Apart from the methods inherited from its parent class Vector, Stack defines following methods:
1 boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the
stack contains elements.
2 Object peek( )
Returns the element on the top of the stack, but does not remove it.
3 Object pop( )
Returns the element on the top of the stack, removing it in the process.
import java.util.*;
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
Note: Implementation is not there for syllabus. It is just for your reference how it work in coding.
Queue:
Queue is also an abstract data type or a linear data structure, in which the first element is inserted from one end
called REAR(also called tail), and the deletion of exisiting element takes place from the other end called
as FRONT(also called head). This makes queue as FIFO data structure, which means that element inserted first will
also be removed first.
The process to add an element into queue is called Enqueue and the process of removal of an element from queue
is called Dequeue.
1. Like Stack, Queue is also an ordered list of elements of similar data types.
3. Once a new element is inserted into the Queue, all the elements inserted before the new element in the
4. peek( ) function is oftenly used to return the value of first element without dequeuing it.
Applications of Queue:
Queue, as the name suggests is used whenever we need to have any group of objects in an order in which the first
one coming in, also gets out first while the others wait for there turn, like in the following scenarios :
1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until a
3. Handling of interrupts in real-time systems. The interrupts are handled in the same order as they arrive, First
Implementation of Queue:
Queue can be implemented using an Array, Stack or Linked List. The easiest way of implementing a queue is by
using an Array. Initially the head(FRONT) and the tail(REAR) of the queue points at the first index of the array
(starting the index of array from 0). As we add elements to the queue, the tail keeps on moving ahead, always
pointing to the position where the next element will be inserted, while the head remains at the first index.
When we remove element from Queue, we can follow two possible approaches (mentioned [A] and [B] in above
diagram). In [A] approach, we remove the element at head position, and then one by one move all the other elements
on position forward. In approach [B] we remove the element from head position and then move head to the next
position.
In approach [A] there is an overhead of shifting the elements one position forward every time we remove the first
element. In approach [B] there is no such overhead, but whener we move head one position ahead, after removal of
first element, the size on Queue is reduced by one space each time.
Linked list
Priority queue
1) LinkedList Implementation-
import java.util.*;
public class QueueDemo {
static String newLine = System.getProperty("line.separator");
public static void main(String[] args) {
queue.add("Javascript");
queue.add("HTML5");
queue.add("Hadoop");
//.element() returns the current element in the queue, here when "java" is removed
//.peek() just returns the current element in the queue, null if empty
//Here it will print Javascript as .NET is removed above
System.out.println("retrieve element, null is empty " + queue.peek() + newLine);
}
}
Output-
Queue in Java
---------------------------
Adding items to the Queue
2) PriorityQueue Implementation
import java.util.*;
class TestCollection12{
public static void main(String args[]){
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
queue.remove();
queue.poll();
}
}
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
Linked list:
A linked list is a data structure consisting of a group of nodes which together represent a sequence.
Under the simplest form, each node is composed of data and a reference (in other words, a link) to the next node in
the sequence; more complex variants add additional links. This structure allows for efficient insertion or removal of
elements from any position in the sequence.
Each element (we will call it a node) of a list is comprising of two items - the data and a reference to the next node.
The last node has a reference to null. The entry point into a linked list is called the head of the list. It should be noted
that head is not a separate node, but the reference to the first node. If the list is empty then the head is a null
reference.
A linked list is a dynamic data structure. The number of nodes in a list is not fixed and can grow and shrink on
demand. Any application which has to deal with an unknown number of objects will need to use a linked list.
Another important type of a linked list is called a circular linked list where last node of the list points back to the first
node (or the head) of the list.
addFirst
The method creates a node and prepends it at the beginning of the list.
Traversing
Start with the head and access each node until you reach null. Do not change the head reference.
addLast
The method appends the node to the end of the list. This requires traversing, but make sure you stop at the last node
Inserting "after"
Find a node containing "key" and insert a new node after it. In the picture below, we insert a new node after "e":
Inserting "before"
Find a node containing "key" and insert a new node before that node. In the picture below, we insert a new node
before "a":
Deletion
Find a node containing "key" and delete it. In the picture below we delete a node containing "A"
import java.util.*;
public class TestCollection7{
public static void main(String args[]){
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:Ravi
Vijay
Ravi
Ajay
Tree:
A tree is a nonlinear data structure, compared to arrays, linked lists, stacks and queues which are linear data
structures.
A tree can be empty with no nodes or a tree is a structure consisting of one node called the root and zero or one or
more sub trees.
A is a parent of B, C, D,
B is called a child of A.
on the other hand, B is a parent of E, F, K
Each node can have arbitrary number of children. Nodes with no children are called leaves, or external nodes. In the
above picture, C, E, F, L, G are leaves. Nodes, which are not leaves, are called internal nodes. Internal nodes have at
least one child.
Nodes with the same parent are called siblings. In the picture, B, C, D are called siblings. The depth of a node is the
number of edges from the root to the node. The depth of K is 2. The height of a node is the number of edges from
the node to the deepest leaf. The height of B is 2. The height of a tree is a height of a root.
Binary Tree:
A binary tree in which each node has exactly zero or two children is called a full binary tree. In a full tree, there are
no nodes with exactly one child.
A complete binary tree is a tree, which is completely filled, with the possible exception of the bottom level, which is
filled from left to right. A complete binary tree of the height h has between 2h and 2(h+1)-1 nodes.
A binary search tree is a rooted binary tree, whose internal nodes each store a key (and optionally, an associated
value) and each have two distinguished sub-trees, commonly denoted left and right. The tree additionally satisfies the
binary search tree property, which states that the key in each node must be greater than all keys stored in the left
sub-tree and smaller than all keys in right sub-tree.
Operations on a BST:
Searching;
Searching a binary search tree for a specific key can be a recursive or an iterative process.
We begin by examining the root node. If the tree is null, the key we are searching for does not exist in the tree.
Otherwise, if the key equals that of the root, the search is successful and we return the node. If the key is less than
that of the root, we search the left sub tree. Similarly, if the key is greater than that of the root, we search the right sub
tree. This process is repeated until the key is found or the remaining sub tree is null. If the searched key is not found
before a null sub tree is reached, then the item must not be present in the tree.
Insertion:
Insertion begins as a search would begin; if the key is not equal to that of the root, we search the left or right sub
trees as before. Eventually, we will reach an external node and add the new key-value pair (here encoded as a record
'newNode') as its right or left child, depending on the node's key. In other words, we examine the root and recursively
insert the new node to the left sub tree if its key is less than that of the root, or the right sub tree if its key is greater
than or equal to the root.
Deletion:
Deleting a node with no children: simply remove the node from the tree.
Deleting a node with one child: remove the node and replace it with its child.
Deleting a node with two children: call the node to be deleted N. Do not delete N. Instead, choose either
its in-order successor node or its in-order predecessor node, R. Copy the value of R to N, then recursively call
delete on R until reaching one of the first two cases. If you choose in-order successor of a node, as right sub
tree is not NIL (Our present case is node has 2 children), then its in-order successor is node with least value in
its right sub tree, which will have at a maximum of 1 sub tree, so deleting it would fall in one of first 2 cases.
Traversal:
Once the binary search tree has been created, its elements can be retrieved in-order by recursively traversing the left
sub tree of the root node, accessing the node itself, then recursively traversing the right sub tree of the node,
continuing this pattern with each node in the tree as it's recursively accessed.
2. Traverse the left sub tree by recursively calling the pre-order function.
3. Traverse the right sub tree by recursively calling the pre-order function.
Pre-order: F, B, A, D, C, E, G, I, H
In-order (symmetric)
1. Traverse the left sub tree by recursively calling the in-order function
3. Traverse the right sub tree by recursively calling the in-order function
In-order: A, B, C, D, E, F, G, H, I
Post-order
1. Traverse the left sub tree by recursively calling the post-order function.
2. Traverse the right sub tree by recursively calling the post-order function.
Post-order: A, C, E, D, B, H, I, G, F
INHERITANCE:
Inheritance is a feature that is present in many object-oriented languages such as C++, Eiffel, Java, Ruby, and
Smalltalk, but each language implements it in its own way.
Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an
application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can
designate that the new class should inherit the members of an existing class. This existing class is called
the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal
hence dog IS-A animal as well and so on.
A class can be derived from more than one classes, which means it can inherit data and functions from multiple base
classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list
names one or more base classes and has the form:
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined
class. If the access-specifier is not used, then it is private by default.
Syntax:-
class Base
{
};
class Derived: public Base
{
};
Example:
#include <iostream>
using namespace std;
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
}
Derived Classes:-
Inheritance is a feature of an object-oriented language that allows classes or objects to be defined as extensions or
Specializations of other classes or objects. In C++, classes inherit from other classes. Inheritance is useful when a project contains many
similar, but not identical, types of objects. In this case, the task of the programmer/software engineer is to find commonality in this set of
similar objects, and create a class that can serve as an archetype for this set of classes. 1.1.2
Examples
Squares, triangles, circles, and hexagons are all 2D shapes; hence a Shape class could be an archetype.
Faculty, administrators, office assistants, and technical support staff are all employees, so an Employee class could be an archetype.
Cars, trucks, motorcycles, and buses are all vehicles, so a Vehicle class could be an archetype. When this type of relationship exists
among classes, it is more efficient to create a class hierarchy rather than replicating member functions and p
When this type of relationship exists among classes, it is more efficient to create a class hierarchy rather than replicating member functions
and properties in each of the classes. Inheritance provides the mechanism for achieving this.
A derived class inherits all base class methods with the following exceptions:
Constructors, destructors and copy constructors of the base class.
Overloaded operators of the base class.
The friend functions of the base class.
. The derived class does not have access to the base class's private members.
The derived class has access to all public and protected members of the base class.
The friend functions and friend classes of the base class are not inherited.
Modes of Inheritance:
There are three types of inheritance in C++.
Private inheritance
Public inheritance
Protected inheritance
The access specifier private is not accessible outside the class. The access specifier publicis accessible outside the
class. The access specifier protected is accessible in the derived class with some restrictions, the explanation is
given later.
1. Private inheritance
In the derived class, the reserved word private is optional before the base class but for a good programming practice
it is a good idea to use it. Otherwise, it will be considered as private by default.
A member declared with the access specifier private could be accessed only be members of a class where it is
defined. The derived class is restricted to the private section.
For example
derived_calss:private base_class
{ };
Or
derived_class:base_class
{ };
2. Public inheritance
This type of inheritance must be explicitly mentioned. Instead of private, which is by default, simply use
public.
For example
Derive_class: public base_class
{};
3. Protected inheritance
The word protected in the derived class means that if another class is derived from this current derived class that is
derived_derived class, the protected members in the base class will be private in the first derived class instead of
public. This prohibits the derived_derived class from being access to the protected members of the base class.
that when a derived object is destroyed, the destructor it contains is called first, followed by the base class destructor,
if it exists.
Types of Inheritance:
In C++, we have 5 different types of Inheritance. Namely,
Single Inheritance
Multiple Inheritance
Hierarchical Inheritance
Multilevel Inheritance
1) Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from one base class.
2) Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from multiple base
class(es).
3) Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherit from one base
class.
4) Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class for other
classes.
5) Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other four types of
inheritance.
Inheritance guidelines:
We know that inheritance is a relationship that is a way of relating two classes so that one class is capable of using
another class members without redefining them. Anything that is associated with an access specfier public is
accessible or visible to all derived classes of a base class. The information given to and taken from the member
function of the same access specifier is accessible by code outside the class. The next specifier comes private, which
is known as the highest level of data hidng. The private members of the base or super class remain inaccessible
even to the derived class or sub class. The third and last access specifier is the protected. Data member and member
function associated with this access specifier can be inherited by the sub class or child class or derived class. With
two objects of the same class, they are not allowed to use each other data member of the protected access specifier.
Both will have the same names with different data.
It is to be noted that when an object of a derived class is created, if there exist a constructor in the base class, it will
be called first, followed by the derived class constructor. It is also to be noted.
POLYMORPHISM:
The word polymorphism means having many forms, Poly" means "many" and "morph" means "form". Polymorphism
is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object.
Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different function to be executed depending
Example:
Consider the following example where a base class has been derived by other two classes:
#include <iostream>
class Shape {
protected:
public:
width = a;
height = b;
int area()
return 0;
};
public:
int area ()
};
public:
int area ()
};
int main( )
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec;
shape->area();
shape = &tri;
shape->area();
return 0;
When the above code is compiled and executed, it produces the following result:
The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the
version defined in the base class. This is called static resolution of the function call, or static linkage - the function
call is fixed before the program is executed. This is also sometimes called early binding because the area()
But now, let's make a slight modification in our program and precede the declaration of area() in the Shape class
class Shape {
protected:
public:
width = a;
height = b;
return 0;
};
After this slight modification, when the previous example code is compiled and executed, it produces the following
result:
This time, the compiler looks at the contents of the pointer instead of it's type. Hence, since addresses of objects of
tri and rec classes are stored in *shape the respective area() function is called.
As you can see, each of the child classes has a separate implementation for the function area(). This is
how polymorphism is generally used. You have different classes with a function of the same name, and even the
Function Overloading:
Function overloading in C++: Function overloading means two or more functions can have the same name but either
the number of arguments or the data type of arguments has to be different. Return type has no role because function
will return a value when it is called and at compile time compiler will not be able to determine which function to call. In
the first example in our code we make two functions one for adding two integers and other for adding two floats but
they have same name and in the second program we make two functions with identical names but pass them
different number of arguments. Function overloading is also known as compile time polymorphism.
#include <iostream>
int main()
{
long a, b, x;
float c, d, y;
x = add(a, b);
y = add(c, d);
return 0;
}
sum = x + y;
return sum;
}
sum = x + y;
return sum;
}
In the above program, we have created two functions "add" for two different data types you can create more than two
functions with same name according to requirement but making sure that compiler will be able to determine which
one to call. For example you can create add function for integers, doubles and other data types in above program. In
these functions you can see the code of functions is same except data type, C++ provides a solution to this problem
we can create a single function for different data types which reduces code size which is via templates.
Function Overriding:
If we inherit a class into the derived class and provide a definition for one of the base class's function again inside the
derived class, then that function is said to be overridden, and this mechanism is called Function Overriding
1. Inheritance should be there. Function overriding cannot be done within a class. For this we require a derived
2. Function that is redefined must have exactly the same declaration in both base and derived class, that
means same name, same return type and same parameter list.
class Base
public:
void show()
};
public:
void show()
In this example, function show() is overridden in the derived class. Now let us study how
Connecting the function call to the function body is called Binding. When it is done before the program is run, its
class Base
public:
void shaow()
};
public:
void show()
int mian()
d.show();
In the above example, we are calling the overrided function using Base class and Derived class object. Base class
object will call base version of the function and derived class's object will call the derived version of the function.
But when we use a Base class's pointer or reference to hold Derived class's object, then Function call Binding gives
class Base
public:
void shaow()
};
public:
void show()
int mian()
b = &d;
In the above example, although, the object is of Derived class, still Base class's method is called. This happens due
to Early Binding.
Compiler on seeing Base class's pointer, set call to Base class's show() function, without knowing the actual object
type.
Compile-time binding is to associate a functions name with the entry point of the function at compile time.
Example:
#include<iostream>
void sayHi();
int main()
sayHi(); // the compiler binds any invocation of sayHi() // to sayHi()s entry point.
void sayHi()
Run-time binding is to associate a functions name with the entry point at run-time.
Polymorphism is thus implemented by virtual functions and run-time binding mechanism in C++. A class is called
polymorphic if it contains virtual functions.
The first class that defines a virtual function is the base class of the hierarchy that uses dynamic binding for that
function name and signature.
Each of the derived classes in the hierarchy must have a virtual function with same name and signature.
There is a pointer of base class type; and this pointer is used to invoke virtual functions of derived class.
Example:
#include<iostream>
class Shape
};
public:
};
public:
};
int main()
Shape *p;
int which;
switch ( which )
Packages:
A package allows a developer to group classes (and interfaces) together. It is easy to organize class files into
packages. All we need to do is put related class files in the same directory, give the directory a name that relates to
the purpose of the classes, and add a line to the top of each class file that declares the package name, which is the
same as the directory name where they reside.
Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and
usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations )
providing access protection and name space management.
java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to
group related classes implemented by you so that a programmer can easily determine that the classes, interfaces,
enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in other packages.
Using packages, it is easier to provide access control and it is also easier to locate the related classes.
Creating a package:
When creating a package, you should choose a name for the package and put a packagestatement with that name
at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you
want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement in each
source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an
unnamed package.
package <package name>;
Example:
publicvoid id () {
System.out.println ("Hammer");
Before discussing how to use them let see why we should use packages.
Reusability: Reusability of code is one of the most important requirements in the software industry.
Reusability saves time, effort and also ensures consistency. A class once developed can be reused by any
In real life situation there may arise scenarios where we need to define files of the same name. This may
Access level modifiers determine whether other classes can use a particular field or invoke a particular method.
There are two levels of access control:
A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a
class has no modifier (the default, also known as package-private), it is visible only within its own package.
The following table shows the access to members permitted by each modifier.
protected Y Y Y N
no modifier Y Y N N
private Y N N N
can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same
meaning. For members, there are two additional access modifiers: private and protected. The private modifier
specifies that the member can only be accessed in its own class. The protected modifier specifies that the member
can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in
another package.
Access Levels
Interfaces:
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A
class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:
Example:
import java.lang.*;
publicinterfaceNameOfInterface{
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the
specific behaviours of the interface. If a class does not perform all the behaviors of the interface, the class must
A class uses the implements keyword to implement an interface. The implements keyword appears in the class
publicclassMammalIntimplementsAnimal{
publicvoid eat(){
System.out.println("Mammal eats");
publicvoid travel(){
System.out.println("Mammal travels");
publicint noOfLegs(){
return0;
MammalInt m =newMammalInt();
m.eat();
m.travel();}
Mammal eats
Mammal travels
Exceptions:
An exception is a problem that arises during the execution of a program. An exception can occur for many different
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
To understand how exception handling works in Java, you need to understand the three categories of exceptions:
Checked exceptions: A checked exception is an exception that is typically a user error or a problem that
cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found,
an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably could have been
avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time
of compilation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error.
For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block is referred to as protected code,
and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in
protected code, the catch block (or blocks) that follow the try is checked. If the type of exception that occurred is
listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method
parameter.
If a method does not handle a checked exception, the method must declare it using the throws keyword. The
throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using
the throw keyword. Try to understand the different in throws and throw keywords.
Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array
which throws an exception.
import java.io.*;
publicclassExcepTest {
try{
int a[]=newint[2];
This example shows how to create user defined exception by extending Exception Class.
classWrongInputExceptionextendsException{
WrongInputException(String s){
super(s);
classInput{
void method()throwsWrongInputException{
thrownewWrongInputException("Wrong input");
classTestInput{
try{
newInput().method();
catch(WrongInputException wie){System.out.println(wie.getMessage());
Result:
Wrong input
Advantages of Exceptions:
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
o Defining Defining a database involves specifying the datatypes, structures, and constraints of the
data that has to be stored in the database.
o Constructing Constructing the database is the process of storing the data itself on some storage
medium that is controlled by the DBMS.
o Manipulating Manipulating a database includes such functions as querying the database to
retrieve specific data, updating the database to reflect changes in the mini world, and generating
reports from the data.
o Sharing Sharing a database allows multiple users and programs to access the database
simultaneously.
Example :
University Database:
-Data about students, faculty, courses, research laboratories, course registration/ enrollment etc..
-It reflects the state of affairs of the academic aspects of the university.
Purpose : To keep an accurate track of the academic activities of the university.
Characteristics of DBMS:
There are a number of characteristics that distinguish the database approach with the file-based approach. Few are
listed below:
- DB system contains the complete definition of structure and the constraints which makes itself describing.
- The description of the structure and constraints of the data is termed as Meta-data.
- This information (meta-data) is used either by the DBMS software or database users who need information
about the database structures.
- On the other hand, in file based systems, the definition of the data is a part of application program that has
to be handled by the users.
- In file based system, the structure of the data is stored in the application program. As a result, if we want to
change any definition of the data, then the program that accesses that data has to be changed.
- Whereas, in database systems, as the data structures are stored in the catalog and not in programs, we can
manipulate any one i.e. either program or data whichever is needed.
- View is a subset of the database. View contains virtual data that is derived from the database files but it is
not explicitly stored.
- Multiple users in the same Database system might have different views of that system. Each view might
contain only the data of interest to that user or a group of users.
- The Concurrency Control Techniques of DBMS ensures that several users trying to access and update the
same data do so in a controlled manner.
- Thus DBMS provides multiple user transaction unlike the file based system where the transaction
processing is restricted for single user.
- DBMS provides certain methodologies to define and enforce certain constraints such as data type, data
uniqueness, etc.
- Not all users of the system have the same accessing privileges. DBMS provides a security sub system to
- If the computer system fails in the middle of a complex update process, the recovery subsystem is
responsible for making sure that the database is restored to the stage it was in before the process started
executing.
- At view level, the ER model is considered a good option for designing databases.
- Entity :
Example, in an university database, students, teachers, classes, and courses offered can be
considered as entities.
- Entity set :
An entity set may contain entities with their properties sharing similar values.
For example, a Students set may contain all the students of university; likewise a Teachers set may
Attributes:
For example, a student entity may have name, class, and age as attributes.
There exists a domain or range of values that can be assigned to attributes. For example,
a student's name cannot be a numeric value. It has to be alphabetic. A student's age
cannot be negative, etc.
Types of attributes :
o Simple attribute: The attributes with the atomic values which cannot be divided
further are classified as Simple attributes. For example, a student's phone
number is an atomic value of 10 digits.
o Composite attribute: Attributes made up of more than one simple attribute are
termed as Composite attributes. For example, a student's complete name may
have first_name , middle_name and last_name.
o Derived attribute: Derived attributes are the attributes that do not exist in the
physical database, but their values are derived from other attributes present in
the database. For example, average_salary in a department should not be
saved directly in the database, instead it can be derived. To quote another
example, age can be derived from data_of_birth.
o Single value attribute: Single value attributes contain single value. For
example , Social_security_number of an employee, USN of a student etc..
o Multi value attribute: Multi value attributes may contain more than one values.
For example, a person can have more than one phone numbers, email
addresses etc ..
Keys:
students.
o Super Key A set of attributes (one or more) that collectively identifies an entity in
an entity set.
o Candidate Key A minimal super key is called a candidate key. An entity set may
o Primary Key A primary key is one of the candidate keys chosen by the database
Relationship:
Degree of a relationship:
Types :
Mapping cardinalities:
Cardinality defines the number of entities in one entity set, which can be associated with
Types of Cardinality :
I. One-to-one One entity from entity set A can be associated with at most one entity of
II. One-to-many One entity from entity set A can be associated with more than one
entities of entity set B however an entity from entity set B, can be associated with at
III. Many-to-one
entities from
be associated with
of entity set B,
however an
entity from entity set B can be associated with more than one entity from entity set A.
IV. Many-to-many One entity from A can be associated with more than one entity from B
Relational Schema:
o Relational Schema consists of relational name, and a set of attributes or field names or column
names.
o Each attribute is associated with its domain.
o Domain = Set of atomic values + Data types.
Choose one of the relations S, say and include as a foreign key in S the primary key of T. It is better
to choose an entity type with total participation in R in the role of S.
Include all the simple attributes (or simple components of composite attributes) of the 1:1 relationship
type R as attributes of S.
Include as foreign key in S the primary key of the relation T that represents the other entity type
participating in R; (this is done because each entity instance on the N-side is related to at most one
entity instance on the 1-side of the relationship type).
Include any simple attributes (or simple components of composite attributes) of the 1:N relationship type
as attributes of S.
Include as foreign key attributes in S the primary keys of the relations that represent the participating
entity types; their combination will form the primary key of S.
Also include any simple attributes of the M:N relationship type (or simple components of composite
attributes) as attributes of S.
The primary key of R is the combination of A and K. If the multi valued attribute is
composite, we include its simple components.
Include as foreign key attributes in S the primary keys of the relations that represent the
participating entity types.
Also include any simple attributes of the n-ary relationship type (or simple components of
composite attributes) as attributes of S.
The primary key of S is usually a combination of all the foreign keys that reference the
relations representing the participating entity types.
Normalization:
Normalization:
Normalization is the Formal technique for analyzing a relation based on
- Its primary key and
-The FDs between the attributes of that relation.
-A relation can be normalized to a specific form to prevent the possible occurrence of update anomalies.
- As normalization proceeds, the relations become progressively more restricted (stronger) in format and also less
vulnerable to update anomalies.
Solution2:
Split the Student table into two different tables.
Student(RollNo, Name, Age)
Apply(RollNo,DepName)
Second Normal Form:
Def: A relation schema R is in 2NF if and only if it is in 1NF and every non-prime attribute in R is fully functionally
dependent on key.
Example :
Consider:
Student (RollNo, Name, Dept, Gender, HostelName, RoomNo)
Assumption: Boys & girls are accommodated in separate hostels
Keys: RollNo, (HostelName, RoomNo)
SELECT clause
FROM clause
WHERE clause
GROUP BY
HAVING
DBMS Languages
Data definition language (DDL)
Defines schemas
Storage definition language (SDL)
Specifies the internal schema
View definition language (VDL)
Specifies user views/mappings to conceptual schema
Data manipulation language (DML)
Allows retrieval, insertion, deletion, modification
Drop indexes.
Create sequences.
DDL commands:
1. The Create Table Command: It defines each column of the table uniquely. Each column has minimum
of three attributes, a name, data type and size.
Syntax:
Ex:
create table emp(
empno number(4) primary key,
ename char(10));
Syntax:
Alter table <tablename> add(<new col><datatype(size),<new col>datatype(size));
Ex:
alter table emp add(sal number(7,2));
Syntax:
Alter table <tablename> drop column <col>;
Ex:
alter table emp drop column sal;
Syntax:
Alter table <tablename> modify(<col><newdatatype>(<newsize>));
Ex:
alter table emp modify(ename varchar2(15));
Syntax:
Rename <oldtable> to <new table>;
Ex:
rename emp to emp1;
Syntax:
Truncate table <tablename>;
Ex:
trunc table emp1;
7. Destroying tables.
Syntax:
Drop table <tablename>;
Ex:
drop table emp;
DML commands:
Once a table is created the most natural thing to do is load this table with data to be manipulated later.
Syntax 1:
insert into <tablename> (<col1>,<col2>.....<col n>) values(<val 1>, <val 2>.......<val n>);
Syntax 2:
insert into <tablename> values(&<col1>,&<col2>......,&<col n>);
Syntax 3:
insert into <tablename> values(<val 1>,<val 2>.......,<val n>);
Ex 1:
Insert into skc(sname,rollno,class,dob,fee_paid)values(sri,104B,cse,27-feb-05,10000.00);
Ex 2:
insert into skc values(&sname,&roll no,&class); enter sname:sri
enter roll no:104B enter class:cse
Ex 3:
2. Delete operations.
Syntax:
delete from <tablename>;
Syntax:
delete from <tablename> where <condition>;
Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp>;
Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp> where <condition>;
Syntax:
<col><datatype>(size)not null
b) unique constraint
Syntax:
Unique constraint at column level. <col><datatype>(size)unique;
Syntax:
Create table
tablename(col=format,col=format,unique(<col1>,<col2>);
Syntax:
<col><datatype>(size)primary key;
e) primary key constraint at table level.
Syntax:
Create table tablename(
col=format,
col=format
primary key(col1>,<col2>);
Syntax:
<col><datatype>(size>) references <tablename>[<col>];
Syntax:
foreign key(<col>[,<col>]) references <tablename>[(<col>,<col>)
h) check constraint
Syntax:
<col><datatype>(size) check(<logical expression>)
Syntax:
check(<logical expression>)
DCL commands:
Oracle provides extensive feature in order to safeguard information stored in its tables from
unauthoraised viewing and damage. The rights that allow the user of some or all oracle resources on the
server are called privileges.
Syntax:
GRANT <object privileges> ON <objectname> TO<username> [WITH GRANT OPTION];
Syntax:
REVOKE<object privilege>
ON
FROM<user name>;
Example-1
CREATING A STUDENT RELATION TABLE WITH ALL DATATYPES:
Example:
create table student252(
sid number(5),
sname varchar(20),
sbranch char(5),
dob date,
spercent number(3,2));
METHOD 2:
Insert into Student252 values(104,sri,,cse,27-feb-05,70);
1 row created.
METHOD 3:
Insert into Student252(sid,sname,sbranch,dob,spercent) values(&sid,
&sname,&sbranch,&dob,&spercent);
1 row created.
METHOD 4:
Insert into Student252(sid,sname,sbranch,dob,spercent) values(&sid,
&sname,&sbranch,&dob,&spercent);
1 row created.
DROPING A COLUMN
ALTER TABLE Emp252 DROP COLUMN phno;
Table altered.
Operators in Database:
What is an Operator in SQL?
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform
operation(s), such as comparisons and arithmetic operations.
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in
a statement.
Arithmetic operators
Comparison operators
Logical operators
<> Checks if the values of two operands are equal or not, if (a <> b)
values are not equal then condition becomes true. is true.
> Checks if the value of left operand is greater than the (a > b) is
value of right operand, if yes then condition becomes true. not true.
< Checks if the value of left operand is less than the value of (a < b) is
right operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal (a >= b)
to the value of right operand, if yes then condition is not
becomes true. true.
<= Checks if the value of left operand is less than or equal to (a <= b)
the value of right operand, if yes then condition becomes is true.
true.
!< Checks if the value of left operand is not less than the (a !< b)
value of right operand, if yes then condition becomes true. is false.
!> Checks if the value of left operand is not greater than the (a !> b)
value of right operand, if yes then condition becomes true. is true.
Operator Description
ALL The ALL operator is used to compare a value to all values in another
value set.
ANY The ANY operator is used to compare a value to any applicable value
in the list according to the condition.
BETWEEN The BETWEEN operator is used to search for values that are within a
set of values, given the minimum value and the maximum value.
EXISTS The EXISTS operator is used to search for the presence of a row in a
specified table that meets certain criteria.
LIKE The LIKE operator is used to compare a value to similar values using
wildcard operators.
NOT The NOT operator reverses the meaning of the logical operator with
which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN,
etc. This is a negate operator.
IS NULL The NULL operator is used to compare a value with a NULL value.
UNIQUE The UNIQUE operator searches every row of a specified table for
uniqueness (no duplicates).
Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DSC
SQL aggregate functions return a single value, calculated from values in a column.
Syntax:
SELECT SUM(column_name) FROM table_name;
The COUNT(column_name) function returns the number of values (NULL values will not be counted) of
the specified column
Syntax:
SELECT COUNT(column_name) FROM table_name;
Syntax:
SELECT COUNT(DISTINCT column_name) FROM table_name;
The MAX() function returns the largest value of the selected column.
Syntax:
SELECT MAX(column_name) FROM table_name;
The MIN() function returns the smallest value of the selected column.
Syntax:
SELECT MIN(column_name) FROM table_name;
Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name ;
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.
Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value ;
What Is a Subquery?
select <column(s)>
from table =>Outer Query
where <condn> operator
(select <column> =>Inner Query
from table);