Professional Documents
Culture Documents
(Code : 214444)
Semester III – Information Technology
Harish G. Narula
ge
io led
Ansari M. A.
Formerly, Assistant Professor (Senior), Ph. D (Computer Engineering)
ic ow
Khushboo Shah
Te
Copyright © by Author. All rights reserved. No part of this publication may be reproduced, copied, or stored in a retrieval
system, distributed or transmitted in any form or by any means, including photocopy, recording, or other electronic or
mechanical methods, without the prior written permission of the publisher.
This book is sold subject to the condition that it shall not, by the way of trade or otherwise, be lent, resold, hired out, or
otherwise circulated without the publisher’s prior written consent in any form of binding or cover other than which it is
ge
published and without a similar condition including this condition being imposed on the subsequent purchaser and without
limiting the rights under copyright reserved above.
io led
First Printed in India : July 2013 (For Mumbai University)
ic ow
South-East Asia. Sale and purchase of this book outside of these countries is unauthorized by the publisher.
at
Pu ch
:
Te
ISBN : 978-93-89889-57-4
Published by
TechKnowledge Publications
Head Office : B/5, First floor, Maniratna Complex, Taware Colony, Aranyeshwar Corner,
Pune - 411 009. Maharashtra State, India
Ph : 91-20-24221234, 91-20-24225678.
Email : info@techknowledgebooks.com,
Website : www.techknowledgebooks.com
ge
io led
ic ow
n
bl kn
at
Pu ch
Te
My Dear Students,
We are extremely happy to come out with this book on “Object Oriented
Programming” for you. The topics within the chapters have been arranged in a proper
ge
sequence to ensure smooth flow of the subject.
io led
We present this book in the loving memory of Late Shri. Pradeepji Lunawat,
He will always be remembered in our heart and motivate us to achieve our milestone.
n
bl kn
We are thankful to Shri. J. S. Katre, Shri. Shital Bhandari, Shri. Arunoday Kumar
at
and Shri. Chandroday Kumar for the encouragement and support that they have
Pu ch
Publications for their efforts to make this book as good as it is. We have jointly made
every possible efforts to eliminate all the errors in this book. However if you find any,
We are also thankful to our family members and friends for their patience and
encouragement.
- Authors
Course Objectives :
1. Apply concepts of object oriented paradigm.
2. Design and implement models for real life problems by using object oriented programming.
ge
3. Develop object oriented programming skills.
Course Outcomes :
io led
CO1 : Differentiate various programming paradigms and apply basic concepts of OOP.
CO2 : Identify classes, objects, methods, and handle object creation, initialization, and destruction to
ic ow
Introduction OOP : Software Evolution, Introduction to Procedural, Modular, Object-Oriented and Generic
Programming Techniques, Limitations of Procedural Programming, Need of Object-Oriented Programming,
Fundamentals of Object-Oriented Programming: Objects, Classes, Data Members, Methods, Messages, Data
Encapsulation, Data Abstraction and Information Hiding, Inheritance, Polymorphism, Static and Dynamic Binding,
Message Passing. (Refer Chapter 1)
Class : Creating a Class, Visibility/Access Modifiers, Encapsulation, Methods: Adding a Method to Class, Returning a
Value, Adding a Method That Takes Parameters, The ‘this’ Keyword, Method Overloading, Object Creation, Using
Object as a Parameters, Returning Object, Array of Objects, Memory Allocation: ‘new’, Memory Recovery: ‘delete’,
Static Data Members, Static Methods, Forward Declaration, Class as Abstract Data Types (ADTs), Classes as Objects.
(Refer Chapter 2)
ge
UNIT - V : Exception Handling and Generic Programming (06 Hours)
Exception : Errors, Types of Errors, Exception and its Types, Exception-Handling Fundamentals, Uncaught Exception,
io led
Using try and Catch, Multiple Catch Clauses, Nested Try Statements, User Define Exception using Throw.
Generics : What are Generics? Introduction to Language Specific Collection Interface: List Interface and Set Interface,
Collection Classes: ArrayList Class and LinkedList Class. (Refer Chapter 5)
ic ow
n
UNIT - VI : File Handling and Design Patterns (06 Hours)
bl kn
File Handling : Introduction, Concepts of Stream, Stream Classes, Byte Stream Classes, Character Stream, Classes,
at
Using Stream, Other Useful I/O Classes, Using the File Class, Input/output Exceptions, Creation of Files,
Pu ch
Reading/Writing Character, Reading/Writing Bytes, Handling Primitive Data Types, Concatenating and Buffering Files,
Random Access Files.
Te
Design Patterns : Introduction, Types of Design Patterns, Adapter, Singleton, Iterator. (Refer Chapter 6)
Chapter 1 : Foundations of Object 1.14.1 Programs Based on for Loop ..................................... 1-28
Oriented Programming 1-1 to 1-74 1.14.2 Nested for Loop ......................................................... 1-35
1.1 Computer .................................................................... 1-1 1.15 Revisiting Control Statements ................................... 1-43
1.2 Binary Number System................................................ 1-1 1.15.1 Programs using if-else Statement ............................. 1-44
1.3 Software Evolution....................................................... 1-4 1.15.2 if-else Ladder or if-else if ........................................... 1-46
1.3.1 History of C / C++ Programming Languages ............... 1-4 1.16 Revisiting Arrays ....................................................... 1-47
1.3.2 Comparison of C++ and Java ...................................... 1-5 1.16.1 Multi-dimensional Arrays ........................................... 1-57
1.3.3 Java Evolution: History ................................................ 1-6 1.16.2 Arraycopy() ................................................................ 1-64
ge
1.4 Introduction to Procedural, Modular, Object-Oriented 1.17 Revisiting Strings....................................................... 1-65
and Generic Programming Techniques ....................... 1-6
io led 1.17.1 Methods of String Class ............................................ 1-66
1.4.1 Introduction Object Oriented Programming (OOP)
1.17.2 Methods in String Buffer Class .................................. 1-72
and OOP Languages ................................................... 1-7
ic ow
1.5 Fundamentals of Object-Oriented Programming : Objects, 2.1 Comparison of Procedure Oriented Programming and
Classes, Data Members, Methods ............................... 1-8 Object Oriented Programming ..................................... 2-1
Te
1.6 Static and Dynamic Binding, Message Passing ........... 1-9 2.1.1 Class and Object : Introduction ................................... 2-2
1.7 Java Virtual Machine (JVM) ......................................... 1-9 2.1.2 Introduction to Objects ................................................ 2-3
1.8 Formatted and Unformatted IO Functions of C++ ...... 1-11 2.1.2(A) State and Behaviour of an Object ................................ 2-3
1.8.1 Formatted IO Functions ............................................. 1-11 2.2 Visibility / Access Modifiers ......................................... 2-4
1.8.2 Unformatted IO Functions ......................................... 1-12 2.2.1 Access Specifiers in C++ ............................................ 2-4
1.9 Basic C++ Program Examples................................... 1-12 2.2.2 Introduction to Java Access Modifiers ......................... 2-4
1.9.1 Type Casting ............................................................. 1-14 2.3 Encapsulation.............................................................. 2-5
1.10 Input / Output in Java ................................................ 1-15 2.4 Creating a Class and Adding Methods to a Class ........ 2-5
1.10.1 Displaying Output in Java .......................................... 1-15 2.4.1 Defining Member Functions of a Class ........................ 2-5
1.10.2 Accepting Input in Java ............................................. 1-15 2.4.2 Internally Defined Functions ........................................ 2-5
1.10.3 Accepting Input using BufferedReader Class ............ 1-16 2.4.2(A) Nesting of Member Function ....................................... 2-8
1.11 First Program of Java ................................................ 1-17 2.4.3 Externally Defined Functions ....................................... 2-8
1.12 Installing and Implementing Java .............................. 1-22 2.4.4 Inline Member Functions ........................................... 2-10
1.12.1 Java Development Kit (JDK)...................................... 1-23 2.4.5 Java Member Methods .............................................. 2-11
2.5 Object Creation and Memory 3.1.2 Constructors, Destructors, Modifiers, Iterators and
Allocation: 'new' Operator .......................................... 2-15 Selectors ..................................................................... 3-1
2.5.1 Creating Objects and Memory 3.2 Types of Constructor ................................................... 3-2
Allocation of Objects.................................................. 2-15
3.2.1 Default Constructor ..................................................... 3-2
2.5.2 Memory Recover: ‘delete’ Operator ........................... 2-15
3.2.2 Parameterized Constructor .......................................... 3-3
2.6 Returning a Value ...................................................... 2-16
3.2.3 Copy Constructor (Multiple Constructors/Constructor
2.7 Adding a Method that Takes Parameters .................. 2-17 Overloading) ................................................................ 3-4
2.8 The "this" Keyword .................................................... 2-18 3.2.4 Constructors ................................................................ 3-7
2.8.1 “this” Keyword in C++ ................................................ 2-18 3.2.4(A) Parameterized Constructor .......................................... 3-7
2.8.2 The “this” Keyword in Java ........................................ 2-19 3.2.4(B) Default Constructor ..................................................... 3-9
ge
2.9 Method Overloading .................................................. 2-20 3.2.4(C) Copy Constructor ...................................................... 3-10
2.9.1 Function Overloading or Function Polymorphism ...... 2-20 3.3 Constructor Overloading ............................................ 3-12
io led
2.9.2 Constructor Overloading ............................................ 2-22 3.4 Constructor with Default Arguments .......................... 3-13
2.14 Forward Declaration .................................................. 2-39 4.1.1(A) Visibility Modes and Effects ......................................... 4-1
2.15 Class as "Abstract Data Type" (ADT) ........................ 2-39 4.1.2 Introduction to Inheritance ........................................... 4-2
Model Question Paper (In Sem.)................................ Q-1 4.1.3 Cost of Inheritance ...................................................... 4-3
ge
4.5.1 Abstract Classes ....................................................... 4-28
5.5 Nested try Statements ................................................. 5-7
4.5.2 Interface .................................................................... 4-31
io led 5.5.1 Keyword “throws”......................................................... 5-9
4.5.2(A) Extending an Interface ............................................... 4-31
5.6 User Define Exception using Throw............................. 5-9
4.5.2(B) Variables in Interface ................................................. 4-31
5.7 Exception Handling in C++ ........................................ 5-11
ic ow
4.7.2 Rules for Virtual Functions ........................................ 4-38 5.9.2 Overloading a Template Function Using a Non-template
Function .................................................................... 5-17
4.7.3 Pointer to Derived Class ............................................ 4-39
5.9.3 Overloading a Template Function Using a Template
4.7.4 Virtual Base Class and Abstract Class ...................... 4-42
Function .................................................................... 5-17
4.7.5 Static Polymorphism in Java ..................................... 4-43
5.9.4 Generic Classes, Class Template and Examples ...... 5-18
4.7.5(A) Constructor Overloading ............................................ 4-43
5.9.5 Overview and Use of Standard
4.7.5(B) Method Overloading .................................................. 4-44 Template Library (STL).............................................. 5-18
4.7.5(C) Operator Overloading ................................................ 4-46 5.10 Introduction to Language Specific Collection Interface :
List Interface and Set Interface .................................. 5-19
4.7.6 Dynamic Polymorphism in Java................................. 4-50
5.10.1 List Interface.............................................................. 5-19
4.7.6(A) Dynamic Method Dispatch ......................................... 4-50
5.10.2 Set Interface .............................................................. 5-19
4.8 Efficiency and Polymorphism .................................... 4-51
5.11 Collection Classes : ArrayList Class and
4.9 Case Study : A Bank Account System ....................... 4-51
LinkedList Class ........................................................ 5-19
5.11.2 LinkedList Class ........................................................ 5-20 6.7 Using streams for reading from and
writing to the files......................................................... 6-5
5.12 Exception Handling and Generic Programming using
Array List (ArrayList Class) ........................................ 5-20 6.7.1 Reading/Writing Bytes and Detecting End of File ........ 6-6
ge
6.3.1 File Stream Classes .................................................... 6-2
6.11.3 Iterator....................................................................... 6-12
6.3.2 Advantages of Stream Classes ................................... 6-2
io led 6.12 Student Management System ................................... 6-12
6.4 Other Useful I/O Classes ............................................. 6-2
Model Question Paper (End Sem.) .................. Q-1 to Q-2
6.5 Input/Output Exceptions .............................................. 6-3
ic ow
6.6 Creation of Files and using the File Class ................... 6-3
n
bl kn
at
Pu ch
Te
Unit I
Syllabus
Introduction OOP : Software Evolution, Introduction to Procedural, Modular, Object-Oriented and Generic Programming
ge
Object-Oriented Programming: Objects, Classes, Data Members, Methods, Messages, Data Encapsulation, Data
Abstraction and Information Hiding, Inheritance, Polymorphism, Static and Dynamic Binding, Message Passing.
io led
1.1 Computer As a programmer, the computer can be seen as a
ic ow
ge
io led 1 0 1
Fig. 1.2.1
Binary to decimal : The steps to be followed 0 1
n
for converting a binary number to a decimal 1 0
bl kn
number are :
4. EXOR : The output is 1 if and only if
o Multiply the binary digits (bits) with
at
2 3 3. 7 OR 6 :
ge
Note : & is bitwise AND operator i.e. it works on each bit Now; 7 OR 6
as shown in the above example.
io led (1 1 1)2
(001)2 = 0 × 2 + 0 × 2 + 1 × 2
2 1 0
| (1 1 0)2
= (1)10 (1 1 1)2
(5)10 & (3)10 = (1)10 (111)2 = 1 × 22 + 1 × 22 + 1 × 2
ic ow
2. 13 AND 10 : = (7)10
n
2 13 (7)10 | (6)10 = (7)10
bl kn
2 6 1 4. 5 OR 2 :
at
Pu ch
1 2 0 (13)10 = (1101)2
2 5
2 1 1
2 2 1
Te
0 1
2 1 0 (5)10 = (101)2
2 10
0 1
2 3 0
2 2 1 (10)10 = (1010)2
2 1 0 2 2
0 1 2 1 0
= (7)10
(4)10 | (2)10 = (7)10
ge
o
(1 0 1)2 the operation to be performed and
^ (0 1 1)2 o The operands, which are the data on which
io led
(1 0 1)2 the operation is to be performed.
In C, this is written as 3
Pu ch
.net, etc.
0 1 (3)10 = (011)2 HLL programming languages like C / C++ are
Now; ~ 3 is 01011 structured programming languages and hence
10100 are quite easy for the programmers. C / C++ are
sometimes also referred to as middle level
Note : 1) The data may be of more than 2 bits and
languages as they are not fully high level
hence you will get the output depending on
languages and neither are they low level
the size of data.
languages.
2) In computer binary language you will get this
value as (- 4)10. In this subject we have to learn these two
programming languages viz. C and C++. Also
3) Hence if you say (10)10, you will get - (11)10
we have to make some small programs using
and so on.
these languages.
1.3 Software Evolution 1.3.1 History of C / C++ Programming
Languages
Programming is to give the machine a list of
steps to perform a particular task. C programming language was developed by
If the system to which the programming is done Dennis Ritchie at the Bell Laboratories of
is a computer than it is called as Computer AT & T.
Programming.
He developed a complier that can convert the While ‘C’ was a procedure oriented language i.e.
HLL namely C to the machine language that more significance was given to the procedure to
can be understood by the processor or the perform a task.
computer. But his compiler could understand C++ which is an object oriented programming
only if certain rules were followed while writing language was then developed again at Bell
the program. Laboratories by Bjarne Stroustrup. Earlier, this
We need to understand and know these rules to language was called as C with classes, but was
program our computers using this later renamed as C++ in 1983.
programming language. C was the most Object oriented and procedure oriented concepts
popular programming language. of a programming language will be gradually
Some other languages had become popular after seen in this book. Some of these concepts will be
some time of evolution of C. This was because cleared in this chapter itself, while some will
these other programming languages were object come as you reach towards the end of this book.
ge
oriented i.e. more significance was given to
object.
io led
1.3.2 Comparison of C++ and Java
1. C++ is object oriented programming but Java is a purely object oriented programming; no
not a purely object oriented programming program can be written without classes and objects.
at
Pu ch
objects.
2. C++ has a goto statement. But this To avoid this dependency of system, goto statement
statement makes the program system is not available in Java.
dependent.
3. Pointers are also allowed in C++, and it Pointers are not there in Java to avoid platform
also makes the program system dependency.
dependent.
4. Multiple and Hybrid inheritance are Multiple and Hybrid inheritance are not in Java. A
possible in C++. slight implementation of the same can be done with
a special tool called as Interface.
6. We include a header file in C++ that In Java we import class files, which do not consume
consumes a lot of memory space for even memory. As we know memory space is required for
those objects that are not used in the objects and not classes. Hence until we need an
program. object, we will not create it and hence memory space
is not wasted.
7. In C++ we had three access specifiers In Java we have five access specifiers namely:
namely: public, protected and private. public, protected, private, default and private
protected. Although private protected is not
available in recent versions of Java.
9. C++ doesn’t have exception handling. In Java has a powerful exception (error) handling
case of any errors, the compiler cannot system.
handle it.
ge
10. C++ doesn’t support multi threading.
io led Java supports multi threading.
11. C++ cannot be used on internet for Java can be used on internet by making applets and
making applets. hence having dynamic applications.
ic ow
They couldn’t find a single programming Q. In procedure oriented programming all data are
language suited for their project. They decided shared by all functions. Is this statement TRUE?
There are global and local variables as seen in The data of the object can be accessed by the
the Fig. 1.4.1. The global variables can be functions associated with it. The functions of
one object can access the data of another object
accessed by all the functions, while the local
through the functions of that object.
variables are local to the corresponding
Object oriented programming uses bottom up
function.
approach wherein the smaller tasks are first
A procedure oriented programming language dealt in detail and gradually creating the entire
follows top bottom approach. huge system.
Top bottom approach refers to approaching to a
problem as a big task or as a whole. Then
dividing this task into small instructions or
operations. Hence, initially the task is broken
into small tasks and then these smaller tasks
are written in detail.
ge
io led
ic ow
n
Fig. 1.4.2 : Structure of an Object Oriented Programming
bl kn
4. Data can be accessed by all the functions and hence security of data from some users and access to
others is not possible.
OOP finds wide applications in the IT industry as it models the real world problems quite preciecely.
Also it resolves the above mentioned issues of POP. Let us see the differences of POP and OOP.
Table 1.4.1 : Differences between POP and OOP
ge
given object.
3. Data can be accessed by any function, and Data can be accessed only by functions of that
hence there is a scope of unexpected change class and hence it cannot be changed
io led
of data unexpectedly
4. Global data is allowed to be accessed by all No global data. Data is encapsulated
functions. Hence data is not hidden
ic ow
5. If changes are done in some data, the Adding of new data or changes in the data
n
corresponding changes are to be requires to change only the functions of the
bl kn
design. design.
7. It cannot model the real world problems It is used to model the real world problems
Te
precisely. precisely
CIM/CAM/CAD systems
ge
operations happening during the compilation of
3. Data abstraction
io led a program are called as static.
Similarly, if the binding is done during the
Data abstraction is like defining or abstracting
execution, then it is called as dynamic binding
the object according to the required
or runtime binding.
ic ow
ge
Note : The source code is never distributed. If the
source code is distributed then the customer can
io led
do the needful changes by himself and will never
come back to the software developer. Hence a Fig. 1.7.1
software developer should never give away the The method area is used to store the code of the
ic ow
source code developed by him. In C++ programs, program that is currently being executed.
the developer had to go and install the software Heap is used to store objects i.e. space for the
n
on the customer’s system; and sometimes also
bl kn
The JIT translates and immediately executes Table 1.8.1 : Format specifiers
the machine code i.e. just in time. Hence
Sr. Format Data type
increasing the speed of operation. No. specifier
1. %d or % i For integer type of data
1.8 Formatted and Unformatted IO
Functions of C++ 2. %f For float type of data
3. %c For char type of data
Inbuilt IO functions are available in C for 4. %lf For double type of data
displaying data on the standard output device
5. %Lf For long double type of
i.e. monitor and accepting the input from the data
standard input device i.e. keyboard.
Examples:
These IO functions are classified as formatted
and unformatted functions based on the 1. printf(“The number of buildings is %d”,b);
ge
formatting permitted or not. These are This statement will print the output with the
discussed in more details in the following sub
io led format specifier replaced with the value of b.
sections. 2. printf(“The simple interest is %f”,si);
1.8.1 Formatted IO Functions This statement will print the output where the
format specifier %f will be replaced with the
ic ow
There are two formatted IO functions in C float type value of the variable si.
namely printf() to display a data on monitor 3. printf(“The simple interest is %5.2f”,si);
n
and scanf() to accept data from keyboard.
bl kn
Syntax: printf(“Format string”, list of which indicates five digits before the fraction
variables point and 2 digits after the fraction point. This
statement will display the output wherein the
Te
or expressions)
value of si will be displayed with five digits
The format string can contain the following :
before the fraction point and only two digits
(a) Character set (A-Z, a-z, 0-9, all special after the fraction point.
symbols on the keyboard)
2. scanf()
(b) Blank spaces
Syntax: scanf(“format String”, address of
(c) Escape sequences variables);
(d) Field width Here, format string can contain format
specifier, field width and assignment
The width of a value can be fixed by
suppression character. The assignment
specifying the field width. Examples of such suppression character (*) is used to discard
case are given below. one of the user entered value.
(e) Format specifiers The address of the variable is obtained with the
Format specifiers specify the format of the help of the address of operator (&).
variable data whose value is to be Examples
displayed. The format specifiers for
1. scanf(“%d”,&x);
different types of data is given in the
This statement is used to accept aint type value
Table 1.8.1.
from user in the variable x
2. scanf(“%d %d %f”,&x,&y,&z);
This statement is used to accept two int type 1.9 Basic C++ Program Examples
data into variables x and y. It also accepts a
Program 1.9.1 : Write a C++ program to accept a
float type data into the variable z. number and display its square.
ge
getch();
}
io led
Output
Enter a number:6
ic ow
The square of 6 is 36
Explanation
n
bl kn
2. getche(): This function is used accept one Here, we use this function, so that the processor
character from the user and echo it (display it waits for us to enter the character before closing
on the output window after displaying the result.
the screen).
As the processor operation is very fast it
3. getchar(): This function is used to accept one
displays the result on the output screen and
character from the user and echo it (display it
closes the output screen, before we can see the
on
output. Hence, to make the processor to wait for
the screen) and also wait after that for the user
to press the enter key. us to see the result we give a getch() function.
4. gets(): This function is used to accept a string The variables x and y are declared as integer
from the user. We will see in details of this type data.
when studying the chapter on strings.
Using the first cout statement the user is asked
5. putch() : These functions are used to display to provide a number whose square is to be
a character on the monitor. putchar().
found.
6. puts(): This function is used to display a
string on the monitor.
ge
concatenated insertion operators. The insertion
}
operator is used along with the cout statement
io led
to display a data on the monitor.
Output
#include<iostream.h> 9.5
n
#include<conio.h> 10
bl kn
Explanation
Pu ch
clrscr();
All the variables are taken as float as these
int x, y, z; parameters are normally with fraction part included
Te
cout<<"Enter two number:"; like principal has rupees and paisa; rate of interest
cin>>x>>y; is fraction etc.
z=x*y; Program 1.9.4 : Write a program to accept basic salary
cout<<"The product is "<<z; from the keyboard. Calculate the gross salary that includes
basic salary, 50% DA and 40% HRA.
getch();
} #include<iostream.h>
#include<conio.h>
Output
void main ()
Enter two number:3 {
4 clrscr();
The product is 12
floatbasic,hra,da,gross;
Explanation cout<<"Enter the basic salary:";
The two numbers are accepted in the variables cin>>basic;
x and y by concatenating the extraction hra=40*basic/200;
operator in a single statement using cin. da = 50*basic/200;
The product is calculated using the multiply gross=basic+da+hra;
operator (*). cout<<"The total salary is "<<gross;
getch();
}
ge
was float (the variable basic is float type).
}
Program 1.9.5 : Write a program to swap two integers.
io led Output:
#include<iostream.h>
Enter a number to be shifted left:5
#include<conio.h>
After shifting three times left the value is 40
ic ow
void main ()
{ 1.9.1 Type Casting
n
bl kn
clrscr(); Program 1.9.7 : Write a program to accept one int type data
int a, b, temp; and one float type data. Multiply the two numbers and
display the result.
at
Pu ch
ge
cout<<"Enter a float number:";
cin>>b; These methods are available in the a package
a=(int)b; called as “java.lang”. This file has many classes
io led
cout<<"The integer part of the number is:"<<a; and is by default available in any java program.
getch(); One of the class of this package is called as
ic ow
Enter a float number:3.14 namely print() and println() that are static i.e.
The integer part of the number is:3 these methods can be called without making
at
Pu ch
ge
(that terminates with a new
The class Scanner is in the package “java.util”.
line or enter key) entered
When making an object of the class Scanner, we
from the keyboard
io led
need to pass an object of , we need to pass to the
constructor a variable of the class “System” We will see the use of these input and output
called as “in”. This variable refers to the methods in the programs to be followed to this
ic ow
This variable refers to the standard input Another care to be taken when using readLine()
device i.e. keyboard. Hence the object of the method is that it throws an Exception called as
class BufferedReader is to be created as shown IOException when you press the enter key after
below : entering the value. This is a known exception
BufferedReader br = new BufferedReader i.e. it is known to the compiler. Hence compiler
(new InputStreamReader (System.in)) doesn’t allow to compile the program if it is not
said that the main function throws an
Here the object named as “br” is created of the
IOException.
class BufferedReader. While creating this object
an object of InputStreamReader is passed to the 1.11 First Program of Java
constructor, in the brackets meant for passing
In Java, no program can be written without a
the parameters to an object. The new operator
class as already discussed. Hence we will start
is used to create an object of a class as already
writing our program with the keyword “class”
ge
discussed in this section. The class
followed by a name for the class.
InputStreamReader also has a constructor that
requires the variable to indicate the source of Every program should have a main method
io led
the input. which indicates the entry point of the program.
Since this class “BufferedReader” is in the Some important points to be noted for the main
ic ow
classes of this package by writing the statement 1. The main() method should always be
n
“import java.io.*” in the beginning of the public. The main method is called by the
bl kn
int, float etc with the help of wrapper classes. to call this function.
Te
We will see more about wrapper classes in 2. There can be multiple classes in a program.
chapter 9 i.e. packages. For time being, we will Multiple classes can have the method
just see how to convert a string to int, float etc. main(). In such a case, the class that has
The wrapper class “Integer” has a static method the main method which is to be taken as
called as “parseInt()”. The string passed to this the entry point should be the same as the
method is converted into an integer value (but name of the program file. And this function
the string should contain only digits). Hence will have to be called without making an
this method can be called to parse (convert) a object of the class. Hence this main()
string to integer in the following way; function must be declared as static. A
static member of a class is accessed with
int i = Integer.parseInt(str),
the class name while a non-static member
where ‘i’ is an integer and “str” is a string.
is accessed with the object name. The JVM
Similarly, to convert a string to float number, hence calls the main () method of the
the wrapper class “Float” with its static method program name (which is same as that of the
“parseFloat” is to be used. class name) with the dot (‘.’) operator which
For e.g. float f=Float.parseFloat(str), where ‘f’ is a member select operator.
is a float number and “str” is a string.
ge
of C++. Here there is a class called as
definition indicates what data members and
“String”. The array of strings in the
method members are there in the class. The
parameter list of the main() method is
io led
main() method must be declared as public and
nothing but an array of String objects,
static as discussed earlier. Also the main()
wherein each object can store a string. We
method must be capable of accepting an array
ic ow
computer.
class_name.method_name(). But, in this case
We will then understand the meaning of each the method is called with the variable “out” as
Te
word written in the program and also how to discussed in the previous section.
execute this program.
Program 1.11.2 : Define a Class Bank Account having data
Program 1.11.1 : Write a program to display a statement members and member functions as :
“Hello Friends”.
Data members :
//This program displays Hello Friends.
class HelloFriends{ 1. Name of depositor
} Members functions :
import java.util.*; }
class Account public void withdraw()
{ {
protected float bal,with,dep; System.out.print("Enter amount to be withdrawn=");
protected int accno,areacode; with=sc.nextFloat();
public void enterBal() if(with>bal)
{ System.out.println("Insufficient funds.");
Scanner sc=new Scanner(System.in); else if(with>50000)
System.out.print("Enter your balance="); System.out.println("Error: Prior Notice Not
bal=sc.nextFloat(); Submitted.");
} else
} {
class Withdraw extends Account System.out.println("Rupees"+with+"
ge
{ withdrawn.\nYour new Account
protected int dob,pin,mainpin; Balance is "+(bal-with));
bal=bal-with;
io led
protected String name, surname,fullname;
Scanner sc=new Scanner(System.in); }
public void accDetailsAccept() }
ic ow
name=sc.nextLine(); dep=sc.nextFloat();
System.out.print("Last name : "); System.out.println("Your new Account Balance is
at
Pu ch
surname=sc.nextLine(); "+(bal+dep));
fullname=name+" "+surname; bal=bal+dep;
}
Te
ge
{
char ans1,ans2;
System.out.println("******THAKUR WORLD
do
io led
BANK******");
{
System.out.println("WELCOME! PLEASE ENTER
d.Text();
YOUR DETAILS BELOW:");
choice3=sc.nextInt();
ic ow
do
}
{
public void menuCustomer()
at
{
mpin=sc.nextInt();
System.out.println("******___CUSTOMER MAIN
if(mpin==123)
Te
break;
System.out.println("Add Account Holder Data First."); default:System.out.println("Incorrect option. Try Again.");
} break;
else }
{ }
System.out.print("Enter account number of client to be if(choice3==2)
deleted:"); {
del=sc.nextInt(); do
for(j=0;j<=n-1;j++) {
{ d.menuCustomer();
if(w[j].search(del)) choice1=sc.nextInt();
{ switch(choice1)
flag =1; {
ge
for(k=j;k<=n-2;k++) case 1: n++;
{ w[i]=new Withdraw();
w[k]=w[k+1]; w[i].accDetailsAccept();
io led
} i++;
n--; break;
ic ow
if(flag==1) {
{ if(w[j].search(an))
at
Pu ch
} System.out.println();
else do
System.out.println("Account Holder Data Does Not Exist."); {
break; d.menu2();
case 2 :System.out.println("Enter account number whose System.out.println();
data is to be displayed:"); System.out.print("Enter your choice=");
disp=sc.nextInt(); choice2=sc.nextInt();
for(j=0;j<=n-1;j++) System.out.println("\n");
{ switch(choice2)
if(w[j].search(disp)) {
{ case 1: {
w[i].dispData(); w[j].checkBal();
} break;
else }
System.out.println("Account Holder Data Does Not Exist.");
} case 2: {
break; w[j].withdraw();
case 3: System.out.println("Thank You! Have A Good break;
Day!");
}
ge
System.out.println("Incorrect option. Try Again.");
break; if(ans2!='y'||ans2!='Y')
} System.out.println("Thank You For Using The System! Have
io led
A Great Day!");
}
}while(ans2=='y'||ans2=='Y');
System.out.println("Do you wish to perform another
operation?(Y/N)"); }
ic ow
ans1=sc.next().charAt(0); }
if(ans1!='y'||ans1!='Y')
n
1.12 Installing and Implementing Java
bl kn
System.out.println("Thank You
For Using The System! Have A Great Day!"); The question that should come to your mind
after reading the above program is that how
at
}while(ans1=='y'||ans1=='Y');
Pu ch
In the “System variables” box select the for e.g. as shown in the output of
variable “Path” and click the button Program 1.13.1
“Edit” below that box. C:\java programs\WORLD>java
Step 2 : A new window opens. In the “Variable HelloFriends
value” field, type the path of the bin These steps are to be followed to run the
folder of the JDK followed by semicolon program written by you.
(;). For example if the JDK is installed in
“C” drive itself the path to be given is 1.13 Solved Programs
“;C:\jdk1.5.0_02\bin”. Program 1.13.1 : Write a Java program to accept a number
and display its square.
1.12.1 Java Development Kit (JDK)
import java.util.*;
JDK is developed by Sun Microsystems. Java class Square
Development Toolkit as the name says is a {
ge
toolkit required on your system for public static void main(String args[])
programming in Java. This toolkit mainly has a
io led {
compiler that can compile the java programs. int i,res;
Besides the compiler it also has some packages Scanner sc = new Scanner (System.in);
that can be imported by your program to use System.out.println(“\nEnter a number:”);
ic ow
on Windows are :
Step 1 : Type your program on notepad and store Enter a number:
it as the class name.java. For example 3
the above program must be stored as The Square=9
HelloFriends.java. C:\java programs\chapter 1\prog 1.13.1>
Step 2 : Compile the program in command prompt Explanation
using the Java compiler i.e. javac. The
This program begins with a statement to
path should be according to folder where
import the package “java.util”. This package is
your program is stored. The syntax for
required for the class Scanner.
compiling the program is :
C:\....>javac class_file_name.java The class Scanner as discussed earlier is
for e.g. as shown in the output of the required to accept the input from user with the
Program 1.13.1 help of the nextInt() method.
Let us see this program using the For time being, we can assume that the “str” is
BufferedReader class. as good as the variable of type string.
import java.io.*; The user entered number is accepted as a
class Square string in the String object “str”. Then the string
{ is parsed to an integer using the static method
public static void main(String args[]) throws IOException parseInt() in the wrapper class Integer.
{ To find the square the number is simply
int i,res; multiplied by itself and the result is stored in
BufferedReader br = new BufferedReader (new the variable “res”.
InputStreamReader (System.in));
As you must have noticed that using Scanner
String str;
class to accept user input is very simple. Hence
System.out.println(“\nEnter a number:”);
here onwards we will be using the Scanner
str=br.readLine();
class, unless it is required to demonstrate
ge
i=Integer.parseInt(str);
something related to the BufferedReader class.
res=i*i; io led
System.out.println("The Square=" + res); Program 1.13.2 : Write a Java program to accept two
} numbers and display its product.
} import java.util.*;
ic ow
3
The Square=9 int a,b,res;
Scanner sc = new Scanner (System.in);
Te
Program 1.13.3 : Write a program to calculate the simple Program 1.13.4 : Write a program to accept the length and
interest taking principal, rate of interest and number of years breadth of a rectangle from the user. Calculate and display
as inputs from user. the area and perimeter.
ge
p=sc.nextFloat(); area=l*b;
n=sc.nextFloat(); perimeter=2*(l+b);
io led
System.out.println("The Area=" + area + "\nThe
r=sc.nextFloat();
Perimeter=" + perimeter);
si=p*n*r/100; }
ic ow
5
C:\java programs\chapter 1\prog 1.13.3>java SimpleInterest 6.3
The Area=31.5
Enter Principal amount, no. of years and rate of interest:
The Perimeter=22.6
1000
3 C:\java programs\chapter 1\prog 1.13.4>
10
Program 1.13.5 : Write a program to accept two numbers
The Simple Interest=300.0 from user and display the greatest of two using the
conditional operator.
C:\java programs\chapter 2\prog 1.13.3>
import java.util.*;
Explanation class Larger
{
All the variables are taken as float as these
public static void main(String args[])
parameters are normally with fraction part
{
included like principal has rupees and paisa; int a,b,large;
rate of interest is fraction etc.. Scanner sc = new Scanner (System.in);
Hence the method to accept the float type is System.out.println("Enter two numbers:");
a=sc.nextInt();
used i.e. nextFloat() in the class Scanner.
b=sc.nextInt();
C:\java programs\chapter 1\prog 1.13.5>javac Larger.java Program 1.13.7 : Write a program to swap two integers.
C:\java programs\chapter 1\prog 1.13.5>java Larger import java.util.*;
Enter two numbers: class Swap
5 {
7 public static void main(String args[])
The Larger no.=7 {
C:\java programs\chapter 1\prog 1.13.5> int a,b,temp;
Scanner sc = new Scanner (System.in);
ge
Program 1.13.6 : Write a program to find the area of a circle.
System.out.println(“Enter two numbers:”);
import java.util.*;
a=sc.nextInt();
io led
class Circle b=sc.nextInt();
{ System.out.println("a=" + a + "\nb=" + b);
public static void main(String args[]) temp=a;
ic ow
{ a=b;
float r,area;
n
b=temp;
bl kn
}
Pu ch
r=sc.nextFloat();
area=3.14f*r*r; }
Te
Explanation Explanation
The value of pi i.e. 3.14 is to be written followed For swapping two numbers we need to use a
by a character ‘f’ to indicate the value is to be temp variable and store one of the values in
considered as a float number, else the fractional that temp variable.
value as discussed earlier will be considered as The other value is to be then copied as shown in
a double value. the program above.
ge
NOT of b:-6
}
}
io led C:\java programs\chapter 1\prog 1.13.9>
Output
1.14 Revisiting Loops Statements
C:\java programs\chapter 1\prog 1.13.8>javac Shift.java
ic ow
C:\java programs\chapter 1\prog 1.13.8>java Shift For is a iterative statement. It is used to repeat
Enter a number: a set of statements number of times. The
n
syntax (method of writing) the “for” statement
bl kn
4
After Shifting: is given below :
at
Result=32 updating)
C:\java programs\chapter 1\prog 1.13.8> {
Te
-
Program 1.13.9 : Write a program to accept two numbers -
and display the result of their AND, OR, EXOR and NOT
-
operations.
statements;
import java.util.*;
-
class BitwiseOperations
-
{ -
public static void main(String args[]) }
{
The sequence of execution of the for loop is such
int a,b;
that the initialization statements are
Scanner sc = new Scanner (System.in);
executed first.
System.out.println("Enter 2 numbers: ");
These initialization statements are executed
a=sc.nextInt();
only once. They are used to initialize the values
b=sc.nextInt();
of the variables.
System.out.println("After ANDing: " + (a&b) + "\nAfter
ORing: "+ (a|b) + "\nAfter EXORing: "+(a^b) + The second step is checking the condition
“\nNOT of a: " + (~a) + "\nNOT of b: " + (~b)); specified. There can be only one condition. If
} more than one conditions are required they can
} be combined using the logical AND, OR
operators.
ge
If not reached then the control enters inside the
decrement operations, but mostly these are
loop i.e. the curly braces.
increment decrement and hence called so. We
io led The condition we have put is i<=5, since the
can update the variables over here before
starting the next iteration of the iterative value of i will vary from 1 to 5. Hence the
statements. statements inside the loop must be executed in
ic ow
Output 4
5
1
6
2
7
3
4 Explanation
5 In this program we accept the value from user,
6 using the readLine() method and take the value
7 of i from 1 to that number. We are displaying
8 the value of i, and hence displaying the natural
9 numbers from 1 to n.
10
Program 1.14.4 : Write a program to find the factorial of a
Explanation number.
ge
In the above program we have used for loop. import java.util.*;
The variable ‘i’ is initialized to 1 in the class Factorial
initialization statement. In the condition {
io led
statement it is checked if the value has reached public static void main(String args[])
10. {
ic ow
If not reached then the control enters inside the int i,n,fact=1;
loop i.e. the curly braces. In the curly braces we Scanner sc = new Scanner (System.in);
n
are printing the value of ‘i’ itself, hence System.out.print("Enter the value of n:");
bl kn
}
class Natural
System.out.println("Factorial = " + fact);
{
}
public static void main(String args[])
}
{
int i,n; Output
Scanner sc = new Scanner (System.in); Enter the value of n:5
System.out.print("Enter the value of n:"); Factorial = 120
n=sc.nextInt();
Explanation
for(i=1;i<=n;i++)
In this program we accept a number from user
{
in the variable n. We initialize the value of i to
System.out.println(i);
1 and also the value of the variable fact to 1.
}
Remember, initialization part of the for loop
}
can have multiple initializations. Update or
}
increment / decrement operations can be
Output multiple. But the condition statement has to be
Enter the value of n:7 only one, if required to be combined with AND /
1 OR operator.
2
3
ge
result will always be 0. public static void main(String args[])
{
Program 1.14.5 : Write a program to display the
io led int i,n;
multiplication table of a user entered number. The table must
be upto 10. Scanner sc = new Scanner (System.in);
import java.util.*; System.out.print("Enter the value of n:");
ic ow
{
{ System.out.println(i);
int i,n;
at
}
Pu ch
n=sc.nextInt();
for(i=1;i<=10;i++) Output
{ Enter the value of n:6
System.out.println(n + " X " +i + " = " + (n*i)); 1
} 3
}
5
}
7
Output 9
Enter the value of n:4 11
4X1=4
Explanation
4X2=8
4 X 3 = 12 In this program we multiply the value of i by 2
4 X 4 = 16 and add to it 1. To start the odd numbers from
4 X 5 = 20 1, we have to make the value of i initialized to
4 X 6 = 24 0, and hence go upto n – 1.
4 X 7 = 28 Since we need a total of n odd numbers,
4 X 8 = 32 starting from 0 when we reach n – 1, we have
4 X 9 = 36 already covered n numbers.
4 X 10 = 40
ge
} value of i to sum.
}
Hence at the end, the sum of all numbers from
}
io led 1 to n is stored in the variable sum, which is
Output displayed.
Enter the value of n:7
ic ow
7 class Even
{
at
Explanation
Pu ch
int i,n,sum=0;
only increment decrement statements can be
Scanner sc = new Scanner (System.in);
written in the updating statements; we can also
System.out.print("Enter the value of n:");
put some other operations like the addition
n=sc.nextInt();
statement written in this program.
for(i=2;i <=2*n;i+=2)
The condition checked over here is that i must
{
be less than or equal to n. As it is specified that
System.out.println(i);
the odd numbers are to be printed upto n, we
}
want the value of i to reach maximum upto n.
}
Program 1.14.8 : Write a program to calculate and display
}
the sum of first n natural numbers.
import java.util.*; Output
class Sum { Enter the value of n:5
public static void main(String args[])
2
{
4
int i,n,sum=0;
Scanner sc = new Scanner (System.in); 6
System.out.print("Enter the value of n:"); 8
n=sc.nextInt(); 10
for(i=1;i<=n;i++)
Explanation Explanation
In this program we are changing the values of i We first display the values 0 and 1 i.e. the first
from 2 to n and in each case we are adding the value two elements of Fibonacci series. Also these two
of 2*i to sum. values are initialized in the variables a and b.
Program 1.14.10 : Write a program to display first n In every iteration, the next value is calculated
elements of Fibonacci series. and stored in the variable c and is printed. Also
import java.util.*; the values of a and b are updated accordingly
class Fibonacci i.e. the latest two values calculated must
{ always be in a and b.
public static void main(String args[]) The condition statement of the for loop is
{ important in this case. Since the first two
int i,n,a,b,c; elements are already printed the counting of
a=0;
ge
printing the elements of Fibonacci series in the
b=1; loop must go only upto n-2 i.e. two values less
Scanner sc = new Scanner (System.in); which are printed outside the loop.
io led
System.out.print("Enter the value of n:");
Program 1.14.11 : Write a program to calculate the value of
n=sc.nextInt();
1 1 1 1
System.out.println("Fibonacci Series:\n0\n1"); the following series. 1 + 2 + 3 + 4 + … + n
ic ow
c =a+b; {
System.out.println(c); public static void main(String args[])
{
at
a=b;
Pu ch
ge
System.out.println("Sum=" + sum);
{
}
public static void main(String args[]) }
io led
{
Output
int i,n,fact=1;
float sum=0; Enter angle in degrees:90
ic ow
ge
System.out.println("t\ts\n1\t" + s);
Program 1.14.15 : Write a program to determine the sum of
1 1 1 1 for(t=5;t<=100;t+=5)
the series. 1 – 2 + 3 – 4 + .... n
io led {
import java.util.*; s=s0+v0+0.5f*a*t*t;
System.out.println(t+"\t" + s);
class Sum
ic ow
}
{
}
n
public static void main(String args[]) }
bl kn
{
Output
int i,n,sign=1;
at
float sum=0; 0
Scanner sc = new Scanner (System.in); 9.8
Te
t s
System.out.print("Enter value of n:");
1 4.9
n=sc.nextInt(); 5 122.5
for(i=1;i<=n;i++) 10 490.0
{ 15 1102.5
20 1960.0
sum=sum+1.0f/i*sign;
25 3062.5
sign=sign*-1; 30 4410.0
} 35 6002.5
40 7840.0
System.out.println("Sum=" + sum);
45 9922.5
} 50 12250.0
} 55 14822.5
60 17640.0
Output
65 20702.5
Enter value of n:4 70 24010.0
75 27562.5
Sum=0.5833334
80 31360.0
Program 1.14.16 : Write a program to display the value of s 85 35402.5
1 2
for t=1, 5, 10, 15, 20, …100. s = s0 + v0 + 2 a t
90 39690.0 for(i=1;i<=5;i++)
95 44222.5 {
100 49000.0 for(j=1;j<=2;j++)
95 44227.500861 {
100 49005.000954 System.out.print("Hi\t");
Explanation }
System.out.println();
The values of s0, v0 and a are taken from the
}
user.
}
The output is displayed in a tabular form with
}
the values of t and s separated by a horizontal
tab (using the escape sequence “\t”). Output
ge
outside the loop, as it doesn’t match the series Hi Hi
of 5, 10, 15, 20…100. Hi Hi
Hi Hi
The remaining values are calculated and
io led
Hi Hi
displayed using a for loop wherein the value of t
is incremented by 5 after every iteration. Explanation
ic ow
The new value of s is calculated and displayed The value of i is first initialized to 1, and the
again separated with a horizontal tab. value of j is also initialized to 1. The statement
n
This loop is repeated until the value of t in the inner for loop prints the string “Hi” for
bl kn
ge
} *****
} io led Program 1.14.20 : Write a program to display the following
Output
for the user specified number of lines
1 *
11
ic ow
**
111 ***
n
1111 ****
bl kn
11111 *****
Explanation |
at
Pu ch
Output Output
Enter number of lines:6 Enter number of lines:5
*
*
**
**
***
**** ***
***** ****
****** *****
ge
****
***** third thing to be done is to go to the next line.
****** The first inner loop is used to display the
io led
******* number of blank spaces. The blank spaces in
******** first line will be five, if the number of lines is
| six.
ic ow
|
The next line number of blanks spaces will
n lines
reduce by one and keep on reducing in every
n
bl kn
{
The same variable i.e. j can be used in the next
public static void main(String args[])
for loop also as done in the above program.
Te
{
The next for loop i.e. the inner second one is
int i,j,n;
used to display the number of stars equal to the
Scanner sc = new Scanner (System.in);
line number.
System.out.print("Enter number of lines:");
Finally once everything is done for the line we
n=sc.nextInt(); use println() method to go to the next line for
for(i=1;i<=n;i++) the next iteration. This process will continue for
{ n lines, where the value of n is taken from user.
for(j=1;j<=n-i;j++)
Program 1.14.22 : Write a program to display the following
{
asking the user for the number of “*” in the largest line
System.out.print(" ");
*
}
**
for(j=1;j<=i;j++) ***
{ ****
System.out.print("*"); *****
} ******
System.out.println(); *****
} ****
} ***
} **
*
ge
} ****
for(j=1;j<=i;j++) *****
{ ******
io led
*******
System.out.print("*");
******
}
*****
System.out.println();
ic ow
****
} ***
for(i=n-1;i>=1;i--)
n
**
{
bl kn
*
for(j=1;j<=n-i;j++) import java.util.*;
{
at
class Pattern
Pu ch
System.out.print(" ");
{
}
public static void main(String args[])
Te
for(j=1;j<=i;j++)
{
{
System.out.print("*"); int i,j,n;
} Scanner sc = new Scanner (System.in);
System.out.println(); System.out.print("Enter number of * in the largest line:");
} n=sc.nextInt();
} for(i=1;i<=n;i++)
} {
for(j=1;j<=n-i;j++)
Output
{
Enter number of * in the largest line:5 System.out.print(" ");
* }
** for(j=1;j<=i;j++)
*** {
**** System.out.print("* ");
***** }
**** System.out.println();
*** }
** for(i=n-1;i>=1;i--)
* {
ge
}
Enter number of * in the largest line:5 for(j=1;j<=2*i-1;j++)
* {
io led
** System.out.print("*");
*** }
**** System.out.println();
ic ow
***** }
for(i=n-1;i>=1;i--)
n
****
{
bl kn
***
** for(j=1;j<=n-i;j++)
{
at
*
Pu ch
System.out.print(" ");
Explanation }
Te
Explanation Explanation
In this program the operation is again similar In this program the operation is almost similar
to the program 3.2.22. The only difference being to the pervious programs. Only the difference
that here the number of stars (*) in each line is being that instead of stars, here we print the
2 * i -1, where i is the line number. value of j itself. Hence the numbers are printed
instead of stars.
Program 1.14.25 : Write a program to display the following
asking the user for the number of lines. Program 1.14.26 : Write a program to display the following
asking the user for the number of lines.
1
1
12
121
123
12321
1234
1234321
12345
ge
123454321
123456 12345654321
import java.util.*; import java.util.*;
io led
class Pattern class Pattern
{ {
ic ow
public static void main(String args[]) public static void main(String args[])
{ {
n
int i,j,n; int i,j,n;
bl kn
n=sc.nextInt(); n=sc.nextInt();
for(i=1;i<=n;i++) for(i=1;i<=n;i++)
Te
{ {
for(j=1;j<=i;j++) for(j=1;j<=n-i;j++)
{ {
} }
for(j=1;j<=i;j++)
System.out.println();
{
}
System.out.print(j);
}
}
}
for(j=i-1;j>=1;j--)
Output {
Enter number of lines:5 System.out.print(j);
1 }
12 System.out.println();
123 }
1234 }
12345 }
Output System.out.print((char)(j+64));
}
Enter number of lines:5
System.out.println();
1
}
121
}
12321
}
1234321
123454321 Output
ge
line number. The third operation is to print the
ABCDEFEDCBA
numbers from i-1 (where iis line number) to 1.
io led
For each of these three operations there is an Explanation
ABCBA System.out.print((char)(j+64));
ABCDCBA instead of the statement of previous program
at
Pu ch
ABCDEDCBA
System.out.print(j);
ABCDEFEDCBA
Te
System.out.println(); Output
} Enter number of lines:6
} A
} BC
DEF
Output
GHIJ
Enter number of lines:5 KLMNO
1 PQRSTU
23
Explanation
456
7 8 9 10 There is only one change as compared to the
previous program i.e. type casting. Here the
11 12 13 14 15
numbers of previous program are type casted to
Explanation char.
Here the numbers to be printed are not the Here the value of k is added to get the ASCII
ge
same as the value of j i.e. column number. value of ‘A’ and also increment the value of k
Instead the numbers are to be incremented thereafter for the next character.
io led
every time a value is printed. Hence a separate
variable i.e. k is used to keep a track of the Program 1.14.30 : Write a program to display the following
numbers to be printed. pattern.
****
ic ow
BC
import java.util.*;
DEF
class Pattern
at
Pu ch
GHIJ
{
KLMNO
public static void main(String args[])
import java.util.*; {
Te
ge
1 0 1 0 1 -
import java.util.*; -
statements1;
class Pattern
io led
{ -
public static void main(String args[]) -
ic ow
{ }
int i,j,n,k; else
n
Scanner sc = new Scanner (System.in); {
bl kn
for(i=1;i<=n;i++) statements2;
{ -
Te
for(j=0;j<=i-1;j++) -
{ }
System.out.print((i+j)%2 + " "); The set of statements named as statements1 in
} the above syntax are executed if the condition
System.out.println(); given with the if statement is true. The set of
} statements statements2 are not executed in
} this case.
} If the condition specified in the if statement is
Output false then the statements named as
statements2 in the above syntax are executed.
Enter number of lines:7
The set of statements statements1 are not
1
executed in this case.
0 1
1 0 1 Note: The else part is optional i.e. we can have a if
- int sum=0,n,i=2;
Statements Scanner sc = new Scanner (System.in);
- System.out.print("Enter a number:");
-
n=sc.nextInt();
}
while(n%i!=0)
The subsequent section deals with the
{
programs using if-else statement.
i++;
1.15.1 Programs using if-else Statement }
Program 1.15.1 : Write a program to check if the user if(n==i)
entered number is divisible by 10 or not.
{
import java.util.*;
System.out.println("Prime Number");
class Divisible
}
ge
{
public static void main(String args[]) else
{ {
io led
int sum=0,n; System.out.println("Not a prime number");
Scanner sc = new Scanner (System.in); }
System.out.print("Enter a number:");
ic ow
}
n=sc.nextInt();
}
n
if(n%10==0)
bl kn
} Prime Number
}
Te
Explanation
Output A simple logic is used to find out whether the
Enter a number:56 entered number is prime or not. The logic is
Not divisible by 10 similar to the one used by us to check the
number being prime or not.
Explanation
The number entered by user is checked for
We know that a number will be said to be
divisibility by 2, 3 and so on upto the entered
divisible by 10 if and only if the remainder after
number. If it is divisible then the further
dividing the number by 10 is equal to 0.
checking stops and the control comes out of the
Hence we check this condition using the if while loop. In worst case the control will come
statement and accordingly display that the out of the while loop when the value of i is
number is divisible by 0 or not. equal to n, because a number is definitely
Program 1.15.2 : Write a program to check if the entered divisible by itself.
number is prime number or not. Finally when the control comes out of the while
import java.util.*; loop, if n is equal to i, then the number is a
class Prime prime number else it is not. This is checked
{ using the if-else statement.
public static void main(String args[])
{
Program 1.15.3 : Write a program to display first n prime Program 1.15.4 : Write a program to check if the entered
numbers where the value of n is taken from the user. number is Armstrong or not.
import java.util.*; Note : A number is said to be Armstrong number if the
class Prime sum of the cube of its digits is equal to the
{ number itself. For e.g. 153, the sum of the cubes
3 3 3
public static void main(String args[]) is 1 + 5 + 3 = 1+125 + 27 = 153 i.e. the original
{ number itself.
int n,i,x=1; import java.util.*;
Scanner sc = new Scanner (System.in); class Armstrong
System.out.print("Enter a number:"); {
n=sc.nextInt(); public static void main(String args[])
while(n!=0) {
{ int sum=0,digit,n,copy;
ge
x++; Scanner sc = new Scanner (System.in);
i=2; System.out.print("Enter a number:");
while(x%i!=0) n=sc.nextInt();
io led
{ copy=n;
i++; while(n!=0)
}
ic ow
{
if(x==i) digit=n%10;
n
{ sum+=digit*digit*digit;
bl kn
System.out.println(x); n/=10;
n--; }
at
Pu ch
} if(copy==sum)
} System.out.println("Armstrong Number");
} else
Te
ge
System.out.print("Enter year:"); if (condition)
year=sc.nextInt(); {
io led statements;
if(year%4==0 && year%100!=0 || year%100==0 &&
year%400==0) }
System.out.println("Leap Year"); else
ic ow
else {
System.out.println("Not Leap Year"); if(condition)
n
} {
bl kn
} statements;
}
at
Pu ch
Output
|
Enter year:2012
|
Leap Year
Te
|
Explanation else
ge
0-39 Fail Enter marks:93
import java.util.*;
io led Distinction
class Grade
Explanation
{
public static void main(String args[]) The above program is said to implement if else
ic ow
if(marks>=70)
{ type. For example we can have an array of int
System.out.println("Distinction"); type data or float type data etc.
Te
where, a[0] 1
data_type is the data type like int, float, double
a[1] 2
etc.
a[2] 3
array_name is the identifier i.e. the name of
the variable a[3] 4
new is an operator to allocate memory to an a[4] 5
object
a[5] 6
array_size is an integer value which
determines size of the array or memory a[6] 7
locations to be allocated to an array. a[7] 8
For e.g. int a[ ] = new int [10];
a[8] 9
is an array of int type data named ‘a’ and can
ge
a[9] 10
store upto 10 integers indexed from
0 to 9 i.e. 0 to n – 1, where n is the size
io led Fig. 1.16.1 : Memory allocation for an array ‘a’ of 10
The memory allocated to an array also depends integer elements
on the data type i.e. the space required for each We will see some very basic programs of
accepting and displaying the elements of an
ic ow
using functions.
data requires 4 byte memory locations double
at
class Array
To access an element of an array we have to use {
the array selection operator i.e. [ ]. public static void main(String args[])
For e.g. if we want to access the 3rd element of {
int n,i;
an array named ‘a’, then we need to access it as
Scanner sc = new Scanner (System.in);
a[2]. Remember 3rd element will be indexed 2,
System.out.print("Enter no of elements: ");
as the index of first element is 0. n=sc.nextInt();
Hence to access an element we need to use the int a[]=new int [n];
array name or identifier and write the index for(i=0;i<=n-1;i++)
number in brackets. {
System.out.print("Enter a no:");
Another e.g. to access the 9th element of an
a[i]=sc.nextInt();
array ‘x’, we need to write x[8]. }
If numbers from 1 to 10 are stored in an array for(i=0;i<=n-1;i++)
of 10 elements then, the values will be stored in {
the array as shown in the Fig. 1.16.1 each of System.out.println(a[i]);
}
these locations shown in the Fig. 1.16.1 are of
}
four bytes i.e. to store one integer type of data.
}
Output a[i]=sc.nextInt();
}
Enter no of elements:4
for(i=0;i<=n-1;i++)
Enter a no:1
{
Enter a no:2
sum=sum+a[i];
Enter a no:3
}
Enter a no:4
avg=(float)sum/n;
1
System.out.println(“Average=“+avg);
2
}
3
}
4
Output
Explanation
Enter no of elements:4
The array named ‘a’ is declared with a size of n
Enter a no:2
ge
elements. The size is taken to be ‘n’ as the user
Enter a no:3
wants n elements to be stored.
Enter a no:1
io led
The first “for” loop is to accept ‘n’ integers from
Enter a no:4
the user in different index locations numbered
Average=2.5
from 0 to n – 1. In the loop the value of ‘i’ is
ic ow
value entered by the user is stored into the next The first loop as usual is to accept all the
n
index element. elements and the second for loop is to calculate
bl kn
Again in this loop the value of ‘I’ varies from 0 every element is added to it with the index of
to n – 1. Here also the value of ‘i’ is incremented the array ‘a’ from 0 to n – 1.
Te
after every iteration and hence the element Finally this value is divided by the total
displayed in every iteration is the consecutive number of elements i.e. ‘n’ to find the average.
next one in the array. But before that the value of the integer variable
Program 1.16.2 : Write a program to accept ‘n’ integers from ‘sum’ is type casted to float. This is done to take
user into an array and display the average of these numbers. into consideration the fraction part after
import java.util.*; division.
class Average Finally the average is displayed.
{
Program 1.16.3 : Write a program to evaluate the value of
public static void main(String args[])
the following series and display the result.
{ 2
n n
int n,i,sum=0;
x – x
i
2
i
float avg; i=1 i = 1
Scanner sc = new Scanner (System.in);
import java.util.*;
System.out.print("Enter no of elements:");
class Sum
n=sc.nextInt();
{
int a[]=new int [n];
public static void main(String args[])
for(i=0;i<=n-1;i++)
{
{
int n,i,sum1=0,sum2=0,sum;
System.out.print("Enter a no:");
Scanner sc = new Scanner (System.in); Program 1.16.4 : Write a program to evaluate the value of
the standard deviation (s.d.) and display the result.
System.out.print("Enter no of elements:");
n=sc.nextInt();
n
–2
(xi – x )
int a[]=new int [n]; s.d. =
i=i
n
for(i=0;i<=n-1;i++)
{ –
where, x is the average of all the numbers.
System.out.print("Enter a no:"); import java.util.*;
a[i]=sc.nextInt(); class SD
} {
for(i=0;i<=n-1;i++) public static void main(String args[])
{ {
sum1=sum1+a[i]; int n,i;
sum2=sum2+a[i]*a[i]; float avg,sum=0,sd;
ge
Scanner sc = new Scanner (System.in);
}
System.out.print("Enter no of elements:");
sum=sum2-sum1*sum1;
n=sc.nextInt();
System.out.println(“Sum=“+sum);
io led
int a[]=new int [n];
}
for(i=0;i<=n-1;i++)
} {
ic ow
Enter a no:1
for(i=0;i<=n-1;i++)
Enter a no:2
{
at
Enter a no:3
Pu ch
sum=sum+a[i];
Enter a no:4 }
Enter a no:5 avg=sum/n;
Te
Sum=-170 sum=0;
Explanation for(i=0;i<=n-1;i++)
{
The method to initialize and accept the
sum=sum+(a[i]-avg)*(a[i]-avg);
elements from user is same as in previous
}
programs.
sum=sum/n;
Note, the expression says elements from 1 to n,
sd=(float)Math.pow(sum,0.5);
but we go from 0 to n – 1. This is because, the
System.out.println(“SD=“+sd);
index of the elements in the array are from 0 to
n-1 as already seen. }
}
The logic is very simple. The two term sums are
calculated i.e. sum1 and sum2. These variables Output
i = 1 x i
n n
sum1 and sum2 are x2
i=0 i
and Enter no of elements:4
respectively. Enter a no:2
These values are calculated in the “for” loop. Enter a no:3
Then the final result is calculated by Enter a no:4
subtracting the square of second term i.e. sum2 Enter a no:3
from the first term i.e. sum1. And this result is
SD=0.70710677
displayed.
Explanation for(i=0;i<=(n-1);i++)
{
The method to initialize and accept the
xi=xi+x[i];
elements from user is same as in previous yi=yi+y[i];
programs. xiyi=xiyi+x[i]*y[i];
Also to calculate the average, we have already xi2=xi2+x[i]*x[i];
}
seen a program i.e. 1.16.2.
m =(float)(n*xiyi-xi*yi)/(n*xi2-yi*yi);
The average is calculated in the same manner c=(yi-m*xi)/n;
so as to get the average in “float” type data System.out.println(“Equation of straight line is
format. y=“+m+”x+”+c);
}
Then the new sum is calculated to find the
}
–
value of the term ( xi – x )2 in the variable
Output
sum1.
ge
Enter no of points:3
Finally the above calculated term is divided by
Enter x co-ordinate:1
“n” i.e. the total number of elements and its
Enter y co-ordinate:1
io led
square root is calculated. This is the value of
Enter x co-ordinate:3
standard deviation which is then displayed.
Enter y co-ordinate:3
ic ow
Program 1.16.5 : Write a program in Java for fitting a straight Enter x co-ordinate:5
line through a set of points (xi, yi), i = 1, 2, 3 .... n. The
Enter y co-ordinate:5
n
straight line equation is y = mx + c and the values of m and c
are given by
Equation of straight line is y=1.0x+0.0
bl kn
i i i i
Pu ch
m=
n ( x ) – ( y)
2 2 import java.util.*;
i
i
class Large
Te
{
1
c=n ( y – m x)
i i public static void main(String args[])
import java.util.*; {
class Line int n,i,large;
{ Scanner sc = new Scanner (System.in);
public static void main(String args[]) System.out.print("Enter no of elements:");
{ n=sc.nextInt();
int n,i,xi=0,yi=0,xiyi=0,xi2=0; int a[]=new int [n];
float m,c; for(i=0;i<=n-1;i++)
Scanner sc = new Scanner (System.in); {
System.out.print("Enter no of points:"); System.out.print("Enter a no:");
n=sc.nextInt(); a[i]=sc.nextInt();
int x[]=new int [n]; }
int y[]=new int [n]; large=a[0];
for(i=0;i<=n-1;i++) for(i=0;i<=n-1;i++)
{ {
System.out.print("Enter x co-ordinate:"); if(large<a[i])
x[i]=sc.nextInt(); large=a[i];
System.out.print("Enter y co-ordinate:"); }
y[i]=sc.nextInt(); System.out.println(“Largest no=“+large);
} }
}
Output Output
ge
The first element is initially assumed to be the with each of the remaining elements in the
largest number. array. If an element found is smaller, then the
value of the variable “small”, then this number
io led
Thereafter in the “for” loop, each of the other
is copied into the variable “small”. Finally the
elements i.e. starting from the second element
value of this variable “small” is displayed.
is compared with the value of the variable
ic ow
“large”. Whenever a larger value is found, this Program 1.16.8 : Write a program to find and display the
new value is copied into the variable “large” reverse of an array.
n
using the if statement. import java.util.*;
bl kn
class Reverse{
Program 1.16.7 : Write a program to find the smallest of ‘n’ public static void main(String args[])
at
Pu ch
{
System.out.print("Enter no of elements:");
public static void main(String args[])
n=sc.nextInt();
{
int a[]=new int [n];
int n,i,small;
Scanner sc = new Scanner (System.in); int b[]=new int [n];
System.out.print("Enter no of elements:"); for(i=0;i<=n-1;i++)
n=sc.nextInt(); {
int a[]=new int [n]; System.out.print("Enter a no:");
for(i=0;i<=n-1;i++) a[i]=sc.nextInt();
{ }
System.out.print("Enter a no:"); for(i=0;i<=n-1;i++)
a[i]=sc.nextInt(); {
} b[n-i-1]=a[i];
small=a[0]; }
for(i=0;i<=n-1;i++) for(i=0;i<=n-1;i++)
{
{
if(small>a[i])
System.out.println(b[i]);
small=a[i];
}
}
}
System.out.println(“Smallest no=“+small);
} }
}
ge
Explanation
}
We have accepted the array in the same }
manner as in the previous program. Here the
io led
Output
array is reversed and put into another array.
Enter no of elements:5
The logic to reverse is very simple in this case,
Enter a no:1
ic ow
Enter a no:4
expression n-i-1, will be n–1 i.e. the last
Enter a no:5
element.
at
5
Pu ch
ge
if(i==n) System.out.print("Enter a no:");
System.out.println("No. not found"); a[i]=sc.nextInt();
else }
io led
System.out.println("Index =" + i); for(i=0;i<=n-2;i++)
} {
} for(j=0;j<=n-2;j++)
ic ow
{
Output if(a[j]>a[j+1])
n
Enter no of elements:5 {
bl kn
Enter a no:3
}
Enter a no:4 }
Te
Enter a no:5 }
Enter the no to be searched:4 System.out.println("After Sorting");
Index =3 for(i=0;i<=n-1;i++)
{
Explanation System.out.println(a[i]);
The element to be searched is compared with }
}
each of the elements. Whenever the element to
}
be searched is found, the “if” condition is
Output
satisfied and the break statement transfers the
control outside the “for” loop. This is also called Enter no of elements:5
as sequential search algorithm i.e. the element Enter a no:4
is searched sequentially in the list i.e. array of Enter a no:6
elements. Enter a no:1
Enter a no:85
The value of “i” is compared with the value of
Enter a no:9
“n”; it they are equal then it indicates that the After Sorting
control has come out of the “for” loop because 1
the number was not found in the array. 4
Hence it displays “Not Found”, else it displays 6
the index “i” where the element was found. 9
85
Explanation
Bubble sorting algorithm says that compare the consecutive elements from the beginning of array till
the end. Wherever the proper sorting is not found, swap the numbers. And this entire set of
comparisons is to be repeated for n-1 times. Let us take the example of numbers as given in the output
of the program to understand this logic.
The first two elements are compared i.e. 4 and 6, since they are already sorted i.e. 4 < 6, no swapping
takes place. The next comparison is the next two elements i.e. 6 and 1; now these are not sorted i.e.
6 > 1, hence these are swapped. This continues until the last two elements are compared as shown in
Fig. 1.16.2.
You will notice in Fig. 1.16.2, after all the comparisons done in the first iteration; the largest number
has reached to the last position. But thenumbers are still not sorted properly. To sort these numbers we
need to repeat the above process for n-1 times.
Note : Since the “j” and the “j + 1” elements are compared the value of “j” must go maximum upto n – 2. When the value
ge
of “j” is n – 2, we will be comparing the n – 2 and n-1 i.e. the last two elements. Also since the value of “i”is starting
from 0, we have to go upto n – 2, as we have to perform n–1 comparisons.
io led
Initial After first After second After third After fourth
values comparison comparison comparison comparison
Iteration 4>6, No, hence no 6>1, Yes, hence 6>85, No, hence no 85>9, Yes, hence
1 swap swap swap swap
ic ow
4 4 4 4 4
n
6 6 1 1 1
bl kn
1 1 6 6 6
85 85 85 85 9
at
9 9 9 9 85
Pu ch
Iteration 4>1, Yes, hence 4>6, No, hence no 6>9, No, hence no 9>85, No, hence no
2 swap swap swap swap
Te
4 1 1 1 1
1 4 4 4 4
6 6 6 6 6
9 9 9 9 9
85 85 85 85 85
Iteration 1>4, No, hence no 4>6, No, hence no 6>9, No, hence no 9>85, No, hence no
3 swap swap swap swap
4 1 1 1 1
1 4 4 4 4
6 6 6 6 6
9 9 9 9 9
85 85 85 85 85
Iteration 1>4, No, hence no 4>6, No, hence no 6>9, No, hence no 9>85, No, hence no
4 swap swap swap swap
4 1 1 1 1
1 4 4 4 4
6 6 6 6 6
9 9 9 9 9
85 85 85 85 85
Fig. 1.16.2 : Bubble sorting example
You may also notice in the Fig. 1.16.2, that the sorting is already completed after the second iteration.
The remaining two iterations do no swapping. But, we have to consider the worst case condition i.e. if
all the numbers entered by the user were in exactly reverse order. In this case we would require all the
four iterations. This is explained in the Fig. 1.16.3.
Here, you will notice that till the last iteration the swapping is required. The worst case condition is
one in which the numbers are exactly in the reverse order as expected to be. You will notice in this case
the numbers are in descending order and they are to be sorted in ascending order.
ge
4 io led5 3 3 3
3 3 5 2 2
2 2 2 5 1
1 1 1 1 5
ic ow
Iteration 4>3, Yes, hence 4>2, Yes, hence 4>1, Yes, hence 4>5, No, hence no
n
2 swap swap swap swap
bl kn
4 3 3 3 3
3 4 2 2 2
at
Pu ch
2 2 4 1 1
1 1 1 4 4
Te
5 5 5 5 5
Iteration 3>2, Yes, hence 3>1, Yes, hence 3>4, No, hence no 4>5, No, hence no
3 swap swap swap swap
3 2 2 2 2
2 3 1 1 1
1 1 3 3 3
4 4 4 4 4
5 5 5 5 5
Iteration 2>1, Yes, hence 2>3, No, hence no 3>4, No, hence no 4>5, No, hence no
4 swap swap swap swap
2 1 1 1 1
1 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
Fig. 1.16.3 : Worst case condition of sorting numbers using Bubble sorting
After Sorting
Program 1.16.12 : Write a program to sort numbers in
descending order. OR Write a program to implement bubble
85
sorting algorithm for sorting numbers in descending order. 9
import java.util.*; 6
class Descend 4
{ 1
public static void main(String args[]) Explanation
{
This is implemented using the same logic as in
int n,i,j,temp;
the previous program i.e. bubble sorting. The only
Scanner sc = new Scanner (System.in);
difference here is that the numbers are swapped if
System.out.print("Enter no of elements:");
the first number is smaller than the consecutive
n=sc.nextInt();
next one. The remaining logic is entirely same.
int a[]=new int [n];
ge
for(i=0;i<=n-1;i++) 1.16.1 Multi-dimensional Arrays
{
Multi dimensional arrays are used to store data
io led
System.out.print("Enter a no:");
that requires multiple references for e.g. a
a[i]=sc.nextInt();
matrix requires two references namely row
}
ic ow
To understand how a matrix element can be Program 1.16.13 : Write a program to accept an m n
matrix and display it in natural form.
accessed Fig. 1.16.5 explains it all, but the
import java.util.*;
elements of this matrix are stored in a different
class Matrix
manner in the memory as shown in Fig.1.16.3.
{
This figure assumes the values in matrix as 1,
public static void main(String args[])
2, 3 … 9. {
Memory int m,n,i,j;
Scanner sc = new Scanner (System.in);
System.out.print("Enter no of rows and columns:");
m=sc.nextInt();
a[0][0] 1
n=sc.nextInt();
a[0][1] 2 int a[][]=new int [m][n];
ge
for(i=0;i<=m-1;i++)
a[0][2] 3
io led {
a[1][0] 4 for(j=0;j<=n-1;j++)
{
a[1][1] 5 System.out.print("Enter a no:");
ic ow
a[1][2] 6 a[i][j]=sc.nextInt();
}
n
a[2][0] 7 }
bl kn
for(i=0;i<=m-1;i++)
a[2][1] 8
{
at
Pu ch
a[2][2] 9 for(j=0;j<=n-1;j++)
{
Fig. 1.16.5 : Arrangement of the elements in a two
Te
System.out.print(a[i][j]+"\t");
dimensional array }
As shown in Fig. 1.16.5, the elements are stored System.out.println();
in a sequential manner with all the elements of }
a row together one below the other, and then }
}
the next row and so on.
Output
The method of accepting elements of an m n
matrix and displaying it in natural form is Enter no of rows and columns:2
shown in Program 1.16.13 3
Enter a no:1
(Note : m is the number of rows and n is the
Enter a no:2
number of columns).
Enter a no:3
The values of m and n must be taken from user. Enter a no:4
Natural form display of a 2 4 matrix is as Enter a no:5
shown below. Enter a no:6
1 2 3 4 1 2 3
4 5 6
5 6 7 8
Explanation Output
First, the user is asked for number of rows and Enter no of rows and columns:3
columns. To accept the elements of the matrix, 3
we need a nested “for” loop as shown. The outer Enter a no:1
loop has “i” as a counter for the row number Enter a no:2
and hence is counted from 0 to m-1; while the Enter a no:3
inner loop has “j” as a counter for the column Enter a no:4
number and hence is counted from 0 to n-1. Enter a no:5
The displaying of the elements of the matrix Enter a no:6
also requires a nested for loop as required for Enter a no:7
accepting the matrix elements from the user. Enter a no:8
Enter a no:9
Program 1.16.14 : Write a program to find and display the
Sum=15
ge
sum of the diagonal elements of a square matrix.
import java.util.*; Explanation
class Diagonal The method to accept the elements of the
io led
{ matrix is same as the previous program.
public static void main(String args[]) The next nested “for” loop is for finding the sum
ic ow
n=m;
int a[][]=new int [m][n]; Program 1.16.15 : Write a program to add two matrices of
for(i=0;i<=m-1;i++) size m n.
Te
{ import java.util.*;
for(j=0;j<=n-1;j++) class Sum
{ {
System.out.print("Enter a no:"); public static void main(String args[])
a[i][j]=sc.nextInt(); {
} int m,n,i,j;
} Scanner sc = new Scanner (System.in);
for(i=0;i<=m-1;i++) System.out.print("Enter no of rows and columns:");
{ m=sc.nextInt();
for(j=0;j<=n-1;j++) n=sc.nextInt();
{ int a[][]=new int [m][n];
if(i==j) int b[][]=new int [m][n];
sum=sum+a[i][j]; int c[][]=new int [m][n];
} System.out.println(“Matrix A”);
} for(i=0;i<=m-1;i++)
System.out.println("Sum"+sum); {
} for(j=0;j<=n-1;j++)
} {
System.out.print("Enter a no:");
ge
{ displayed in natural form.
for(j=0;j<=n-1;j++) io led Program 1.16.16 : Write a program to find the transpose of a
{ matrix of size m n.
c[i][j]=a[i][j]+b[i][j]; import java.util.*;
} class Transpose
ic ow
} {
System.out.println(“Sum Matrix”); public static void main(String args[])
n
for(i=0;i<=m-1;i++) {
bl kn
{ int m,n,i,j;
for(j=0;j<=n-1;j++) Scanner sc = new Scanner (System.in);
at
Pu ch
} n=sc.nextInt();
System.out.println(); int a[][]=new int [m][n];
} int b[][]=new int [n][m];
} System.out.println(“Matrix A”);
} for(i=0;i<=m-1;i++)
Output {
for(j=0;j<=n-1;j++)
Enter no of rows and columns:2
{
3
System.out.print("Enter a no:");
Matrix A
a[i][j]=sc.nextInt();
Enter a no:1
}
Enter a no:2
}
Enter a no:3
for(i=0;i<=m-1;i++)
Enter a no:4
{
Enter a no:5
for(j=0;j<=n-1;j++)
Enter a no:6
{
Matrix B
b[j][i]=a[i][j];
Enter a no:1
}
Enter a no:2
}
Enter a no:3
System.out.println("Transpose Matrix"); Hence, the value of outer “for” loop i.e. “i” varies
for(i=0;i<=n-1;i++) from 0 to n-1, while that of the inner loop i.e. “j”
{ varies from 0 to m-1.
for(j=0;j<=m-1;j++)
Program 1.16.17 : Write a program to find the transpose of a
{ square matrix.
System.out.print(b[i][j]+"\t");
import java.util.*;
}
class Transpose
System.out.println();
{
}
public static void main(String args[])
}
{
}
int m,i,j,temp;
Output Scanner sc = new Scanner (System.in);
System.out.print("Enter value of m:");
ge
Enter values of m and n:2 3
Matrix A m=sc.nextInt();
Enter a no:1 int a[][]=new int [m][m];
io led
Enter a no:2 for(i=0;i<=m-1;i++)
Enter a no:3 {
Enter a no:4 for(j=0;j<=m-1;j++)
ic ow
Enter a no:5 {
System.out.print("Enter a no:");
n
Enter a no:6
a[i][j]=sc.nextInt();
bl kn
Transpose Matrix
1 4 }
}
at
2 5
Pu ch
3 6 for(i=0;i<=m-1;i++)
{
Te
Explanation
for(j=i;j<=m-1;j++)
The method to accept the elements of the {
matrix is same as the previous program. temp=a[i][j];
The transpose of a matrix is shown below. a[i][j]=a[j][i];
1 2 a[j][i]=temp;
3 4 , the transpose of this
If matrix A = }
5 6 }
1 3 5
matrix will be 2 4 6 System.out.println("Transpose Matrix");
for(i=0;i<=m-1;i++)
i.e. the column 1 of matrix A, will be the row
{
1 of its transpose; similarly column 2 will
for(j=0;j<=m-1;j++)
become row 2 and so on.
{
The transpose is found by just placing the a[i][j] System.out.print(a[i][j]+ "\t");
term in b[j][i], using the same type of nested }
“for” loop. System.out.println();
Also while displaying the transpose of the }
matrix i.e. the matrix “b”, we need to take care }
that the number of rows and columns are }
reversed.
Output {
Enter value of m:3 int m,n,p,i,j,k;
Enter a no:1 Scanner sc = new Scanner (System.in);
Enter a no:2 System.out.print("Enter values of m, n and p:");
Enter a no:3 m=sc.nextInt();
Enter a no:4 n=sc.nextInt();
Enter a no:5 p=sc.nextInt();
Enter a no:6 int a[][]=new int [m][n];
Enter a no:7 int b[][]=new int [n][p];
Enter a no:8 int c[][]=new int [m][p];
Enter a no:9 System.out.println("Matrix A");
Transpose Matrix
for(i=0;i<=m-1;i++)
1 4 7
{
2 5 8
ge
for(j=0;j<=n-1;j++)
3 6 9
{
Explanation :
io led System.out.print("Enter a no:");
The method to accept the elements of the a[i][j]=sc.nextInt();
matrix is same as the previous program. }
ic ow
{
for(j=0;j<=p-1;j++)
at
Pu ch
{
System.out.print("Enter a no:");
Te
b[i][j]=sc.nextInt();
Fig. 1.16.6 : Transpose of a square matrix }
Here, the elements are swapped since it is a }
square matrix. Care is to be taken that for for(i=0;i<=m-1;i++)
every new row; the swapping is to be started {
from the element after the swapped ones. For for(j=0;j<=p-1;j++)
{
example, the first element of the second row is
c[i][j]=0;
already swapped with the second element of
for(k=0;k<=n-1;k++)
first row while going along the first row. Hence,
{
in the second row swapping has to begin from
c[i][j]+=a[i][k]*b[k][j];
the second element and not the first one. }
Similarly, for the third row, we need to start }
from the third element, for the fourth row from }
fourth element and so on. System.out.println("Product Matrix");
for(i=0;i<=m-1;i++)
Program 1.16.18 : Write a program to multiply two matrices.
{
import java.util.*;
for(j=0;j<=p-1;j++)
class Product {
{ System.out.print(c[i][j]+"\t");
public static void main(String args[])
ge
Enter a no:3
Enter a no:4 (a2, 0 b0, 2) + (a2, 1 b1, 2)
Enter a no:5 Fig. 1.16.7 : Multiplication of matrices
io led
Enter a no:6 Hence, in the Fig. 1.16.7 you will notice that to
calculate each term of the resultant matrix, we
Matrix B need to add many product terms. This is what
Enter a no:1 is implemented by the three level nested loops.
ic ow
Enter a no:4
expression value.
Enter a no:5 To find each element, you will notice that the
at
Enter a no:6
Pu ch
ge
a[i][0]=sc.nextInt();
Enter roll no and marks in three subjects:4
a[i][1]=sc.nextInt();
90
a[i][2]=sc.nextInt();
io led 90
a[i][3]=sc.nextInt(); 97
a[i][4]=a[i][1]+a[i][2]+a[i][3]; Enter roll no and marks in three subjects:5
ic ow
} 98
System.out.println(“Roll NO\tSub 1\tSub 2\tSub 98
n
3\tTotal\n”); 95
bl kn
for(j=0;j<=4;j++) 2 90 98 99 287
{ 3 97 89 90 276
Te
System.out.print(a[i][j]+"\t"); 4 90 90 97 277
} 5 98 98 95 291
Highest total marks is:291 and obtained by student with roll
System.out.println();
number:5
}
largeroll=a[0][0]; 1.16.2 Arraycopy()
largetotal=a[0][4]; This static method is available in the class
for(i=0;i<=4;i++) “System” of the package java.lang. This method
{ is used to copy an array from another.
if(a[i][4]>largetotal) The speciality of this method is that you can
{ select the starting location of source and
largeroll=a[i][0]; destination array, and also the number of
largetotal=a[i][4]; elements can be selected.
ge
class ArrayCopy The second case array ‘a’ is copied from element
{
number ‘0’ onwards into array ‘b’ from element
public static void main(String args[])
io led number ‘1’ onwards. The number of elements
{
copied in this case is n-1 and then the array ‘b’
int n,i;
is displayed.
Scanner sc = new Scanner (System.in);
ic ow
System.out.print("Enter number of elements:"); The third case array ‘a’ is copied from element
n=sc.nextInt(); number ‘1’ onwards into array ‘b’ from element
n
int a[]=new int [n]; number ‘0’ onwards. The number of elements
bl kn
int b[]=new int [n]; copied in this case is also n-1 and then the
for(i=0;i<=n-1;i++) array ‘b’ is displayed.
at
Pu ch
{
System.out.print("Enter a no:"); 1.17 Revisiting Strings
Te
a[i]=sc.nextInt();
} Strings used to be array of characters in C/C++.
System.arraycopy(a,0,b,0,a.length); But in Java, we have been using them and we
for(i=0;i<=n-1;i++) have seen many times that it is a class. And the
{
variable of string is actually an object of the
System.out.print(b[i]+"\t");
class String. The advantage is that, the class
}
System.out.println(); String has many member methods, that help
System.arraycopy(a,0,b,1,a.length-1); making our programs very simple especially to
for(i=0;i<=n-1;i++) handle the strings type data.
{ There is also a method to convert a String
System.out.print(b[i]+"\t");
object into an array of characters and then
}
handle it in the same manner as was done in
System.out.println();
System.arraycopy(a,1,b,0,a.length-1); C/C++. We will also go through these methods
for(i=0;i<=n-1;i++) and in some programs we will handle strings as
{ an array of character type data.
System.out.print(b[i]+"\t");
We will first go through some of the important
}
methods supported by the class String and then
}
} make some programs using those methods.
The String class has a number of methods for its objects. Some of them are listed in the table below
with their operation.
Table 1.17.1 : Methods of string class
Method Operation
.length() Returns an Integer value equal to the length of the string
.toLowerCase() It returns the string object through which it is called with the string
converted into lower case
.toUpperCase() It returns the string object through which it is called with the string
converted into upper case
.trim() This method removes the blank spaces at the end of a string.
ge
.replace(char, char) This method replaces all the occurrences of the first character with the
second character passed to the method.
io led
.equals(String) This method compares the string object through which it is called and the
string object passed to this method. It returns true if the two strings are
ic ow
object passed to this method. It returns true if the two strings are equal
else returns false.
at
Pu ch
.compareTo(String) This method compares the string object through which it is called and the
string object passed to this method. It returns ‘0’ if the two strings are
equal. It returns positive value if the string object through which it is
Te
We will use these methods in the following programs and understand their operation much better.
ge
} str=str.concat(str2);
} io led }
Output }
The string is simply accepted from the user and Enter a String:
then it is converted to upper case using the alL tHe beSt
at
Pu ch
Finally the string is displayed. This kind of Program 1.17.4 : Develop a Java program that determines
the number of days in a given semester. Input to the program
string with first alphabets capital of each word
is year, month and day information of the first and the last
is called as title case. days of a semester. The program should accept the date
information as a single string instead of accepting year,
Program 1.17.3 : Write a program to capitalize the first
month and day information separately. The input string must
character of first word from a sentence taken from user i.e.
be in the MM/DD/YYYY format. (Assuming the semester
convert a string to sentence case.
starts and ends in the same year)
import java.util.*; import java.util.*;
class SentenceCase class Days
{ {
public static void main(String args[]) public static void main(String args[])
{ {
String str,str1,str2; String str,str1;
int i,n; int sd,sm,sy,ed,em,ey,i,total;
ge
Scanner sc = new Scanner (System.in); int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
System.out.println("Enter a String:"); Scanner sc = new Scanner (System.in);
System.out.println("Enter the Starting date of the semester
str=sc.nextLine();
io led
(MM/DD/YYYY):");
str=str.toLowerCase();
str=sc.nextLine();
str1=str.substring(1);
str1=str.substring(0,2);
ic ow
str=str.substring(0,1); sm=Integer.parseInt(str1);
str=str.toUpperCase(); str1=str.substring(3,5);
n
str=str.concat(str1); sd=Integer.parseInt(str1);
bl kn
n=str.length(); str1=str.substring(6,10);
System.out.println(str); sy=Integer.parseInt(str1);
at
Pu ch
str=sc.nextLine();
Output
str1=str.substring(0,2);
Enter a String: em=Integer.parseInt(str1);
all thE besT str1=str.substring(3,5);
All the best ed=Integer.parseInt(str1);
str1=str.substring(6,10);
Explanation
ey=Integer.parseInt(str1);
The string is simply accepted from the user and total=ed;
then it is converted to lower case using the for(i=sm;i<=em-2;i++)
method discussed earlier. The returned string {
is put into the same object. total+=days[i];
}
The string is then divided into two parts viz.
total+=days[sm-1]-sd+1;
the first character and the remaining string.
if((sy%4==0 && sy%100!=0 && sm<=2 && em>2)
The first character is then converted to upper || (sy%100==0 && sy%400==0 && sm<=2 &&
case and then concatenated again to get the em>2))
new string. total++;
Finally the string is displayed. This kind of System.out.println("Total Days="+total);
}
string with first alphabets capital of each word
}
is called as title case.
ge
The same procedure is repeated for the ending 2 i
date of the semester. 3 s
io led
Then the days of the last month are directly 4
added as the ending date is the number of days 5 i
in that month for which the semester is on. 6 s
ic ow
str=sc.nextLine(); n=str.length();
n=str.length(); char c[]=new char[n];
char c[]=new char[n]; c=str.toCharArray();
c=str.toCharArray(); for(i=0;i<=n-1;i++)
for(i=0;i<=n-1;i++)
{
{
if(c[i]==‘a’ || c[i]==‘e’ || c[i]==‘i’ || c[i]==‘o’
if(c[i]==‘a’ || c[i]==‘e’ || c[i]==‘i’ || c[i]==‘o’
|| c[i]==‘u’ || c[i]==‘A’ || c[i]==‘E’ || c[i]==‘I’
|| c[i]==‘u’ || c[i]==‘A’ || c[i]==‘E’ || c[i]==‘I’
|| c[i]==‘O’ || c[i]==‘U’)
|| c[i]==‘O’ || c[i]==‘U’)
countv++;
count++;
} else if(c[i]==‘ ‘)
System.out.println(count+" Vowels"); counts++;
ge
} else if(c[i]>=‘0’ && c[i]<=‘9’)
} io led countd++;
Output else if((c[i]>=‘a’ && c[i]<=‘z’) || (c[i]>=‘A’ &&
c[i]<=‘Z’))
Enter a String:
countc++;
ic ow
Explanation
spaces\n”+countd+” Digits\n”+countc+”
The string is converted to an array of Consonants”);
at
Pu ch
case. Output
Program 1.17.8 : Write a Java program to count the number System.out.println(countu+" Upper case
of upper case, lower case, blank spaces and digits in a alphabets\n”+counts+" spaces\n"+countd+"
string. Digits\n"+countl+" Lower case alphabets");
}
import java.util.*;
class Count }
ge
Output
public static void main(String args[]) Enter a String:
{
io led There are 20 benches
String str; 1 Upper case alphabets
int countu=0,i,n,countd=0,counts=0,countl=0; 3 spaces
ic ow
str=sc.nextLine();
Explanation
n=str.length();
The string is converted to an array of
at
Pu ch
for(i=0;i<=n-1;i++)
with lower case alphabets, spaces, digits and
{
upper case alphabets as in the previous
if(c[i]>=‘A’ && c[i]<=‘Z’) program. Every time one of the things is found
countu++; the corresponding counter is incremented.
else if(c[i]==‘ ‘) Finally these counts are displayed.
Program 1.17.9 : Write a Java program to check if the string is palindrome or not.
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String str;
int i,n;
Scanner sc = new Scanner (System.in);
System.out.println("Enter a String:");
str=sc.nextLine();
n=str.length();
char c[]=new char[n];
char rev[]=new char[n];
c=str.toCharArray();
for(i=0;i<=n-1;i++)
{
rev[n-i-1]=c[i];
}
for(i=0;i<=n-1;i++)
{
if(rev[i]!=c[i])
break;
}
if(n==i)
System.out.println("Palindrome");
else
ge
System.out.println("Not Palindrome");
} io led
}
Output
Enter a String:
ic ow
bench
n
Not Palindrome
bl kn
Explanation
at
Pu ch
The string is converted to an array of characters using the toCharArray() method. The char array is
reversed in another array named rev. To reverse the array, the ith element of array is stored in the
Te
The reverse array is then compared element by element with the original array. If the comparison is
found to be not equal then the control breaks out of the loop and in this case the value of ‘n’ and ‘i’ are
not equal, it display “Not Palindrome”. Else if the control comes out of the loop then it indicates all
elements are same hence it is a “Palindrome”.
We have already seen two methods of making a string in Java. The first method was an object of class
String and the other method is an array of char type data.
Another way of making a string in Java is making an object of StringBuffer class. One major speciality
of the object of this class is that it is mutable.
The size of this object can be changed again and again during runtime i.e. we can insert, append, delete
etc a character from the string.
An object of StringBuffer has some advantages of extra methods provided in the class. Let us see the
methods supported in this class.
Method Operation
capacity() This method returns the current capacity of the StringBuffer object.
length() This method returns an integer value equal to the length of the string
setCharAt(int,char) The character passed is set at the index specified in the brackets
charAt(int) The method returns the character at the index mentioned in the brackets.
toString() Converts the string buffer data into a string
insert(int,char) Inserts the character passed at the index passed.
delete(int,int) Deletes the substring from the starting to ending indices passed to the method
replace(int,int,String) Replaces the string passed into the original string from the starting to ending
indices passed to the method.
ge
reverse() Reverses the original string
append(String) Appends the string passed to the original string.
io led
In the string buffer class we have the reverse method. Let us see a program to check palindrome using
string buffer methods.
ic ow
Program 1.17.10 : Write a Java program to check if the string is palindrome or not using StringBuffer object.
import java.util.*;
n
class Palindrome
bl kn
{
public static void main(String args[])
at
Pu ch
{
String str,rev;
Te
Output
Enter a String:
nitIN
Palindrome
Explanation
The string is converted to an object of class StringBuffer using the append() method i.e. a string is
appended to an object of StringBuffer.
Then this object of StringBuffer is reversed and converted back to an object of class String using the
toString() method which returns a string object of the string in a StringBuffer object.
The two strings are compared ignoring the case and if they are equal it displays “Palindrome” else it
displays “Palindrome”.
ge
io led
ic ow
n
bl kn
at
Pu ch
Te
Syllabus
Class : Creating a Class, Visibility/Access Modifiers, Encapsulation, Methods: Adding a Method to Class, Returning a
Value, Adding a Method That Takes Parameters, The ‘this’ Keyword, Method Overloading, Object Creation, Using Object
ge
as a Parameters, Returning Object, Array of Objects, Memory Allocation: ‘new’, Memory Recovery: ‘delete’, Static Data
Members, Static Methods, Forward Declaration, Class as Abstract Data Types (ADTs), Classes as Objects.
io led
ic ow
The structure of object oriented programs as 2.1.1 Class and Object : Introduction
discussed in chapter 1, is also shown in (SPPU - Dec. 16, May 17, Dec. 18)
Fig. 2.1.1.
Q. What is object-oriented programming ? List basic
concepts of it ? Explain each concept. (10 Marks)
Q. Explain the benefits of object oriented
programming. (8 Marks)
Q. Define the following terms :
(1) Object (2) Class (2 Marks)
Q. Define class with it's syntax. (2 Marks)
Q. Write down characteristics of object oriented
programming. (4 Marks)
Q. Define the terms polymorphism, data abstraction.
ge
(Dec. 16, 4 Marks)
Q. Explain various features of Object Oriented
io led
Programming.
Fig. 2.1.1 : Structure of an object oriented program (May 17, 4 Marks, Dec. 18, 6 Marks, May 19, 6 Marks)
ic ow
1. Class is a reference Structure is a value problems that the data or the objects are
type and its object is type that is why its more important than the procedure or the
method to perform a task. Hence, in object
Te
ge
changed, which require to access the data.
The data of an object is hidden from other
8. It follows a bottom-up approach. In this objects. This is called as encapsulation.
io led
type of approach, each element is first Encapsulation is achieved by putting data and
specified in detail and then the entire functions associated with it into a class.
system is made using these elements. You
ic ow
5. Inheritance
will notice in the programming of C++, that
The mechanism of deriving the properties of
n
this approach of bottom-up approach makes
bl kn
Polymorphism, etc. Let us understand them one different forms. Hence, polymorphism means
multiple forms of the same thing. This topic
by one.
will also be covered in detail in the later
1. Class
sections
2. Object
2.1.2 Introduction to Objects
3. Data abstraction
An object is an instance or an example of a class.
4. Data encapsulation
For example if “HumanBeing” is a class, then
5. Inheritance you and me are examples or objects of this class.
6. Polymorphism A real-world object or the object of a class has
two characteristics:
1. Class
1. State 2. Behavior
It is a type or a category of things. It is similar
We will understand these concepts in the next
to a structure with the difference that it can
sub-section.
also have functions besides data items. A
structure, we have seen, can have only data
2.1.2(A) State and Behaviour of an Object
variables but a class can have data members as The state of an object can be related to the
well as function members. variables.
For example if there is a class like “Student”, The access specifiers are as listed below :
then some of the states of the object of this class
1. public 2. protected
can be :
1. Name of the student, 3. default 4. private
ge
2.2.1 Access Specifiers in C++ io led 2. private
These access specifiers are used to specify the the same class.
access of the data and function members of a
3. protected
n
class
bl kn
4. private protected
A “protected” access specifier indicates that only
This gives a visibility level between the
classes derieved can use this member. A
“protected” and “private”. These members can
derieved class concept will be dealt later in the
be accessed only by the sub classes that can be
topic called as Inheritance.
of the same package or other package. This
A “private” access specifier indicates that only access specifier is not available in some later
the functions of the same class can access the versions of JDK.
member.
5. default
2.2.2 Introduction to Java Access Modifiers
Java also provides a default specifier which,as
The access to the members of a class i.e. the the name says is the access specifier for those
constructors, methods and fields of class is members where no access modifier is present.
controlled by access specifiers. All fields and methods that have no declared
Thus access specifiers indicate who can access access specifier are accessible only by the
the members of a class.
methods of same class. This access specifier is
For encapsulation, we should keep the data also many times termed as “friend”.
fields in minimal access while method members
The Table 2.2.1, shows the scope of access of the
in maximal access.
members of a class.
ge
Q. Explain syntax for declaring the function inside the
functions outside the class is called as class and outside the class with example.
encapsulation.
(4 Marks)
io led
The data when declared as private, cannot be
accessed by any method outside the class. When the member functions of a class are
The external method if requires access to the defined inside the class itself they are called as
internally defined member functions.
data members of a class, needs to take the help
ic ow
of internal methods of the class. Let us see some examples of object oriented
This ensures encapsulation of the data of a programs with internally defined functions. We
n
class. will see these examples for most of the concepts
bl kn
2.4 Creating a Class and Adding values of data members of the object during
Methods to a Class runtime or during the execution time.
Program 2.4.1 shows dynamic initialization of
Te
(SPPU - Dec. 17) Program 2.4.1 : Write a C++ program to find area of circle
using Object Oriented Programming such that the class
Q. How many ways we can define member function in
circle must have three member functions namely : (a) read()
class ? Give it's syntax. (4 Marks) to accept the radius from the user (b) compute() for
Q. What do you mean by dynamic initialization of calculating the area (c) display() for displaying the result.
object ? (Dec. 17, 4 Marks) # include<iostream.h>
To define the data members of a class the logic # include<conio.h>
is similar to that of the data members of a class circle
structure. But the new thing as discussed some {
time back is the member functions of a class. Let
float r,a;
us see how this can be done and what are the
different methods to do this. public:
There are three methods of defining member void read()
functions of a class. They are : {
1. Internally defined Functions cout<<"Enter radius:";
cin>>r;
2. Externally defined functions
}
3. Inline functions
void compute()
{
Let us see each of these in details.
ge
c.display(); Hence, the read() function accepts the input
getch(); io led from user as seen in the output and the display()
} function displays the result calculated by the
Output compute() function.
Enter radius:5 Program 2.4.2 : Write a C++ program to calculate the value
ic ow
public:
‘circle’ namely read(), compute() and display().
void read()
The read() function accepts the value of radius {
from the user. The compute() function calculates cout<<"Enter the value of n:";
the area of the circle. The display() function cin>>n;
displays the calculated area. }
void compute()
But all these functions will perform these tasks
{
only when they are called. These functions can
for(i=1, sum = 0;i<=n;i++)
be called by the period operator used with an
{
object of this class. sum=sum+i*i;
Hence, an object of this class is created in the }
main function. The syntax of making an object }
of a class is very simple. void display()
{
Syntax of declaring an object of a class:
cout<<"Value of the series="<<sum;
Class_name Object_name; }
For example, in the above case we have made };
an object of the class “circle” by the statement, void main()
{
circle c;
ge
Note : A variable cannot be initialized in the declaration
Program 2.4.4 : Write a C++ program to declare a class
of a class member variable. It has to be initialized
io led ‘student’ having data members as name and percentage.
in a function only. Hence, the variable “sum” is Write a constructor to initialize these data members accept
and display data for one student.
not initialized in the declaration statement;
#include<iostream.h>
ic ow
{
same as the previous one.
private:
at
Pu ch
Output s.read();
s.display();
Enter name and percentage:Ajay
getch();
85
}
Name:Ajay
Percentage:85 Output
ge
another member function of the same class is called as out of class. (2 Marks)
nesting of member function. The following C++ program Q. How user can declare member function outside the
example demonstrates this concept. class ? (2 Marks)
io led
# include<iostream.h>
When the member functions of a class are
# include<conio.h>
defined outside the class they are called as
class series externally defined member functions.
ic ow
{
The functions when defined outside must use
int n,i,sum;
n
scope resolution operator to define the scope of
public:
bl kn
{
}
-
int compute()
Statements;
{
for(i=1, sum = 0;i<=n;i++) -
{ }
sum=sum+i*i; Also in this case the prototype declaration has to
} be done inside the class for the externally
return sum; defined functions.
} Let us see these in details.
void display()
Program 2.4.6 : Write a C++ program to find area of circle
{
using Object Oriented Programming such that the class
compute();
circle must have three externally defined member functions
cout<<"Value of the series="<<sum;
namely : (a) read() to accept the radius from the user (b)
} compute() for calculating the area (c) display() for displaying
}; the result.
void main() # include<iostream.h>
{ # include<conio.h>
clrscr(); class circle
series s; {
ge
a=3.14*r*r;
} io led Program 2.4.7 : Write a C++ program to calculate the value
void circle::display() of the following series using external member function :
{
S = 12 + 22 + 32 + 42 …... + n2
cout<<"Area="<<a;
# include<iostream.h>
ic ow
}
void main() # include<conio.h>
n
{ class series
bl kn
clrscr(); {
circle c; int n,i,sum;
at
Pu ch
c.read(); public:
c.compute();
void read();
Te
c.display();
void compute();
getch();
} void display();
};
Output
void series::read()
Enter radius:5
{
Area=78.5
cout<<"Enter the value of n:";
Explanation
cin>>n;
A class is created with the name ‘circle’. Two }
float type variables are declared in it namely ‘r’ void series::compute()
and ‘a’ for the radius and area respectively.
{
The prototype of the three functions are
for(i=1, sum = 0;i<=n;i++)
declared inside the class “circle” namely read(),
{
compute() and display().
sum=sum+i*i;
The definition of these functions are written
}
outside the class. But, with the help of the scope
resolution operator the scope of the functions is }
declared in the class “circle”. void series::display()
{
ge
Output
defined outside. Also another advantage is a
Enter the value of n:5 member can be declared inline for two classes
io led and hence access members of two classes.
Value of the series=55
Let us see the same examples as seen inline
Explanation
defined functions.
ic ow
in a function only. Hence, the variable ‘sum’ is circle must have three inline functions namely : (a) read() to
not initialized in the declaration statement; accept the radius from the user (b) compute() for calculating
the area (c) display() for displaying the result.
at
# include<iostream.h>
function.
# include<conio.h>
The logic and way of writing the program is
Te
class circle
same as the previous one.
{
2.4.4 Inline Member Functions float r,a;
public:
Q. What are inline functions ? Write a program to
void read();
demonstrate inline function. (10 Marks)
void compute();
Q. Write short note on : Inline function. (5 Marks)
void display();
Q. Explain inline function with an example. (10 Marks)
};
Q. What do you mean by inline function? Write its inline void circle::read()
syntax and example. (4 Marks) {
We have seen that a function can be defined cout<<"Enter radius:";
inside a class or outside a class. cin>>r;
If a function is to be defined outside the class, }
but still be treated as a internally defined inline void circle::compute()
function then such a function has to be made {
“inline” function. a=3.14*r*r;
}
To make a function inline function the keyword
inline void circle::display()
‘inline’ before the header line of the function.
{
ge
Output
Enter radius:5
Enter the value of n:5
Area=78.5
Value of the series=55
io led
Program 2.4.9 : Write a C++ program to calculate the value
of the following series using inline member function : S = 12
2.4.5 Java Member Methods
+ 22 + 32 + 42 …... + n2 A class is a collection of fields and methods. We
ic ow
int n,i,sum;
below:
public:
class_name object_name = new
Te
void read();
class_name(parameters_to_be_passed_to_the_constructor)
void compute();
We will learn some more concepts of Object
void display();
Oriented Programming in later sections. We will
};
see some simple program examples for making
inline void series::read()
classes and its object.
{
cout<<"Enter the value of n:"; Program 2.4.10 : Write a C++ program to make a class
cin>>n; called as Circle. It should have three methods namely :
accept radius, calculate area and display the area.
}
import java.util.*;
inline void series::compute()
class Circle
{
{
for(i=1, sum = 0;i<=n;i++)
private float r,area;
{
public void accept(float x)
sum=sum+i*i;
{
}
r=x;
}
}
inline void series::display()
public void calculate()
{
{
{ import java.util.*;
float x; class Euclid
ge
Scanner sc = new Scanner (System.in); {
System.out.print("Enter Radius:"); private int n1,n2,gcd;
void accept(int x, int y)
x=sc.nextFloat();
io led
Circle c=new Circle(); {
c.accept(x); n1=x;
ic ow
c.calculate(); n2=y;
c.display(); }
n
} void calculate()
bl kn
} {
int temp;
at
Pu ch
Output
while(n1%n2!=0)
Enter Radius:10
{
Te
Area=314.0
n1=n1%n2;
Explanation temp=n1;
The class Circle is first made with the private n1=n2;
System.out.print("Enter two numbers:"); Then the calculate() method is called and finally
x=sc.nextInt(); the display() method.
y=sc.nextInt(); Program 2.4.12 : Using C++ create a class employee with
Euclid e=new Euclid(); data members empid, empname, designation and salary.
e.accept(x,y); Write methods get_employee()- to take user input,
show_grade() - to display grade of employee based on
e.calculate(); salary. show_employee() to display employee details. Let the
e.display(); employee be graded according to salary as follows :
}
Salary range Grade
}
<10000 D
Output
20
ge
25000-49999 B
GCD=5
>50000 A
Explanation
io led
import java.util.*;
The class Euclid is first made with the private
class Employee
data (field) members ‘n1’, ‘n2’ and “gcd”. The
{
ic ow
{
3. display() to display the gcd.
Scanner sc=new Scanner(System.in);
Since no access specifier is mentioned with the System.out.println("Enter employee name, designation, ID
Te
ge
e.show_grade(); import java.util.*;
e.show_employee(); class Student
} {
io led
} private int id,p,c,m,t;
Output private String name;
ic ow
void accept()
Enter employee name, designation, ID and salary
{
n
Ajay
Scanner sc= new Scanner(System.in);
bl kn
Professor
String str;
325
at
51000
M");
Grade A
name=sc.nextLine();
Te
Name:Ajay
str=sc.nextLine();
Designation:Professor
id=sc.nextInt();
ID:325 str=sc.nextLine();
Salary:51000.0 p=sc.nextInt();
Explanation : str=sc.nextLine();
c=sc.nextInt();
The class Employee is first made with the
str=sc.nextLine();
private data (field) members as given in the
m=sc.nextInt();
problem statement. The class has three method
t=p+c+m;
members namely
}
1. get_employee() to accept the information of void display()
employee. This method has to accept input {
from user and hence has the nextLine() System.out.println("Name:"+name+"\nID:"+id+"\nP:"+p
method. String data are directly accepted +"\nC:"+c+"\nM:"+m+"\nTotal:"+t);
while the others are accepted as string and }
then converted into required data types }
using the wrapper class methods. class Main
2. show_grade() to find and display the grade. {
public static void main(String args[]) Note : The memory space is allocated to an object and
{ not to a class. Hence, by writing the statement,
Student s= new Student(); circle c; we are actually allocating the memory
s.accept(); space required for the data members of the class
s.display(); ‘circle’. This statement allocates space as
} required for two float type elements i.e. for the
} variables ‘r’ and ‘a’.
Enter name, ID and marks in P, C & M memory. Hence, if we declare another object, the
ge
90 in following class :
90 class Book
io led
Name:Ajay {
ID:325 char B_name[15]; int B_id;
P:90 int Price;
ic ow
C:90 };
Book B1;
n
M:90
bl kn
Total:270 Output
B_name: 15 bytes
at
Pu ch
ge
operator, we require delete operator. In this case
Explanation
the delete operator must be in the destructor.
Hence, the destructor will be destroying the The destructor is the ~test() function. This
io led
memory allocated. The syntax for the delete destructor is automatically called after the
operator to destroy the memory space allocated end of the execution of the main() function.
ic ow
# include<conio.h> cout<<"Destroyed";
class test
is then executed.
Te
{
int *p; Hence, similar to constructor even the
public: destructor is not to be called explicitly. It is
test()
automatically called.
{
p=new int;
2.6 Returning a Value
}
void read() A method or a function can return a value.
{
The data type of the returned value is to be
cout<<"Enter a number";
mentioned in the beginning of the method
cin>>*p;
} definition i.e. after its access specifier.
void display() If a method doesn’t return anything, it can be
{ declares as a void function.
cout<<"Value="<<*p<<endl; The Java program given below shows the
}
calculate() method returning the answer
~test()
{ import java.util.*;
delete p; class Euclid
cout<<"Destroyed"; {
}
private int n1,n2;
{ import java.util.*;
n1=n1%n2; class Euclid
temp=n1; {
ge
private int n1,n2,gcd;
n1=n2;
void accept(int x, int y)
n2=temp;
io led
{
}
n1=x;
return n2;
n2=y;
ic ow
}
}
}
n
void calculate()
bl kn
class Main {
{ int temp;
at
Pu ch
} }
class Main
Output
{
Enter two numbers:15 public static void main(String args[])
20 {
int x,y;
GCD=5
Scanner sc= new Scanner(System.in);
ge
GCD=5 {
cout<<"The value is:"<<a;
}
2.8 The "this" Keyword
io led
};
2.8.1 “this” Keyword in C++
void main()
ic ow
(2 Marks)
Compare c2;
Q. Describe the concept of' this' pointer. Give one c1.read();
at
Pu ch
(4 Marks) c3=c1.compare(c2);
"this" is a keyword used to indicate the current c3.display();
object. It is used to access the members of the getch();
current object. }
ge
method(), and you want to refer to the same
Compare c3;
object through which the method is called, then
c3=c1.compare(c2);
you need to use the “this” keyword.
io led
c3.display();
We have been using the parameters of the
}
current object in the instance methods of the
}
ic ow
Enter a no:
same is shown in Program 6.9.1 below.
4
at
ge
Since, for overloaded functions the functions y=add(p,q);
have same name, a function can be called with cout<<"Sum="<<y<<endl;
the common name but the function that will be
io led y=add(p,a);
invoked is based on the parameter type and cout<<"Sum="<<y<<endl;
number of parameters. getch();
ic ow
Sum=11
overloading.
Sum=10.1
at
Sum=8.5
Pu ch
third function adds a float number with an integer. The first call to function add() in the main()
OR Explain need of function overloading. Write C++ program function, has both the integer elements ‘a’ and
to demonstrate function overloading. ‘b’; hence the second add() function is called
(SPPU - Dec. 18, 6 Marks, May 19, 6 Marks. which has both the integer parameters.
ge
} Output
float area(float l, float b)
1.Area of Circle
io led
{
2.Area of Rectangle
return (l*b);
} 3.Area of Triangle
ic ow
2
s=(a+b+c)/2;
The area of the rectangle=7
ar=s*(s-a)*(s-b)*(s-c);
at
Pu ch
ar=pow(ar,0.5); Explanation
return ar; The user is asked for the choice of the shape
Te
Program 2.9.3 : Write a C++ program using function After swapping, a=4 and b=3
overloading to swap 2 integer numbers and swap 2 float
Enter two float numbers:3.5 2.75
numbers.
Numbers entered are: c=3.5 and d=2.75
#include<iostream.h>
#include<conio.h> After swapping, c=2.75 and d=3.5
#include<stdio.h>
Program 2.9.4 : Write a C++ program to calculate area of
void swap(int *a, int *b)
circle and area of rectangle using function overloading.
{
#include<iostream.h>
int temp;
temp=*a; #include<conio.h>
*a=*b; #include<stdio.h>
*b=temp; float area(float r)
} {
void swap(float *a, float *b)
ge
return (3.14*r*r);
{
}
float temp;
io led float area(float l,float b)
temp=*a;
*a=*b; {
*b=temp; return(l*b);
ic ow
} }
void main()
n
void main()
bl kn
{ {
int a,b;
clrscr();
at
float c,d;
Pu ch
ge
area=3.14*r*r; break;
} case 3:cout<<"Enter the length of the three sides of
io led
Area(float l, float b) the triangle:";
{ cin>>x>>y>>z;
ic ow
{ default:cout<<"Invalid Choice";
at
float s; }
Pu ch
s=(a+b+c)/2; getch();
area=s*(s-a)*(s-b)*(s-c); }
Te
area=pow(area,0.5); Output
}
1.Area of Circle
void display()
2.Area of Rectangle
{
3.Area of Triangle
cout<<"Area="<<area;
Enter your choice:1
}
Enter the radius of the circle:5
};
Area=78.5
void main()
{ Explanation
ge
number is passed as well as returned by the }
function. The function adds two complex
Output
numbers and returns the result
io led
Enter the real and imaginary parts of a complex number:2
Program 2.10.1 : Write a C++ program to add two complex
numbers using objects of a class Complex.
3
Enter the real and imaginary parts of a complex number:4
ic ow
#include<iostream.h>
#include<conio.h> 5
n
class Complex 6+i8
bl kn
{
2.10.2 Passing Objects to a Method
int x,y;
at
public:
an object of the same class to the constructor.
void read()
Objects can be passed to methods also. The
Te
{
cout<<"Enter the real and imaginary parts of a objects are handled in the same manner by a
complex number:"; method as that was done by constructors in the
cin>>x>>y; above program examples. We will see the
} following program example, wherein we pass an
Complex add (Complex c) object to a method.
{
When an object is passed to a method in Java,
Complex c1;
the values contained in that object can be
c1.x=x+c.x;
changed. These values will remain changed even
c1.y=y+c.y;
when the method execution ends and the control
return c1;
returns to the caller method. This will be seen in
} more details in the further sections.
void display() In this program given below, we are adding a
{ complex number with another. The add()
if(y<0) method will be called by one of the object and
cout<<x<<y<<"i"; another object will be passed to this method.
else The method will add the values of the
cout<<x<<"+i"<<y;
corresponding object and then the result will be
}
displayed.
ge
x =x+a.x;
1. add() to add the two complex numbers.
y =y+a.y;
2. display() to display the complex number.
}
io led
void display() The add() method accepts an object of the class
{ Complex. The method adds the real and
if(y>=0) imaginary parts of the object for which the
ic ow
System.out.println(x + " " + y +"i"); In the main() method, we have accepted the real
} and imaginary parts of two complex numbers
at
Pu ch
public static void main(String args[]) and the object c2 is passed to this method. The
{ method as discussed earlier adds the
int a,b; corresponding parts of the two complex
Scanner sc=new Scanner(System.in); members. Finally the display() method is called
System.out.println("Enter real and imaginary part of a again by the object c1 as the result is in the
complex number:");
object c1.
a =sc.nextInt();
The display() method has a special technique to
b =sc.nextInt();
be followed. If the imaginary part is greater
Complex c1=new Complex(a,b);
than or equal to zero then “+i” must be
System.out.println("Enter real and imaginary part of
another complex number:"); displayed between the two values i.e. x and y.
a=sc.nextInt(); But if the imaginary part is less than zero, then
b=sc.nextInt(); the x value followed by the value of y with its
Complex c2=new Complex(a,b); sign and finally “i” as it is. The special care has
c1.add(c2); to be taken to differentiate between the “+” sign
c1.display(); as addition and the “+” sign as string
} concatenation (joining). You will notice that is
} done in the statement in the display() method.
ge
adding two complex numbers will be considered,
Complex c2=new Complex(a,b);
but the result will be returned to another object
Complex c3 = new Complex();
of the same class.
io led c3=c1.add(c2);
Program 2.10.3 : Write a Java program that demonstrates c3.display();
returning objects to a method. }
ic ow
import java.util.*; }
class Complex
n
Output
{
bl kn
private int x,y; Enter real and imaginary part of a complex number:
Complex(int a,int b) 1
at
{ 2
Pu ch
} 4
Complex() 4+i6
{
Explanation
}
Complex add (Complex a) The class Complex has a constructor to initialize
{ the values of the object made of this class. There
Complex c=new Complex(); is a constructor added in this program that
c.x=x+a.x; doesn’t initialize the values of its variable ‘x’ and
c.y=y+a.y; ‘y’. This constructor is especially for the object c3
return c; and the object c.
} The class has two method members namely
void display()
1. add() to add the two complex numbers.
{
if(y>=0) 2. display() to display the complex number.
System.out.println(x+"+i"+y); The add() method accepts an object of the class
else Complex. The method adds the real and
System.out.println(x + " " + y +"i"); imaginary parts of the object for which the
} method is called with the corresponding values
} of the object ‘a’ passed to it.
class Main
The answer is stored in another object created in Program 2.10.4 : Write a Java program that demonstrates
call by value to swap two numbers.
the method itself. Hence this object is returned
by the add() method and accepted by the main() import java.util.*;
method into the object c3. class Main
{
In the main() method, we have accepted the real
int a,b;
and imaginary parts of two complex numbers
public static void main(String args[])
from user and accordingly two objects are made
{
namely c1 and c2.
Scanner sc=new Scanner(System.in);
Then the add() method is called by the object c1 Main m=new Main();
and the object c2 is passed to this method. The System.out.println("Enter two numbers:");
method as discussed earlier adds the m.a=sc.nextInt();
corresponding parts of the two complex m.b=sc.nextInt();
members. Finally the display() method is called
ge
System.out.println("Numbers are
again by the object c3 as the result is in the a="+m.a+"\tb="+m.b);
object c3. swap(m.a,m.b);
io led
The display() method has a special technique to System.out.println("After returning from method\nNumbers
be followed. If the imaginary part is greater are a="+m.a+"\tb="+m.b);
than or equal to zero then “+i” must be }
ic ow
displayed between the two values i.e. x and y. static void swap(int a, int b)
But if the imaginary part is less than zero, then {
n
int temp;
bl kn
ge
In case of Java, call by reference is possible by Numbers are a=4 b=7
passing the object to the method. If we pass the After swapping in method
io led
object to a method, we can access the actual Numbers are a=7 b=4
parameters of that object according to the access After returning from method
specifiers. Numbers are a=7 b=4
ic ow
swap().
We will see how the parameters of the object can
The object is received in formal parameter
at
Program 2.10.5 : Write a Java program that demonstrates changed in this case.
call by reference to swap two numbers.
This is demonstrated in the output of the
import java.util.*;
program. The numbers accepted were 4 and 7
class Main
respectively for ‘a’ and ‘b’. In the method the
{
numbers are swapped i.e. ‘a’ has 7 and ‘b’ has 4.
int a,b;
And when the control returns back to the main()
public static void main(String args[])
{ method the values are also found to be swapped
Scanner sc=new Scanner(System.in); i.e. changed.
Main m=new Main();
System.out.println("Enter two numbers:");
2.11 Array of Objects in C++
m.a=sc.nextInt();
When multiple objects of a class are to be made
m.b=sc.nextInt();
we can use array of objects.
System.out.println("Numbers are
a="+m.a+"\tb="+m.b); Creating array of objects is quite similar to
swap(m); creating array of any other data type.
System.out.println("After returning from method\nNumbers Syntax of creating array of objects
are a="+m.a+"\tb="+m.b);
} class_name object_array_name[size];
static void swap(Main x)
ge
{ Finance
Enter name and department:Digvijay
private:
Finance
io led
char name[20],dept[20]; Enter name and department:Manoj
public: Sales
Enter name and department:Manish
ic ow
void accept()
Sales
{ Enter name and department:Suresh
n
cout<<"Enter name and department:"; Finance
bl kn
}
Enter name and department:Saurav
void display() HR
Te
{ Name Department
a finance
cout<<name<<"\t"<<dept<<"\n";
Ajay HR
} Vijay HR
}; Jay Finance
void main() Digvijay Finance
Manoj Sales
{
Manish Sales
int i; Suresh Finance
clrscr(); Dinesh HR
Saurav HR
Staff s[10];
for(i=0;i<=9;i++) Program 2.11.2 : Write a C++ program to declare a class
staff having data members as name and post. Accept and
{ display data for five staff members. (Using array of object)
s[i].accept(); #include<iostream.h>
} #include<conio.h>
cout<<"Name\tDepartment\n"; #include<stdio.h>
class Staff
for(i=0;i<=9;i++)
{
{
ge
{ cin>>acc_no>>balance;
int i; }
clrscr();
io led
void display()
Staff s[5]; {
for(i=0;i<=4;i++) cout<<acc_no<<"\t"<<balance<<endl;
ic ow
{ }
s[i].accept(); };
n
} void main()
bl kn
cout<<"Name\tPsot\n"; {
for(i=0;i<=4;i++) Account b[5];
at
{
Pu ch
int i;
s[i].display(); clrscr();
} for(i=0;i<=4;i++)
Te
getch(); {
} b[i].get_data();
Output }
cout<<"Acc No\t\Balance\n";
Enter name and post:Jay
for(i=0;i<=4;i++)
Manager
{
Enter name and post:Ajay
b[i].display();
Officer
}
Enter name and post:Vijay
getch();
Officer
}
Enter name and post:Suresh
Clerk Output
Enter name and post:Dinesh Enter account number and balance:2
Clerk
3
Name Psot
Enter account number and balance:1
Jay Manager
2
Ajay Officer
Vijay Officer Enter account number and balance:123
Suresh Clerk 5000
Dinesh Clerk Enter account number and balance:456
10000 Output
Enter account number and balance:789 Enter model name and price:s1
1000 2000
Acc No Balance Enter model name and price:s2
2 3 3000
1 2 Enter model name and price:s3
123 5000 4000
456 10000 Enter model name and price:s4
789 1000 5000
Program 2.11.4 : Write a C++ program to declare a class Enter model name and price:s5
mobile having data members as price and model number. 6000
Accept and display this data for ten objects. Enter model name and price:s6
#include<iostream.h> 7000
ge
#include<conio.h> Enter model name and price:s7
#include<stdio.h>
8000
class Mobile
io led Enter model name and price:s8
{
private: 9000
char model[20]; Enter model name and price:s9
ic ow
{ Model Price
cout<<"Enter model name and price:"; s1 2000
at
Pu ch
cin>>model>>price;
s2 3000
}
s3 4000
void display()
Te
{ s4 5000
cout<<model<<"\t"<<price<<"\n"; s5 6000
} s6 7000
}; s7 8000
void main() s8 9000
{ s9 10000
int i; s10 11000
clrscr();
Mobile s[10];
2.11.2 Array of Objects in Java
for(i=0;i<=9;i++)
{ To create an array of objects of a class, the
s[i].accept(); following syntax is to be used :
}
cout<<"Model\tPrice\n"; class_name object_name[] = new
for(i=0;i<=9;i++) class_name[size_of_array].
{ You will notice this is exactly similar to creating
s[i].display();
an array of any in-built data type i.e. “int”,
}
getch(); “float” etc.
}
Note : Memory is not allocated to each object with the s[i]=new Student();
above declaration. We need to use the “new” s[i].accept();
operator separately for each object of the array }
for allocating memory to it. We will see how this System.out.println("Name\tID\tPhy\tChem\tMaths\tTotal");
is to be done in the Program 2.11.5. for(i=0;i<=n-1;i++)
Program 2.11.5 : Write a Java program to create an array of {
objects of a class student. The class should have field s[i].display();
members name, id, total marks and marks in three subjects }
namely Physics, Chemistry and Maths. Accept information of
}
‘n’ students and display them in tabular form.
}
import java.util.*;
class Student{ Output
private String name; Enter number of students:
private int id,p,c,m,t; 3
ge
void accept() Enter name, ID and marks in Physics, Chemistry and Maths:
{ Ajay
io led
String str; 325
Scanner sc = new Scanner (System.in); 90
System.out.println("Enter name, ID and marks in Physics, 90
ic ow
425
p=sc.nextInt();
90
c=sc.nextInt();
at
Pu ch
99
m=sc.nextInt();
99
t=p+c+m;
Enter name, ID and marks in Physics, Chemistry and Maths:
Te
} Jay
void display() 525
{ 99
99
System.out.println(name+"\t"+id+"\t"+p+"\t"+c+"\t"+m 99
+"\t"+t); Name ID Phy Chem Maths Total
} Ajay 325 90 90 90 270
} Vijay 425 90 99 99 288
class Main Jay 525 99 99 99 297
{
Explanation
public static void main(String args[])
{ You will notice that the declaration statement
int n,i; shown above is used to declare an array of
Scanner sc=new Scanner(System.in); objects of the class Student.
System.out.println("Enter number of students:"); The class Student has the field members as
n=sc.nextInt(); given in the problem statement. The class also
Student s[]= new Student[n]; has methods to accept and display the
for(i=0;i<=n-1;i++) information of a student.
{
ge
}
calling the accept() method for each object in the
System.out.println("Name\tID\tdesig.\t\tsalary");
for loop and then displayed in tabular form
io led for(i=0;i<=n-1;i++)
using another for loop.
{
Program 2.11.6 : Create a class employee with data s[i].show_employee();
ic ow
class Employee
3
{
Enter name, ID , designation and salary:
Te
ge
2. show_employee() to display all the else
information about the employee. return false;
Then another class is made, that has the main() }
io led
which is the beginning of the execution of the void display()
program. Hence the name of the program is as {
ic ow
}
created of the class Employee named as ‘s’. And
}
the memory is allocated for each object in the
at
class Main
Pu ch
ge
Enter number of students: to each object using the new operator. This is
3 done by the statement
io led
Enter name, ID and marks in Physics, Chemistry and Maths: s[i]=new Student()
Ajay This statement is required to each object, hence
325 it is put in the for loop. If this statement is not
ic ow
Vijay
Pu ch
ge
return false;
} 3
void show_employee() Enter name, ID , designation and salary:
io led
{ Ajay
325
System.out.println(empname+"\t"+empid+"\t"+designatio Accountant
ic ow
n+"\t"+salary); 50000
} Enter name, ID , designation and salary:
n
bl kn
} Jay
class Main 525
at
{ Operator
Pu ch
String data are directly accepted while the Static members are common for the entire class
others are accepted as string and then and not for each object of the class.
converted into required data types using
We can have static data members as well as
the wrapper class methods.
static function members.
2. show_employee() to display all the
We will see the static data member in this class
information about the employee.
and static function members will be dealt with
3. compare() method to compare the salary of
in chapter 7.
the object through which the method is
called and the salary of the consecutive Static data member will have same value for all
next object which is passed to the method the objects. Hence if one object alters the value
as a parameter. This method returns a of static data member, its altered value will be
Boolean value as true or false based on available for all other objects
whether swapping will be required or not Let us see a program example of static data
for arranging the two objects in descending
ge
member.
order of their salary.
Then another class is made, that has the main() Program 2.13.1 : Write a C++ program to define a class
io led having data members principle, duration and rate-of-interest.
which is the beginning of the execution of the
Declare rate-of-interest as static member variable. Calculate
program. Hence the name of the program is as the simple interest and display it for one object.
the name of this class. Also the main() method is
ic ow
#include<iostream.h>
declared public and static.
#include<conio.h>
In the main() method the array of objects is
n
#include<stdio.h>
created of the class Employee named as ‘s’. And
bl kn
ge
class Counter
2.13.1 Static Class Members in Java
{
io led
We can declare a method or a field to be static. private static int count;
We may also have a block called as static. What Counter()
is the effect of the keyword “static” on these {
ic ow
ge
and hence the output shows Count=1.
The next two times we have done the same }
thing but after making two objects each time class Exam
io led
and hence the outputs are Count=3 and {
Count=5 respectively.
int p,c,m;
ic ow
it is used. This is called as forward declaration. We can have abstract classes. These classes
For example:
cannot be instantiated i.e. no objects of abstract
Te
class Student
class can be created.
{
int roll; We will see Abstract class in further chapters.
Exam e; The abstract data type are used create a
}
template for data.
class Exam
{
int p,c,m;
}
ge
Q. 1 (a) Compare Object Oriented Programming with Procedure oriented programming.
(c) Write a Java program to accept two numbers and display its product.
n
(Refer Program 1.13.2) (5 Marks)
bl kn
OR
at
Q. 2 (a) Explain the limitations of procedure oriented programming and structure of object oriented programming.
Pu ch
(b) Explain Java Virtual Machine with block diagram. (Refer Section 1.7) (5 Marks)
(c) Write a program to check if the entered number is prime number or not.
Q. 3 (a) Explain the methods of adding functions to a class in C++. (Refer Section 2.4.1) (5 Marks)
OR
(b) What is method overloading? Write a C++ program to add two numbers using function overloading such that
one function adds two integers, second function adds two float numbers and the third function adds a float
number with an integer. (Refer Section 2.9.1 and Program 2.9.1) (5 Marks)
(c) Write a C++ program to declare class Account having data member as acc_no and balance. Accept and display
data for five object using pointer to array of object. (Refer Program 2.11.3) (5 Marks)
Syllabus
Overloading, Constructor with Default Arguments, Symbolic Constants, Garbage Collection: Destructors and Finalizers.
ge
io led 6. A constructor cannot be inherited but a
3.1 Introduction of Constructors : Use
and Characteristics derived class can call the constructor of the
base class.
ic ow
3.1.1 Constructor
7. A constructor cannot be static or virtual.
(SPPU - May 17)
n
Note : Some of the terms used above may not be
bl kn
They are special member functions used for There are three types of constructors based on
initializing the data elements of the object. the parameter list. The types of constructors
Te
ge
}
modifying them.
inline void circle::display()
Some methods are called as Iterators methods
io led {
that provide orderly access to the components of
cout<<"Area="<<a;
an object. The iterator methods are most
}
common with objects maintaining collections of
ic ow
void main()
other objects like vector class object.
{
n
3.2 Types of Constructor clrscr();
bl kn
circle c;
3.2.1 Default Constructor
at
c.compute();
Pu ch
ge
void display();
Let us see the same examples of programs again
};
with parameterized constructor.
inline void series::compute()
io led
{ Program 3.2.3 : Write a program to find area of circle using
Object Oriented Programming. The value of the radius must
for(i=1;i<=n;i++)
be accepted from the user in the main program and passed
ic ow
} # include<iostream.h>
inline void series::display() # include<conio.h>
at
class circle
Pu ch
{
{
cout<<"Value of the series="<<sum;
float r,a;
Te
}
public:
void main()
circle(float x)
{
{
clrscr(); r=x;
series s; }
s.compute(); void compute();
s.display(); void display();
getch(); };
} inline void circle::compute()
{
Output
a=3.14*r*r;
Enter the value of n:5 }
Value of the series=55 inline void circle::display()
{
Explanation
cout<<"Area="<<a;
Here, the variables i.e. ‘n’ and ‘sum’ are }
initialized in the constructor. The value of sum void main()
is initialized to zero while the value of ‘n’ is {
taken from the user. The remaining logic is clrscr();
similar.
ge
void main()
Here, the constructor has an argument to be
{
accepted i.e. a float variable ‘x’. This variable is
io led clrscr();
to be passed to the constructor when the object
int x;
is made.
cout<<"Enter the value of n:";
To pass the variable to the constructor, it has to
ic ow
cin>>x;
be mentioned in the brackets along with the
series s(x);
object name while making the object. You will
n
s.compute();
bl kn
}
circle c(p);
Output
Te
ge
with copy constructor. }
Program 3.2.5 : Write a program to find area of circle using Output
io led
Object Oriented Programming. The value of the radius must
be accepted from the user in the main program and passed Enter the radius of the circle5
to the copy constructor and the class circle must have two Area=78.5
inline functions namely : (a) compute() for calculating the
Area=78.5
ic ow
circle(float x)
{ is made.
r=x; The second constructor has an argument of type
} ‘circle’. This type is the object of the same class
circle(circle &c) i.e. ‘circle’. This is the copy constructor. We have
{ passed the earlier created object ‘c’ to the
r=c.r; constructor of the second object ‘c1’ to initialize
} its variable ‘r’.
void compute();
Both the objects are created in the main()
void display();
function with the respective constructors being
};
inline void circle::compute() called as discussed in the previous point. The
{ other functions are called individually for each
a=3.14*r*r; object.Remember memory space allocated for
} each object are different.
inline void circle::display()
Program 3.2.6 : Write a program to calculate the value of
{
cout<<"Area="<<a<<endl; the following series using copy constructor and inline
2 2 2 2 2
} member function : S = 1 + 2 + 3 + 4 …... + n
ge
{
creating the second object as in the previous
n=x.n;
program.
sum=0;
io led
Program 3.2.7 : Consider the definition of the following
}
class :
void compute();
ic ow
class Sample
void display();
{
n
};
bl kn
{ int x;
at
Pu ch
for(i=1;i<=n;i++) double y;
{ public :
Te
sum=sum+i*i;
Sample(); //constructor 1
}
Sample (int, double); //constructor 2
}
Sample(Sample &P); Constructor 3
inline void series::display()
{ };
(i) Write the definition of the constructor 1 so that the
cout<<"Value of the series="<<sum<<endl; private member variables are initialized to 0.
} (ii) Write the definition of the constructor 2 so that the
private member variable x and y is initialized according
void main()
to the value of the parameter.
{ (iii) Write the definition of the constructors 3, where copy
clrscr(); one object to another. (SPPU - Dec. 19, 6 Marks)
cin>>x; private
s.compute(); double y;
s.display(); public :
ge
y=P.y; private float r,area;
} Circle(float x)
{
};
io led
r=x;
3.2.4 Constructors }
void calculate()
ic ow
}
constructor, as listed below:
void display()
1. Constructor should always be in the
at
Pu ch
{
public/default/protected visibility of a class.
System.out.println("Area="+area);
2. The name of the constructor should always
}
Te
Explanation n1=n2;
The class Circle is first made with the private n2=temp;
data (field) members ‘r’ and “area”. The class }
has three method members namely gcd=n2;
}
1. Circle() i.e. parameterized constructor to
void display()
accept the radius. This constructor is
{
passed with the value of radius (hence
System.out.println("GCD="+gcd);
parameterized constructor), which is
}
initialized in the variable r.
}
2. calculate() to calculate the area. class Main
3. display() to display the area. {
Then another class is made, that has the main() public static void main(String args[])
ge
method which is the beginning of the execution {
of the program. Hence the name of the program
io led int x,y;
is as the name of this class. Also the main() Scanner sc= new Scanner(System.in);
method is declared public and static. System.out.print("Enter two numbers:");
In the main() method, we have accepted the x=sc.nextInt();
ic ow
e.display();
making the object.
}
at
}
the display() method.
Output
Te
ge
class Circle program. Hence the name of the program is as
{ the name of this class. Also the main() method is
private float r,area;
io led declared public and static.
Circle() In the main() method, we have created an object
{ of the class Circle named as ‘c’.
ic ow
ge
parameter passed is an object is called as copy
System.out.println("GCD="+gcd);
constructor.
}
io led The parameters of the object passed to the
}
constructor are used to initialize the parameters
class Main of the newly created object, hence the name
ic ow
{ “copy”.
public static void main(String args[]) Let us see some programs using this copy
n
constructor.
bl kn
{
Euclid e=new Euclid(); Program 3.2.12 : Write a program to make a class called as
at
Pu ch
} import java.util.*;
} class Circle
{
Output
private float r,area;
Enter two numbers:20
Circle()
12
{
GCD=4
Scanner sc= new Scanner(System.in);
Explanation System.out.print("Enter Radius:");
The class Euclid is first made with the private r=sc.nextFloat();
data (field) members ‘n1’, ‘n2’ and “gcd”. The }
class has three method members namely Circle(Circle x)
1. Euclid() i.e. the default constructor to {
accept the two numbers. r=x.r;
This constructor accepts two inputs from }
user and initializes the variables n1 and n2. void calculate()
2. calculate() to calculate the GCD. {
3. display() to display the GCD. area=3.14f*r*r;
}
ge
Circle c1=new Circle(c); method to calculate the GCD and display() method to display
c1.calculate(); the same.
import java.util.*;
c1.display();
io led
} class Euclid
} {
ic ow
Explanation n1=sc.nextInt();
n2=sc.nextInt();
The class Circle is first made with the private
Te
}
data (field) members ‘r’ and “area”. The class
Euclid(Euclid x)
has three method members namely.
{
1. Circle() i.e. default constructor to accept the n1=x.n1;
radius. This constructor accepts the value n2=x.n2;
of radius, which is initialized in the }
variable r. Another constructor is written void calculate()
with a parameter as an object of the same {
class. The radius of this object is initialized int temp;
in the object of new constructor. while(n1%n2!=0)
2. calculate() to calculate the area. {
3. display() to display the area. n1=n1%n2;
Then another class is made, that has the main() temp=n1;
which is the beginning of the execution of the n1=n2;
program. Hence the name of the program is as n2=temp;
the name of this class. Also the main() method is }
declared public and static. gcd=n2;
}
In the main() method, we have created an object
void display()
of the class Circle named as ‘c’.
ge
e1.display();
} Q. Explain overloaded constructor in a class with
io led
} suitable example. (8 Marks)
Explanation
Pu ch
The class Euclid is first made with the private Although we have seen examples of constructor
data (field) members ‘n1’, ‘n2’ and “gcd”. The overloading in previous section, let us see one more
Te
ge
{ Then the display function is called with respect
clrscr(); io led to the object.
int choice;
float x,y,z; 3.4 Constructor with Default Arguments
cout<<"1.Area of Circle\n2.Area of Rectangle\n3.Area
ic ow
ge
} sphere. Make use of symbolic constant to display the
}; volume.
import java.util.*;
float Interest::rate=10;
io led
void main() class Sphere{
protected float r,vol;
{
final float pi=3.14f;
ic ow
float x,y;
public void read(float x)
clrscr();
n
{
cout<<"Enter principal amount:";
bl kn
r=x;
cin>>x;
}
at
Interest i(x);
Pu ch
getch(); }
} public void display()
{
Output
System.out.println("Volume="+vol);
Enter principal amount:2000 }
Simple Interest=2000 }
class Main{
Explanation
public static void main (String args[]) {
In this case, the values of principal and float x;
duration, if passed then the same will be Scanner sc = new Scanner (System.in);
initialised. If no values are passed then the System.out.println("Enter the radius:");
values 1000 and 10 are initialised. x=sc.nextFloat();
Sphere s=new Sphere();
3.5 Symbolic Constants
s.read(x);
The keyword final can be preceded to any s.calculate();
member of a class or to the class itself. System.out.println("Sphere:");
Making anything final has following s.display();
implications. }
}
ge
delete Pointer_name;
3.6.1 Destructor
Program 3.6.1 : Write a program to demonstrate the
(SPPU - May 17)
io led destructor.
Q Explain the concept of destructor in C++. (5 Marks) # include<iostream.h>
Q. State the characteristics of destructor. (2 Marks) # include<conio.h>
ic ow
class test
Q. What is destructor? Give its syntax and example.
{
n
(4 Marks)
int *p;
bl kn
ge
destructor is automatically called after the end class Main
of the execution of the main() function. Hence, in {
our case after the statement getch(); the public static void main(String args[])
io led
destructor is automatically called. {
Demo d=new Demo();
When the destructor is called, the memory
d.display(10);
ic ow
cout<<"Destroyed"; }
}
is then executed.
at
Pu ch
Explanation
3.6.2 finalize() Method
An object “d”, is made of the class Demo. The
The C++ programming language had the object is used to call the display() method.
destructors. But in Java we do not have Then the object is given “null” or made null.
destructors. This is to indicate the JVM that the use of this
“Java is garbage collected”, i.e. the objects are object is over.
automatically destroyed when their use is over. The static method gc() of the class System is
Hence there is no need of having destructors. called. This method is called as garbage
But, there may be certain operations to be collection method.
carried out when an object is destroyed. Although garbage collection happens at regular
For example, if the object was using a particular interval in a program, but since our program is
resource of the system, the resource is to be very small and for demonstration purpose, we
surrendered. This can be done using the need to call this method.
finalize() method. You will notice that the statement “In finalize
method of class Demo”, is automatically printed,
Let us see a program example of this method. without exclusively calling the finalize() method.
Thus when the garbage collection happens, the
finalize() method is automatically called.
ge
{ System.out.println("Enter your choice:");
System.out.println("Your total amount to be paid for input=sc.nextInt();
engineering books="+epay);
io led switch(input)
} {
public void ccheck() case 1:ecount++;
ic ow
}
System.out.println("Stock left=5");
public void payment(Engineering x)
System.out.println("Enter the quantity:");
at
Pu ch
{
n=sc.nextInt();
totalpay=x.epay+cpay;
if(n>5) System.out.println("Sorry,not much left in stock");
System.out.println("Your grand total="+totalpay);
Te
else if(n<=5)
System.out.println("Enter the amount:");
{
amt=sc.nextFloat();
epay1=3000*n;
if(amt<totalpay)
estock1=5-n;
System.out.println("Transaction failed...Please enter again");
}
else if(amt==totalpay)
}
System.out.println("Transaction successful,Delivery would
else if(ecount>1)
be done in 5-10 Business days....Balance to be
returned="+(amt-totalpay)); {
else if(estock1<=0)
System.out.println("Sorry,out of stock");
{
else
System.out.println("Transaction successful,delivery would
be done in 5-10 business days....Balance to be {
returned="+(amt-totalpay)); System.out.println("Stock left="+estock1);
} System.out.println("Enter the quantity:");
} n=sc.nextInt();
class Engineering extends Shopping if(n>estock1)
{ System.out.println("Sorry,not much left in stock");
epay1=3000*n; n=sc.nextInt();
estock1=estock1-n; if(n>5)
} System.out.println("Sorry,not much left in stock");
} else if(n<=5)
} {
break; epay3=2500*n;
case 2:ecount1++; estock3=5-n;
System.out.println("Book-Engineering Mathematics-1"); }
if(ecount1==1) }
{ else if(ecount2>1)
System.out.println("Stock left=5"); {
System.out.println("Enter the quantity:"); if(estock3==0)
n=sc.nextInt(); System.out.println("Sorry,out of stock");
ge
if(n>5) System.out.println("Sorry,not much left in stock"); else
else if(n<=5) {
System.out.println("Stock left="+estock3);
{
io led
epay2=1500*n; System.out.println("Enter the quantity:");
estock2=5-n; n=sc.nextInt();
if(n>estock3)
ic ow
}
System.out.println("Sorry,not much left in stock");
}
n
else if(n<=estock3)
else if(ecount1>1)
bl kn
{
{
epay3=2500*n;
if(estock2==0)
at
estock3=estock3-n;
Pu ch
System.out.println("Sorry,out of stock");
else }
{ }
Te
System.out.println("Stock left="+estock2); }
System.out.println("Enter the quantity:"); break;
n=sc.nextInt(); case 4:epay=epay1+epay2+epay3;
if(n>estock2) epay1=0;
System.out.println("Sorry,not much left in stock"); epay2=0;
else if(n<=estock2) epay3=0;
{ System.out.println("Payment has been processed
epay2=1500*n; successfully(Press appropriate key to check and make
payment)");
estock2=estock2-n;
break;
}
case 5:System.out.println("Thank you for shopping");
}
break;
}
default:System.out.println("Invalid input");
break;
break;
case 3:ecount2++;
}
System.out.println("Book-Engineering Graphics");
}while(input!=5);
if(ecount2==1)
}
{
}
System.out.println("Stock left=5");
class Commerce extends Shopping
System.out.println("Enter the quantity:");
{ {
private float cpay1,cpay2,cpay3; cpay1=140*n;
private int cstock1 ,cstock2, cstock3, ccount = 0,ccount1 cstock1=cstock1-n;
= 0,ccount2 = 0; }
Scanner sc=new Scanner(System.in); }
public void buycomm() }
{ break;
do case 2:ccount1++;
{ System.out.println("Book-Marketing & Human Resource
development");
System.out.println("Subject\tPublications\tCost");
if(ccount1==1)
System.out.println("1.Business & service sector\tmanan
public\t140 INR\n2.Marketing & Human Resource {
development\tSheth Publics\t120 INR\n3.Advertising\tVipul System.out.println("Stock left=5");
publics\t110 INR\n4.Process payment\n5.exit"); System.out.println("Enter the quantity:");
ge
System.out.println("Enter your choice:"); n=sc.nextInt();
input=sc.nextInt(); if(n>5)
io led
switch(input) System.out.println("Sorry,not much left in stock");
{ else if(n<=5)
case 1:ccount++; {
ic ow
}
System.out.println("Stock left=5");
else if(ccount1>1)
at
{
n=sc.nextInt();
if(cstock2==0)
if(n>5)
System.out.println("Sorry,out of stock");
Te
ge
System.out.println("Sorry,out of stock"); Commerce c=new Commerce();
else System.out.println("Welcome to our shop");
{ do
io led
System.out.println("Stock left="+cstock3); {
System.out.println("Enter the quantity:"); System.out.println("1.Engineering books\n2.Commerce
n=sc.nextInt(); books\n3.check payment history\n4.Make
ic ow
if(n>cstock3) payment\n5.exit");
System.out.println("Sorry,not much left in stock"); System.out.println("Enter your choice:");
n
else if(n<=cstock3) choice=sc.nextInt();
bl kn
{ switch(choice)
cpay3=110*n; {
at
Pu ch
} break;
break; case 3:e.echeck();
case 4:cpay=cpay1+cpay2+cpay3; c.ccheck();
cpay1=0; break;
cpay2=0; case 4:c.payment(e);
cpay3=0; break;
Engineering x=new Engineering(); case 5:System.out.println("Your happiness is our
epay=x.epay; happiness....#AtmaNirbharBharat");
System.out.println("Payment has been processed break;
successfully(Press appripriate key to check and make default:System.out.println("Invalid input");
payment)"); break;
break; }
case 5: }while(choice!=5);
System.out.println("Thank you for shopping"); }
}
Syllabus
Inheritance : Introduction, Need of Inheritance, Types of Inheritance, Benefits of Inheritance, Cost of Inheritance,
Constructors in derived Classes, Method Overriding, Abstract Classes and Interfaces. Polymorphism and Software
ge
Reuse: Introduction, Types of Polymorphism (Compile Time and Run Time Polymorphism), Mechanisms for Software
Reuse, Efficiency and Polymorphism.
io led
4.1 Inheritance : Introduction and Need
4.1.1(A) Visibility Modes and Effects
4.1.1 Inheritance
ic ow
The mechanism of deriving a class from another Q. State and explain various visibility modifiers in
class is known as inheritance. inheritance.
Te
The class from which another class is derived is Q. Define derived class. Give one example.
called as the base class while the class which is Q. State any two access specifier with example.
derived is called as derived class. Q. Explain various types of inheritance with example
Benefits or need of Ineritance Q. How protected access specifier is different from
1. The main advantage of inheritance is that a private?
code written for a particular class is also Q. What are different types of inheritance ?
accessible to the objects of the classes (May 17, 3 Marks, Dec. 17, 3 Marks, Dec. 18, 7 Marks)
derieved from this class. This concept is
The members of a class may be public,
called as code-reusability.
protected or private and the class may also be
2. Inheritance implements a structured system
derived in the following ways :
of an organization or any system where the
1. Public
programming is to be implemented for.
2. Protected
3. The attributes (i.e. data members and
method members) that are common for 3. Private
many classes, can be written in a base class These keywords viz. public, protected and
and accessible to all the classes derieved private are called as “access specifiers”, as they
from the base class. decide the access of a member.
The visibility of base class members within the To derive a class from another we need to use
derived class is as shown in Table 4.1.1 the following syntax:
Table 4.1.1 : Visibility of base class members
class derived_class_name : access_specifier
in the derived class
base_class_name
Base class Derived class visibility Let us see these types of inheritance in the
member Public Protected Private subsequent sub-sections.
visibility
derivation derivation derivation
4.1.2 Introduction to Inheritance
Public Public Protected Private
The mechanism of deriving a class from another
members
class is known as inheritance.
Protected Protected Protected Private
ge
The class from which another class is derived is
members
called as the base class or super class while the
Private Not Not Not
io led
class which is derived is called as derived class
members inherited inherited inherited
or sub class.
Hence, you will notice in the Table 4.1.1, in case
ic ow
There are various types of inheritance namely : These keywords viz. public, protected, private,
5. Hierarchical Inheritance
Access Location
ge
Non-subclasses in other Yes No No No No
packages
io led
Hence, you will notice in the Table 4.1.2, the 4.1.3 Cost of Inheritance
public members are visible in the entire
program and also in other packages. In terms of time, the cost of inheritance is
ic ow
s.add();
s.display();
getch();
}
Output
ge
for Program 4.2.1 protected, so that they are accessible from the
# include<iostream.h> derived class function to calculate the sum.
# include<conio.h>
io led
The base class also has a function in public
class Data visibility to read the inputs from user. The
{
derived class also has public member functions
ic ow
protected:
add() and display() to find the sum of the two
int a,b;
numbers taken and to display this sum
n
public:
respectively.
bl kn
void read()
{ The class “Sum” is derived from the class
at
};
class Sum: public Data The members of the base class are shown
{ available in the derived class in the class
private: diagram in Fig. P.4.2.1 but these member
int sum; functions and member variables are not to be
public: defined again in the derived class when
void add() actually writing the program. This concept of
{ gaining access to the members of the base class
sum=a+b; is called as code reusability.
}
The main() function has first a creation of the
void display()
object of the class “Sum”. The object of the class
{
sum can access all the functions i.e. read(),
cout<<"The sum is "<<sum;
} add() and display(); because the derived class
}; derives the protected members in the same
void main() visibility when derived publicly as discussed in
{ Table 4.1.2.
clrscr(); The functions to read, calculate the sum and
Sum s; display the sum are thereafter called one by
s.read(); one.
The class diagram of this requirement is as cout<<"The area of the circle is "<<result;
shown in Fig. P. 4.2.2. This diagram shows that the }
class “Area” is derived from class “Data” in public };
visibility. void main()
{
clrscr();
Area a;
a.read();
a.compute();
ge
a.display();
getch();
io led
}
Output
ic ow
Explanation
Fig. P. 4.2.2 : Class Diagram of Single Inheritance
for Program 4.2.2
A program with similar logic, just that instead
at
# include<iostream.h>
of a circle.
# include<conio.h>
Te
int price; {
}; protected:
class Table:public Furniture
int no;
{
char name[20];
private:
};
int height,area;
public: class Fitness:public Employee
void accept() {
{ private:
cout<<"Enter material, price, height and area:"; int height,weight;
cin>>material>>price>>height>>area; public:
}
void get_data()
void display()
{
ge
{
cout<<"Enter name, number height and weight:";
cout<<"Material:"<<material<<"\nPrice:"<<price< cin>>name>>no>>height>>weight;
io led
<"\nHeight:"<<height<<"\nArea:"<<area; }
}
void display()
};
ic ow
{
void main()
n
{
cout<<"Name:"<<name<<"\nNumber:"<<no<<"\n
bl kn
Table t;
Height:"<<height<<"\nWeight:"<<weight;
clrscr();
at
}
Pu ch
t.accept();
t.display(); };
getch(); void main()
Te
} {
Output Fitness b;
ge
class Sub:public Base
{
public:
io led
Sub(int b):Base(b)
{
cout<<"Sub class constructor:"<<b<<endl;
ic ow
}
};
n
void main()
bl kn
{
clrscr();
at
Pu ch
Sub s(5);
getch();
}
Te
Output
Base class constructor:5
Sub class constructor:5
ge
io led
Fig. 4.2.1(a) : Multi level inherritance
ic ow
n
bl kn
at
Pu ch
ge
void display()
{ io led
cout<<"The percentage is "<<percent;
}
};
ic ow
void main()
{
n
clrscr();
bl kn
Percent a;
a.read();
at
Pu ch
a.sum();
a.calculate();
Te
a.display();
getch();
}
Output
Enter the marks obtained in Physics, Chemistry and Fig. P. 4.2.7 : Class Diagram of Multi Level Inheritance for
Maths90 Program 4.2.7
98
# include<iostream.h>
99
# include<conio.h>
The percentage is 95.666664
class Data
Explanation {
The most important part of a program based on protected:
inheritance is the class diagram. Once you draw float r;
the class diagram then writing the program to public:
implement the diagram is very simple. void read()
This program is also just an implementation of {
the class diagram drawn in the Fig. P. 4.2.6. cout<<"Enter the radius of the circle: ";
The implementation is similar to that as seen cin>>r;
in single inheritance, only that there is one }
more level of inheritance.
ge
private: Program 4.2.8
float volume; io led #include<iostream.h>
public: #include<conio.h>
void calculate() #include<stdio.h>
{ class Customer
ic ow
volume=4*area*r/3; {
} protected:
n
void display() char name[20];
bl kn
{ float phone;
cout<<"The volume of the sphere is "<<volume; };
at
Pu ch
Number:"<<phone #include<iostream.h>
<<"\nAccount #include<conio.h>
number:"<<acc_no<<"\nBalance:"<<balance class student
<<"\nLoan number:"<<loan_no<<"\nLoan amount:"
{
<<amount;
protected :
}
int roll_no ;
};
public :
void main()
void get_no (int) ;
{
void put_no (void) ;
clrscr();
};
Burrower b;
void student :: get_no ( int a)
b.accept();
{
b.display();
roll_no = a ;
getch();
ge
}
} io led void student :: put_no ( )
Output {
Enter name, phone number, account number, balance, loan cout << "Roll Number :" << roll_no << "\n" ;
number and loan amount:a }
ic ow
200000 public :
Name:abc void get_marks (float, float);
Te
ge
return 0; Program 4.2.10 : Write a program to define the following
} io led relationship using multiple inheritance.
In this case one class is derived from multiple Fig. P. 4.2.10 : Class Diagram of Multiple Inheritance for
classes. Program 4.2.10
The class diagram of such a inheritance can be # include<iostream.h>
as shown in Fig. 4.2.2. # include<conio.h>
class Polygon
{
protected:
int height, width;
public:
void read(int a, int b)
{
height=a;
width=b;
}
};
class Output
{
Fig. 4.2.2 : Multiple inheritance
public: Output
void output(int x)
1. Area of Rectangle
{
2. Area of Triangle
cout<<"Area is "<<x;
} Enter your choice:2
}; Enter height and width:5
class Rectangle: public Polygon, public Output 4
{ Area is 10
public:
Explanation
int area()
{ The most important part of a program based on
return(height*width); inheritance is the class diagram. Once you draw
} the class diagram then writing the program
}; based on the diagram is very simple.
class Triangle: public Polygon, public Output
ge
{ Here, also we have just implemented the class
public: diagram drawn in the Fig. P. 4.2.10.
int area()
io led
4.2.4 Hybrid Inheritance
{
return(height*width/2); Q. What is hybrid inheritance ? Give one example.
ic ow
} (4 Marks)
};
In this case there is a mixture of multi level
n
void main()
and multiple inheritances. Hence the name is
bl kn
{
clrscr(); hybrid inheritance.
at
cin>>choice;
cout<<"Enter height and width:";
cin>>h>>w;
switch(choice)
{
case 1:
Rectangle r;
r.read(h,w);
a=r.area();
r.output(a);
break;
case 2:
Triangle t;
t.read(h,w);
a=t.area();
t.output(a);
break;
default: cout<<"Invalid choice";
} Fig. 4.2.3 : Hybrid inheritance
getch();
}
ge
relationship using hybrid inheritance.
protected:
int score;
io led
public:
void accept()
{
ic ow
cin>>score;
}
at
Pu ch
};
class Result: public Test, public Sports
{
Te
int total;
public:
void calculate()
{
if(score==1)
total=marks+15;
else
Fig. P. 4.2.11 : Class Diagram of Hybrid Inheritance total=marks;
for Program 4.2.11 }
# include<iostream.h> void display()
# include<conio.h> {
# include<stdio.h> cout<<"The total is "<<total;
class Student }
{ };
protected: void main()
char name[20]; {
clrscr();
int roll_no;
Result r;
};
r.read();
class Test: public Student
r.accept(); # include<iostream.h>
r.calculate(); # include<conio.h>
r.display(); # include<stdio.h>
getch(); class Student
} {
Output protected:
Enter name, roll number and marks obtained:Sandeep char name[20];
24 int roll_no;
81 };
1. Student has won in national sports event
class Test: public Student
2. Student has not won in any national sports event
{
Enter your choice:1
protected:
The total is 96
int marks;
ge
4.2.5 Problem in Multiple and Hybrid public:
Inheritance
void read()
When deriving a class from multiple classes i.e.
io led {
in Multiple Inheritance or Hybrid Inheritance,
there is a problem. The members of the two cout<<"Enter name, roll number and marks
base classes from which a class is derived, may obtained:";
ic ow
};
name along with the function name when
calling it. class Sports
at
Pu ch
ge
getch(); OR Write a C++ program to demonstrate concept of
} io led multilevel and hierarchical inheritance.
96
n
1. Student has won in national sports event
bl kn
# include<iostream.h>
The total is 96
# include<conio.h>
# include<stdio.h>
Te
Explanation
You will notice in this program both the classes class Staff
namely “test” and “Sports” have a member {
function with the same name i.e. read(). protected:
char name[20];
The resolution to the problem can be seen in
int code;
the main() function where the two functions are
};
called with specifying the class name along
class Teacher: public Staff
with the function name.
{
4.2.6 Hierarchical Inheritance private:
Q. Illustrate the hierarchical inheritance. (4 Marks) char subject[20];
Q. How hierarchical inheritance is achieved, explain
int experience;
with example. (4 Marks)
public:
void read()
{
cout<<"Enter name, code, subject and experience of
the teacher:";
gets(name);
cin>>code;
Fig. 4.2.4 : Hierarchical Inheritance gets(subject);
ge
char dept[20]; Enter name, code, subject and experience of the
teacher:Satish
int grade;
234
public:
io led
Maths
void read()
13
{
Teacher Details:
ic ow
cin>>code; Subject:Maths
gets(dept); Experience:13
at
Pu ch
{
cout<<"Officer
Details:\nName:"<<name<<"\nCode:"<<code
<<"\nDepartment:"<<dept<<"\nGrade:"<<grade;
}
};
void main()
{
clrscr();
int choice;
cout<<"1. Teacher\n2. Officer\nEnter the choice, whose
details you want to enter:";
cin>>choice;
switch(choice)
{
case 1:Teacher t;
Fig. P. 4.2.14 : Class Diagram of Hierarchical Inheritance for
t.read();
Program 4.2.14
t.display();
break;
# include<iostream.h> gets(name);
# include<conio.h> cin>>code;
# include<stdio.h> gets(dept);
class Staff cin>>grade;
{ }
protected: void display()
char name[20]; {
int code; cout<<"Officer
}; Details:\nName:"<<name<<"\nCode:"<<code
class Teacher: public Staff <<"\nDepartment:"<<dept<<"\nGrade:"<<grade;
{ }
private: };
ge
char subject[20]; class Typist: public Staff
int experience; {
protected:
public:
io led
void read() int speed,experience;
{ };
ic ow
cout<<"Enter name, code, subject and experience of class Regular: public Typist
the teacher:"; {
n
gets(name); private:
bl kn
{ default:cout<<"Invalid choice";
cout<<"Enter name, code, speed, experience and }
dailywages of the Casual typist:"; getch();
gets(name); }
cin>>code>>speed>>experience>>dailywages;
Output
}
void display() 1. Teacher
2. Officer
{
3. Regular Typist
cout<<"Casual Typist
Details:\nName:"<<name<<"\nCode:" 4. Casual Typist
ge
} teacher:Satish
}; 234
io led
void main() Maths
{ 13
cin>>choice;
switch(choice) 4.3 Types of Inheritance or Mechanism
Te
Output
Explanation
ge
import java.util.*;
class Data{ The base class also has a method in public
protected int a, b; visibility to read the inputs from user. The
io led
public void read(int x, int y) derived class also has public member methods
{
add() and display() to find the sum of the two
a=x;
numbers taken and to display this sum
ic ow
b=y;
} respectively.
n
} The class “Sum” is derived from the class
bl kn
Program 4.3.2 : Write a program to find the area of circle public static void main (String args[]) {
using single inheritance such that the base class method float x;
must accept the radius from the user and the derived class Scanner sc = new Scanner (System.in);
method must calculate and display the area. System.out.println("Enter the radius:");
Solution : x=sc.nextFloat();
The class diagram of this requirement is as Area a=new Area();
shown in Fig. P. 4.3.2. This diagram shows that the a.read(x);
class “Area” is derived from class “Data”. a.calculate();
a.display();
}
}
Output
ge
Enter the radius:
10
Area=314.0
io led
Explanation
Fig. P. 4.3.2 : Class Diagram of Single Inheritance for 4.3.2 Multi Level Inheritance
Program 4.3.2 In this case one class is derived from a class
at
Pu ch
public void read(float x) In this case, class ‘C’ is derived from class ‘B’
{ which is derived from class ‘A’.
r=x; Let us see some program examples using
} multilevel inheritance.
}
class Area extends Data
{
private float area;
public void calculate()
{
area=3.14f*r*r;
}
public void display()
{
System.out.println("Area="+area);
}
}
class Main{
ge
public void compute()
io led {
volume=area*r*4/3;
}
public void output()
ic ow
{
System.out.println("Volume="+volume);
n
}
bl kn
}
at
class Main{
Pu ch
Explanation }
The implementation of the class diagram shown class Main{
in Fig. P. 4.3.3 is done in similar manner as for public static void main (String args[]) {
the previous program. float pay;
int c,e;
Program 4.3.4 : Consider a class network given. The
String str,str1;
class ‘Admin’ derives information from the class ‘Account’
which in turn derives information from ‘Person’ class. Write a Scanner sc = new Scanner (System.in);
program to display Admin object. System.out.println("Enter name, code, pay and exp:");
str1=sc.nextLine();
c=sc.nextInt();
pay=sc.nextFloat();
e=sc.nextInt();
Admin a=new Admin();
ge
a.accept(str1,c,pay,e);
io led a.display();
}
}
Program 4.3.4
Enter name, code, pay and exp:
n
Solution : Ajay
bl kn
10
String name; Name:Ajay
} Code:325
Te
ge
dept =sc.next();
grade =sc.nextInt();
}
io led
public void display()
Fig. P. 4.3.5 : Class Diagram of Hierarchical Inheritance for
{
ic ow
}
{
}
protected String name;
at
ge
}
code=sc.nextInt();
Output
speed=sc.nextInt();
io led 1. Teacher
experience=sc.nextInt();
dailywages=sc.nextFloat(); 2. Officer
} 3. Regular Typist
ic ow
Wages:"+dailywages); 325
} Accounts
Te
} 1
class Main Officer Details:
{ Name:Ajay
public static void main(String args[]) Code:325
{ Department:Accounts
Scanner sc = new Scanner (System.in); Grade:1
int choice; Program 4.3.6 : Assume that a bank maintains two kinds of
System.out.println("1. Teacher\n2. Officer\n3. Regular accounts for its customers. The saving account provides
Typist\n4. Casual Typist\nEnter the choice, whose details compound interest and withdrawal facilities but no cheque
you want to enter:"); book facility. The current account provides cheque book
facility but no interest. Current account holders should also
choice=sc.nextInt();
maintain a minimum balance and if the balance falls below
switch(choice) this level a service charge is imposed. Create a class
{ account that stores customer name, account number and
case 1:Teacher t=new Teacher(); type of account. From this derive the classes current-acct
and savings-acct to make them more specific to their
t.read();
requirements include the necessary methods in order to
t.display(); achieve the following tasks : (i) Accept deposit from a
break; customer and update the balance (ii) Display the balance
case 2:Officer o=new Officer(); (iii) Compute the deposit interest (iv) Permit withdrawal and
update the balance (v) Check the minimum balance,
o.read();
impose penalty if necessary, and update the balance.
ge
{ acc_no=sc.nextInt();
public void read() penalty=0;
min_bal=0;
{
io led
Scanner sc = new Scanner (System.in); interest=sc.nextFloat();
System.out.println("Enter name, account number, balance=sc.nextInt();
ic ow
min_bal=sc.nextInt(); balance+=x;
balance=sc.nextInt(); }
type=“Current”;
Te
ge
s.withdraw(5000); parameter list to be called as method
s.display(); overriding. Method overloading will be
discussed in this chapter later in
}
io led
} section
overriding.
Enter name, account number, penalty, minimum balance
n
and opening balance of the Program 4.4.1 : Write a program to calculate volume of
bl kn
325 class that will have a method to find and display the area of a
circle and another class derived from this will have methods
2
to calculate and display the volume of the sphere.
Te
10000
Solution :
25000
import java.util.*;
Account Details:
class Data{
Name:Ajay
protected float r;
Account no:325
public void read(float x)
Balance:30000.0
{
Cheque book facility:true
r=x;
Enter name, account number, interest rate and opening
balance of the current }
account holder: }
Vijay class Area extends Data
425 {
6 protected float area;
10000 public void calculate()
Account Details: {
Name:Vijay area=3.14f*r*r;
Account no:425 }
Balance:15000.0 public void display()
Cheque book facility:false {
ge
} methods.
} An abstract class can have methods with only
io led
class Main{ declaration and no definition. These methods
public static void main (String args[]) { are called as abstract methods. The abstract
ic ow
} Solution :
import java.util.*;
Output
abstract class Base{
Enter the radius: protected float r,vol;
10 public void read(float x)
Volume=4186.6665 {
r=x;
Explanation
}
The implementation Program 4.4.1 is done with public abstract void calculate();
same method display() in base class Area and in public void display()
sub class Volume. {
Here the method display() of the derived class System.out.println("Volume="+vol);
}
i.e. “Volume” overrides the method display() of
}
the base class “Area”.
class Sphere extends Base
ge
public static void main (String args[]) { public void display()
float x; {
Scanner sc = new Scanner (System.in);
io led System.out.println("Area="+area);
System.out.println("Enter the radius:"); }
x=sc.nextFloat(); }
Sphere s=new Sphere();
ic ow
{
s.display(); r=x;
Hemisphere h=new Hemisphere(); }
at
Pu ch
System.out.println("Hemisphere:"); area=3.14f*r*r;
h.display(); }
} }
} class Rectangle extends Base
{
Output
public void read(float x, float y)
Enter the radius: {
10 l=x;
Sphere: b=y;
Volume=4186.6665 }
Hemisphere: public void calculate()
Volume=2093.3333 {
area=l*b;
Explanation
}
The method calculate() is declared to be }
“abstract” in the base class. This makes it class Triangle extends Base
compulsory for the derived class to override this {
method. Also it makes the base class to be public void read(float x, float y)
compulsorily be declared as “abstract” {
l=x;
b=y;
} Explanation
public void calculate()
The implementation program of the abstract
{
area=0.5f*l*b; method is done with same methods read() and
} calculate() in base abstract class and in sub
} classes Circle, rectangle and triangle.
class Main{ The base class has the method read() and
public static void main (String args[]) {
calculate() declared as “abstract” making the
float x,y;
base class to be “abstract” and also making it
Scanner sc = new Scanner (System.in);
compulsory for the derived classes to override
System.out.println("Circle:");
System.out.println("Enter the radius:"); these methods.
x=sc.nextFloat();
Program 4.5.3 : Write a abstract class program to calculate
Circle s=new Circle(); area of square and triangle.
s.read(x);
ge
Solution :
s.calculate();
s.display(); import java.util.*;
abstract class Base{
io led
System.out.println("Rectangle:");
System.out.println("Enter length and breadth:"); protected float l,b,area;
x=sc.nextFloat(); abstract void calculate();
y=sc.nextFloat();
ic ow
}
h.display();
}
System.out.println("Triangle:");
at
{
Triangle t=new Triangle();
l=x;
t.read(x,y);
t.calculate(); }
t.display(); public void calculate()
} {
} area=l*l;
}
Output
}
Circle: class Triangle extends Base
Enter the radius: {
10 public void read(float x, float y)
Area=314.0
{
Rectangle:
l=x;
Enter length and breadth:
10 b=y;
10 }
Area=100.0 public void calculate()
Triangle: {
Enter height and breadth: area=0.5f*l*b;
10 }
10
}
Area=50.0
class Main{ The base class has the method read() and
public static void main (String args[ ]) { calculate() declared as “abstract” making the
float x,y; base class to be “abstract” and also making it
Scanner sc = new Scanner (System.in); compulsory for the derived classes to override
System.out.println("Square:"); these methods.
System.out.println("Enter the length of a side:");
4.5.2 Interface
x=sc.nextFloat();
Square s=new Square(); The multiple inheritance problem is solved in
s.read(x); Java with the help of Interface.
s.calculate(); Multiple Inheritance is possible when
s.display(); extending interfaces i.e. one interface can
System.out.println("Triangle:");
ge
extend as many interfaces as required.
System.out.println("Enter height and breadth:");
Java does not allow multiple inheritance, but it
x=sc.nextFloat();
io led allows to extend one class and implement as
y=sc.nextFloat();
many interfaces as required.
Triangle t=new Triangle();
A class that implements an interface has to
ic ow
t.read(x,y);
either define all the methods of the interface or
t.calculate();
n
declare abstract methods and the method
bl kn
t.display();
definitions may be provided in the subclass.
}
at
Pu ch
The implementation program of the is done No object can be made of an interface i.e. it
cannot be instantiated.
with same methods read() and calculate() in
base abstract class and in sub classes Square
and triangle.
1. Abstract class is a class which contains one or An Interface can contain only method
more abstract methods, which are to be defined by declarations and no definition.
sub classes.
2. Abstract class definition begins with the keyword An Interface definition begins with the
“abstract” keyword followed by Class definition. keyword “interface” followed by the
interface definition.
3. Abstract classes can have general methods defined Interfaces have all methods with only
and some methods with only declaration defined declarations defined in subclasses
ge
in the subclasses. i.e. classes implemented from the interface.
4. Variables in Abstract class need not be public, All variables in an Interface are by default
io led
static and final. public, static and final.
5. Abstract class does not support Multiple Interface supports multiple Inheritance.
ic ow
Inheritance.
6. An abstract class can contain private as well as An Interface can only have public members.
n
protected members.
bl kn
7. When a class extends an abstract class, it need not A class implementing an interface must
at
Pu ch
implement any of the methods defined in the implement all of the methods declared in the
abstract class. interface.
Te
ge
Scanner sc = new Scanner (System.in); }
System.out.println("Enter the radius:");
io led Implement the above interface using suitable JAVA class
x=sc.nextFloat(); program and also develop the main program.
Sphere s=new Sphere(); Solution :
s.read(x); import java.util.*;
ic ow
ge
{
public void displayMatrix()
product[i][j]=0;
{
io led for(k=0;k<=N-1;k++)
System.out.println("Matrix A");
{
for(i=0;i<=M-1;i++)
product[i][j]+=a[i][k]*b[k][j];
{
ic ow
for(j=0;j<=N-1;j++) }
{ }
n
System.out.print(a[i][j]+"\t"); }
bl kn
} {
System.out.println("Matrix B"); for(j=0;j<=N-1;j++)
Te
for(i=0;i<=M-1;i++) {
{ System.out.print(product[i][j]+"\t");
for(j=0;j<=N-1;j++) }
{ System.out.println();
System.out.print(b[i][j]+"\t"); }
} }
System.out.println(); public void transposeMatrix()
} {
} for(i=0;i<=M-1;i++)
public void addMatrix() {
{ for(j=0;j<=N-1;j++)
for(i=0;i<=M-1;i++) {
{ ta[j][i]=a[i][j];
for(j=0;j<=N-1;j++) }
{ }
sum[i][j]=a[i][j]+b[i][j]; for(i=0;i<=M-1;i++)
} {
} for(j=0;j<=N-1;j++)
System.out.println("The sum of two matrices is"); {
for(i=0;i<=M-1;i++) tb[j][i]=b[i][j];
ge
{ Enter the element:23
for(j=0;j<=N-1;j++) io led Enter the element:24
{ Enter the element:25
System.out.print(tb[i][j]+ "\t"); Matrix b:
} Enter the element:1
ic ow
ge
4 9 14 19 24 referred to as late binding.
5 10 15 20 25 io led
Transpose of Matrix 2
1 6 11 16 21
2 7 12 17 22
ic ow
3 8 13 18 23
4 9 14 19 24
n
5 10 15 20 25
bl kn
Explanation :
at
We have already seen the static polymorphism types i.e. constructor overloading, function overloading
and operator overloading.
We will see dynamic polymorphism in the subsequent sub section.
Sr. Compiler Time Polymorphism Run Time Polymorphism
No.
1. In compile time polymorphism call is resolved by In run time polymorphism call is not resolved
the compiler. by the compiler.
2. It is also known as static binding, Early binding It is also known as dynamic binding late
and overloading as well. binding and over riding as well.
3. Overloading is compile time polymorphism where Over riding is run time polymorphism having
more than one methods share the same name with same method with same parameters or
different parameters or signature and different signature but associated in a class and its
return type. subclass.
ge
4. It is achieved by function over loading and operator It is achieved by virtual functions and
over loading. pointers.
io led
5. It provides fast execution because known early It provides slow execution as compare to
compile time. early binding because it is known at runtime.
ic ow
6. Compile time polymorphism is less flexible as all Run time polymorphism is more flexible as
things execute at compile time. all things execute at run time.
n
4.6.1 Polymorphism in C++
bl kn
Polymorphism
Polymorphism has two types based on the time
of resolution. If the resolution is done during Q. Write short notes on : Virtual function. (5 Marks)
the compiling of the program, then it is called Q. What is function overriding? Give example.
as static polymorphism. But if the resolution is (10 Marks)
done during the run time, then it is called as Q. Explain pure virtual function with example.
dynamic polymorphism.
(5 Marks)
Static polymorphism or early binding includes
Q. Explain virtual function with suitable example.
method overloading and constructor
(4 Marks)
overloading.
Q. What is virtual function ? Why we need virtual
Dynamic polymorphism or late binding includes
function ? (4 Marks)
method overriding and dynamic method
Q. What is pure virtual functions ? Write down the
dispatch.
rules used for pure virtual function. (4 Marks)
We have already seen constructor overloading
Q. How to define virtual function ? Give example.
in earlier chapter and method overriding in this
(4 Marks)
chapter earlier. We will still see these concepts
again and with the remaining topics also. Dynamic binding of a member function is
achieved in C++ with the use of the keyword
“virtual”.
Those member functions that are preceded by If a function in a base class is left blank i.e.
the keyword “virtual” are known as virtual without any definition and only declaration
functions. then;
4.7.2 Rules for Virtual Functions 1. The function must be declared “virtual”.
2. This function is called as “pure virtual
Q. Why do we need virtual functions ? ( 4 Marks)
function” or “do nothing function” or
Q. What is pure virtual function ? (2 Marks)
“dummy function”.
Q. Write short note on: virtual function. (5 Marks)
3. This function must be overridden in the sub
Q. Explain any four rules for virtual function. (4 Marks)
class i.e. the function with same name and
Q. What is need of virtual function? Explain with
parameters must be declared and defined in
example. (4 Marks
the sub class of the virtual class.
If a base class function has the same name as 4. A pure virtual function can be defined with
that of the derived class then the function
ge
the following syntax:
called depends on the parameters, this is called
virtual return_type function_name () =0;
as function overloading. But if the base class
io led For e.g.
function and derived class function have same
name and same parameter list then it is said to virtual void read() = 0;
be function overriding. Let us see examples for each of these concepts
ic ow
then the binding of such a function with its call 2. Virtual function
becomes dynamic i.e. runtime. Thus, if this
3. Pure virtual function
at
Pu ch
ge
}; int a,b;
void main() io led public:
{ virtual void read()
clrscr(); {
Sub s; cout<<"Enter two values:";
ic ow
s.read(); cin>>a>>b;
s.display(); }
n
getch(); virtual void display()
bl kn
} {
cout<<"\nThe values
at
Output
Pu ch
are:"<<a<<"\n"<<b<<endl;
Enter 4 values:4 }
3 };
Te
The class “Sub” is derived from the class “Base”. cout<<"Enter 4 values:";
The functions read() and display() are declared cin>>a>>b>>c>>d;
and defined in the base class and derived class. }
The name and parameter list of the functions in virtual void display()
base class and derived class are same. This is {
called as function overriding. cout<<"\nThe values are:"
<<a<<"\n"<<b<<"\n"<<c<<"\n"<<d<<endl;
In this case, the functions in the class “Sub”
}
override the functions read() and display() of
};
the class “Base”.
void main()
{
ge
Output
Program 4.7.3 : Write a program to demonstrate pure
Enter 2 values:1 virtual function.
io led
2 #include<iostream.h>
#include<conio.h>
The values are:1 class Base
ic ow
2 {
n
Enter 4 values:1 protected:
bl kn
2 int a,b;
3 public:
at
4
Pu ch
{ #include<iostream.h>
clrscr(); #include<conio.h>
Sub s; class Shape
Base *ptr; {
ptr=&s; protected:
ptr->read(); int a,b,area;
ptr->display(); public:
getch(); virtual void read()
} {
Output }
virtual void calc_area()
Enter 4 values:1
{
2
}
3
ge
void display()
4
{
The values are:1
io led cout<<"Area="<<area<<endl;
2
}
3
};
4
ic ow
void read()
defined without any body and are preceded by
{
at
}
late binding. Such functions without any body void calc_area()
and overridden in the derived class are called {
as “pure virtual function”. area=a*b/2;
}
As already discussed pure virtual functions are
};
used to create a template wherein all the
class Rectangle: public Shape
classes derived from the class that has a pure {
virtual function must have the same function public:
defined with its body. If not defined than again void read()
it has to be declared as virtual and defined with {
a blank body as shown in program 4.10.3. cout<<"Enter length and breadth";
cin>>a>>b;
The remaining things are similar to that of the
}
previous program.
void calc_area()
Program 4.7.4 : Create class shape. Derive two classes {
Triangle and Rectangle. Accept dimensions of Triangle and area=a * b;
Rectangle with appropriate functions. Make area() function }
virtual which is common to all classes. With area function };
calculate area of triangle and rectangle. Display the result.
ptr->display(); #include<conio.h>
ge
ptr->calc_area(); protected:
ptr->display(); int a,b;
io led
getch(); public:
} void read()
ic ow
Output {
cout<<"Enter two values:";
n
Enter base and height2
bl kn
10 cin>>a>>b;
Area=10 }
at
Pu ch
ge
} {
Output private int l,b;
io led
public Rectangle()
Enter 4 values:4 {
3 l=b=10;
ic ow
}
2
public Rectangle(int x)
n
1 {
bl kn
3
Pu ch
1
b=y;
Explanation }
The class “Sub” is derived from the class “Base”. public void area()
The functions read() and display() are declared {
and defined in the base class and derived class. System.out.println("Area="+l*b);
}
The name and parameter list of the functions in
}
base class and derived class are same. This is
class Main
called as function overriding.
{
In this case, the functions in the class “Sub” public static void main(String args[])
override the functions read() and display() of {
the class “Base”. Rectangle r1=new Rectangle();
The keyword "virtual" while deriving the class Rectangle r2=new Rectangle(5);
"sub", makes the class "base" as abstract. Rectangle r3=new Rectangle(3,3);
r1.area();
4.7.5 Static Polymorphism in Java r2.area();
As already discussed, those multiple forms r3.area();
(polymorphism) whose resolution is done during }
the compile time are grouped under static }
polymorphism.
Output return(3.14f*r*r);
Area=100 }
Area=25 public float area(float l, float b)
Area=9 {
return (l*b);
Explanation
}
The class Rectangle has three constructors with public float area(float a, float b, float c)
no parameters, one parameter and two {
parameters respectively. float s;
There are three objects of the class Rectangle s=(a+b+c)/2;
made in the main() method. The first object s=s*(s-a)*(s-b)*(s-c);
uses the default constructor, with no return(float)(Math.sqrt(s));
parameters. Hence the length and breadth are }
ge
initialized to 10 each and the area is displayed }
as 100.
io led class Main
{
The second object passes one parameter and
public static void main(String args[])
hence both length and breadth are initialized to
{
the passed value for the second constructor.
ic ow
}
overloading.
Output
4.7.5(B) Method Overloading
Area of circle=314.0
Multiple Method with same name in the same Area of Rectangle=100.0
class or in the base and derived class with Area of Triangle=43.30127
different parameters is called as Method Explanation
overloading.
The class Area has three methods with the
Let us see some program examples of Method
same name i.e. area(). The methods have
overloading.
different number of parameters. This is called
Program 4.7.7 : Write a program to demonstrate Method as method overloading.
overloading by overloading the methods for calculating area
When one parameter is passed in the first
of circle, rectangle and triangle.
println() method, the area of circle is calculated
Solution :
and returned by the first method.
class Area
In the second case the area of rectangle is
{
printed as two parameters are passed.
private float x,y,z;
public float area(float r) In the third case, area of triangle is calculated
{ and printed as three parameters are passed.
Program 4.7.8 : Write a program to demonstrate Method When one parameter is passed in the first
overloading by overloading the methods for calculating println() method, the volume of cube is
volume of cylinder, cube and cuboid.
calculated and returned by the first method.
Solution :
In the second case the volume of cylinder is
class Volume
printed as two parameters are passed.
{
In the third case, volume of cuboid is calculated
private int x;;
and printed as three parameters are passed.
public float volume(float l)
{ Program 4.7.9 : Write a program to demonstrate Method
return(l*l*l); overloading in a base and derived class by overloading the
} methods for displaying the value of a variable contained in
the class.
public float volume(float r, float h)
Solution :
{
class Parent
ge
return (3.14f*r*r*h);
{
}
public void display(int x)
public float volume(float l, float b, float h)
io led
{
{
System.out.println(“x=“+x);
return(l*b*h);
}
}
ic ow
}
}
class Child extends Parent
n
class Main
{
bl kn
{
public void display(int x, int y)
public static void main(String args[])
at
{
Pu ch
{
System.out.println("x="+x+"\ny="+y);
Volume a=new Volume();
}
System.out.println
Te
}
("Volume of cube="+a.volume(10));
class Main
System.out.println
{
("Volume of cylinder="+a.volume(10,10));
public static void main(String args[])
System.out.println
{
("Volume of cuboid="+a.volume(10,10,10));
Child c=new Child();
}
c.display(10);
}
c.display(5,5);
Output }
Volume of cube=1000.0 }
Volume of cylinder=3140.0
Output
Volume of cuboid=1000.0
x=10
Explanation x=5
The class Volume has three methods with the y=5
same name i.e. volume(). The methods have
Explanation
different number of parameters. This is called
as method overloading. The class Parent has a method display() with
one parameter.
Class “child” extended from the class “Parent” 7. Binary operators overloaded by means of
has the same method display() with two friend function can accept up to two
parameters. parameters.
When one parameter is passed you will notice 8. Some of the operators cannot be overloaded
the base class method is called while when two viz.
parameters are passed you will notice that the (a) sizeof()
derived class method is called.
(b) member operator (i.e. '.')
Here the methods with same name and
(c) pointer to member operator (i.e. ".*")
different parameter list are not in the same
(d) scope resolution operator (i.e. "::")
class but in the base and derived class. This is
also called as Method overloading (e) conditional operator (i.e. "?:")
9. Some of the operators cannot be overloaded
4.7.5(C) Operator Overloading
by friend functions viz.
ge
(SPPU - May 17, Dec. 18)
(a) assignment operator (i.e. '=')
Q. What are rules of operator overloading ? (b) function call operator (i.e. "( )")
io led
(May 17, 3 Marks)
(c) subscripting operator (i.e. "[ ]")
Q. Explain need of operator overloading. Write C++
(d) class member access operator (i.e. "->")
ic ow
There are some rules necessary to be known for meant for operator overloading has a
operator overloading. Below is a list of these special syntax as given below :
Te
y=-y; {
} x=-x;
void display() y=-y;
{ }
cout<<"x="<<x<<endl<<"y="<<y; void display()
} {
};
cout<<"x="<<x<<endl<<"y="<<y;
void main()
}
{ };
clrscr();
void main()
Negate n;
{
n.read(); clrscr();
n.compute();
Negate n;
n.display();
n.read();
ge
getch();
-n;
}
n.display();
io led
Output getch();
Enter two numbers4 }
6
ic ow
Output
x=-4
Enter two numbers4
n
y=-6
6
bl kn
Explanation x=-4
A simple program with three functions y=-6
at
Pu ch
functions are called one after the other. overloading operation by overloading the
Let us see the same operation by overloading operator unary minus i.e. ‘-‘.
the unary minus ('-') operator in the following Compare to previous program where we had to
program. call the compute() function, here we have to just
Program 4.7.11: Write a program to negate the values of use the negate operator with the object of the
two variables contained in an object by overloading the class i.e. “–n;”.
operator unary negate i.e. ‘-’.
Actually operators can work only with variables
#include<iostream.h>
of basic data type. The operators cannot be used
#include<conio.h> with the objects of a class. But operator
class Negate overloading allows those operators that are
{ overloaded in a class to be used with the objects
int x,y; of that class.
public:
Remember, we cannot use an operator with an
void read()
{ object unless we have written an operator
cout<<"Enter two numbers"; overloading function for that operator in the
cin>>x>>y; corresponding class.
}
void operator -()
ge
#include<iostream.h>
x--;
#include<conio.h>
y--;
class Complex
}
io led
{
void operator ++ ()
{ int x,y;
public:
ic ow
x++;
y++; void read()
n
} {
bl kn
cout<<"x="<<x<<endl<<"y="<<y<<endl; cin>>x>>y;
Pu ch
} }
}; Complex operator + (Complex c)
Te
void main() {
{ Complex c1;
clrscr(); c1.x=x+c.x;
IncDec n; c1.y=y+c.y;
n.read(); return c1;
--n;
cout<<"After decrementing the object one time\n"; }
n.display(); void display()
++n; {
++n; if(y<0)
cout<<"After incrementing the object twice\n"; cout<<x<<y<<"i";
n.display(); else
getch(); cout<<x<<"+i"<<y;
} }
Output };
void main()
Enter two numbers4
{
5
clrscr();
After decrementing the object one time
Complex c1;
x=3
Complex c2;
ge
c1+=c2;
Explanation c1.display();
Here we have overloaded the binary operator
io led getch();
“+” by the operator overloading function }
Complex operator + (Complex c).
Output
Two objects of the class complex are created.
ic ow
The values of these complex variables are Enter the real and imaginary parts of a complex number:2
read.
n
3
The two objects of the class “complex” are
bl kn
6+i8
Pu ch
operator “+=” to add two complex numbers. Similar implementation like the previous
#include<iostream.h> program, but the original object of the class
#include<conio.h> “complex” i.e. ‘c1’ is changed instead of having
another object.
class Complex
{ Program 4.7.15 : Write a program to add two distances
int x,y; entered by the user in feet and inches using overload binary
public: operator “+”.
void read() #include<iostream.h>
{ #include<conio.h>
cout<<"Enter the real and imaginary parts of a class Distance
complex number:";
{
cin>>x>>y;
int ft,in;
}
public:
void operator += (Complex c)
void read()
{
{
x=x+c.x;
cout<<"Enter the distance in feet and inches:";
y=y+c.y;
cin>>ft>>in;
}
}
void display()
Distance operator + (Distance d)
{
{
ge
inches.";
} A base class reference object can be used to
}; refer either a base class object or a derived class
io led
void main() object.
{ In this case the overridden method to be called
depends on the object to which the reference
ic ow
clrscr();
Distance d1; object is referring at that moment.
n
Distance d2; This can be realized only during the run time
bl kn
ge
} class Bank
} {
private int accountNumber;
Output
io led
private float accountBalance;
y=5
private String accountHolder;
x=10
ic ow
} if(amount>accountBalance-1000)
public void updateName() System.out.println("Minimum balance cannot be maintained
{ if you withdraw this amount");
Scanner sc = new Scanner(System.in); }while(amount>accountBalance-1000);
System.out.println(accountNumber+ accountBalance = accountBalance - amount;
"\t"+accountHolder); System.out.println(amount+ " debited successfully
System.out.println("Account Holder details:-"); from account number "+accountNumber+", updated
account balance is "+accountBalance);
System.out.print("First name : ");
}
name=sc.nextLine();
public void checkBalance()
System.out.print("Middle name : ");
{
middleName=sc.nextLine();
System.out.println("A/c
System.out.print("Last name : ");
"+accountNumber+"\n"+accountHolder+"\nAccount
surname=sc.nextLine(); Balance : "+accountBalance+"\n");
ge
accountHolder=name+" "+middleName+" }
"+surname;
}
accountHolder=accountHolder.toUpperCase();
io led public class Banking
System.out.println("Account "+accountNumber+"
{
Name updated to "+accountHolder);
public static void main(String args[])
}
ic ow
{
public void deposit()
int i,choice,count,copy;
{
n
String str,str1;
bl kn
float amount;
count=0;
System.out.print("Enter amount to deposit : ");
Scanner sc = new Scanner(System.in);
at
{
System.out.println(amount+ " credited successfully to
account number "+accountNumber+", updated account System.out.println("\n1 : Add account\n2 : Change
balance is "+accountBalance); account holder name\n3 : Deposit\n4 : Withdraw\n5 : Check
account balance\n6 : exit");
}
choice = sc.nextInt();
public boolean checkName(String str)
switch(choice)
{
if(accountHolder.equals(str)) return true; {
else return false; case 1: count=count+1;
} b[count-1] = new Bank(count);
public void withdraw() break;
{ case 2: System.out.println("Enter account number
float amount; or account holder's first name");
System.out.println("Balance = str=sc.next();
"+accountBalance+"\tMaintain minimum balance of if(str.charAt(0)>='1'&&str.charAt(0)<='9')
1000"); {
Scanner sc = new Scanner(System.in); copy=Integer.parseInt(str);
do if(copy>count)
{ {
System.out.print("Enter amount to withdraw : "); System.out.println("Account not found");
amount=sc.nextFloat(); break;
ge
copy=count+1; copy=i;
for(i=0;i<=count-1;i++) break;
{ }
io led
if(b[i].checkName(str)) }
{ if(copy>count)
ic ow
copy=i; {
break; System.out.println("Account not found");
n
} break;
bl kn
} }
if(copy>count) b[copy].deposit();
at
Pu ch
{ }
System.out.println("Account not found"); break;
break; case 4: System.out.println("Enter account number
Te
str1=sc.next(); {
str=str+" "+str1; System.out.print("Middle name : ");
str=str.toUpperCase(); str1=sc.next();
copy=count+1; str=str+" "+str1;
for(i=0;i<=count-1;i++)
{ System.out.print("Last name : ");
if(b[i].checkName(str)) str1=sc.next();
{ str=str+" "+str1;
copy=i; str=str.toUpperCase();
break; copy=count+1;
} for(i=0;i<=count-1;i++)
} {
if(copy>count) if(b[i].checkName(str))
ge
{ {
System.out.println("Account not found"); copy=i;
break;
break;
io led
} }
b[copy].withdraw(); }
ic ow
} if(copy>count)
break; {
n
case 5: System.out.println("Enter account number System.out.println("Account not found");
bl kn
if(str.charAt(0)>='1'&&str.charAt(0)<='9') b[copy].checkBalance();
{ }
copy=Integer.parseInt(str); break;
Te
Syllabus
Exception : Errors, Types of Errors, Exception and its Types, Exception-Handling Fundamentals, Uncaught Exception,
Using try and Catch, Multiple Catch Clauses, Nested Try Statements, User Define Exception using Throw.
ge
Generics : What are Generics? Introduction to Language Specific Collection Interface: List Interface and Set Interface,
Some of these abnormal conditions are known to the java compiler while some occur during run time
and are unknown to the compiler.
at
Pu ch
‘Exception’ is a class and it has sub classes. The different sub classes are the according to exceptions
possible in Java. The list of the names of sub classes of the base class Exception is given in the Table
5.2.1. This table lists all the checked and unchecked exceptions of Java and the condition for their
Te
occurrences.
Exception as discussed is an error condition occurrence. For example if a integer is expected and a
character is entered, then while parsing the character to integer, an error will occur. This error or
exception is called as NumberFormatException. It is one of the sub class of the base class ‘Exception’.
Since it is name of a class, there is no space between the words.
Exceptions are classified into two types namely : Checked Exceptions and Unchecked Exceptions.
Unchecked Exceptions are RuntimeException and its subclasses. These are not sub class of the class
Exception.
The compiler doesn’t check for the unchecked exceptions and hence the compiler doesn’t make the
programmers handle them.
In fact, the programmers may not even know that such an exception would be thrown.
Table 5.2.1
ge
ArrayIndexOutOfBoundsException Accessing an element out of the size of an array
io led i.e. outside its boundary
NegativeArraySizeException The variable used to create the array has a negative value hence
n
negative array size.
bl kn
NullPointerException Trying to access the members of an object which is not allocated with
at
Pu ch
NumberFormatException The value expected was a number and the data given is not a number.
StringIndexOutOfBounds Similar to array index out of bounds exception, but for an array of
strings.
Let us see a simple program that generates an Similarly, in this case if the number entered was
exception. We will accept two numbers from a character, we will get Number Format
user, the dividend and the divisor. The divisor Exception, i.e. not a proper number is entered.
entered by user must be zero, so that it Let us see the output in this case.
generates the divide by zero error.
Output 2
Program 5.2.1 : Write a program to perform division of two Enter two numbers:
numbers accepted from user to demonstrate
a
ArithmeticException and also NumberFormatException.
Exception in thread "main"
import java.io.*; java.lang.NumberFormatException: For input string: "a"
class Divide at
{ java.lang.NumberFormatException.forInputString(Unknown
Source)
public static void main(String args[]) throws IOException
ge
at java.lang.Integer.parseInt(Unknown Source)
{
at java.lang.Integer.parseInt(Unknown Source)
int a,b,res;
io led at Divide.main(Divide.java:9)
BufferedReader br = new BufferedReader (new
InputStreamReader (System.in)); If the numbers are entered properly then you
String str; will not get any error. You will get a proper
ic ow
a=Integer.parseInt(str);
str=br.readLine(); Enter two numbers:
at
Pu ch
b=Integer.parseInt(str); 5
res=a/b; 2
Te
ge
{ class Divide
statements; {
io led public static void main(String args[]) throws IOException
}
{
try Block
int a,b,res;
ic ow
The statements that you think can generate an BufferedReader br = new BufferedReader (new
error or exception must be placed in this block. InputStreamReader (System.in));
n
If an exception occurs then the catch block will String str;
bl kn
be executed and then the finally block will be System.out.println("Enter two numbers: ");
executed. str=br.readLine();
at
Pu ch
a=Integer.parseInt(str);
Else if no exception occurs, then the control will
str=br.readLine();
directly go to the finally block i.e. the catch block
Te
b=Integer.parseInt(str);
will not be executed.Java code that you think
try
may produce an exception is placed within a try
{
block for a suitable catch block to handle the
res=a/b;
error.
System.out.println("The Quotient=" + res);
If an exception occurs, but a matching catch
}
block is not found, then it reaches to the finally
catch(ArithmeticException ae)
block.
{
In any case, when the exception occurs in a System.out.println("Exception has occurred. You have
particular statement of try block, the remaining entered the divisor as zero");
statements after this statement of the try block }
are not executed i.e. no statements of the try }
block are executed after the exception }
generating statement.
Output 1
catch Block
Enter two numbers:
The exception thrown by the try block are
4
caught by the catch block.
0
The type of the exception occurred must match Exception has occurred. You have entered the divisor as
with the exception mentioned in the brackets of zero
the catch block.
ge
statement in the try block are not executed.
System.out.println(“Enter two numbers:”);
Let us see how the execution takes place if no
try
exception is generated.
io led
{
Output 2 str=br.readLine();
Enter two numbers: a=Integer.parseInt(str);
ic ow
5 str=br.readLine();
2 b=Integer.parseInt(str);
n
The Quotient=2 }
bl kn
System.out.println("Invalid number");
program behave when a character is given
}
instead of a number
Te
try
Output 3 {
Enter two numbers: res=a/b;
2 System.out.println("The Quotient=" + res);
a }
Exception in thread "main" catch(ArithmeticException ae)
java.lang.NumberFormatException: For input string: "a" {
at System.out.println(“Exception has occurred. You have
java.lang.NumberFormatException.forInputString(Unknown entered the divsior as zero”);
Source) }
at java.lang.Integer.parseInt(Unknown Source) }
at java.lang.Integer.parseInt(Unknown Source) }
at Divide.main(Divide.java:11)
Output
We have caught the arithmetic exception in the
Enter two numbers:
catch block. We haven’t caught the number 5
format exception, hence the exception will again a
show something not understandable to end user. Invalid number
Let us see in the next program how to handle Exception has occurred. You have entered the divisor as
zero
this exception.
Explanation str=br.readLine();
b=Integer.parseInt(str);
You will notice in this case the character is
res=a/b;
entered, but a proper error is displayed saying
System.out.println("The Quotient=" + res);
“Invalid number”.
}
The values of ‘a’ and ‘b’ are to be initialized. As
catch(ArithmeticException ae)
the statements in which the values are put into
{
the variables ‘a’ and ‘b’ may not be executed if
System.out.println("Exception has occurred. You have
the exception takes place in a statement before entered the divisor as zero");
them in the try block. }
Now one more exception is displayed, saying catch (NumberFormatException ne)
divisor given is zero. But you have entered {
divisor as a character. But the initial values of System.out.println("Invalid number");
ge
‘a’ and ‘b’ were zero. Since the statement that }
generated the first exception did not allow the }
new value to be given to the variable “b”, “b” }
io led
remained 0. Hence we get this exception.
Output 1
We will see in the next section how should we
Enter two numbers:
ic ow
Output 2
have all the statements that can generate an
exception in one try block and the catch blocks for Enter two numbers:
Te
ge
a=Integer.parseInt(str);
Program 5.5.1 : Write a program to perform division of two
str=br.readLine();
numbers accepted from user. Handle the Number format
b=Integer.parseInt(str);
io led exception and also handle the divide by zero exception using
res=a/b; nested try catch block.
System.out.println("The Quotient=" + res); import java.io.*;
ic ow
} class Divide
catch(ArithmeticException ae) {
n
{ public static void main(String args[]) throws IOException
bl kn
}
catch(IOException ioe) InputStreamReader (System.in));
{ String str;
Te
ge
Output 2 entered the divisor as zero");
}
Enter two numbers:
finally
io led
4
{
a
System.out.println("In Finally Block");
Invalid number
}
ic ow
Output 3 }
n
Enter two numbers: }
bl kn
5 Output 1
2
at
The Quotient=2
4
The first output shows only divide by zero 0
Te
exception as the divisor entered was zero. Exception has occurred. You have entered the divisor as
The second output shows invalid number as zero
there was a number format exception In Finally Block
ge
{ import java.io.*;
int a,b,res; class Month
BufferedReader br = new BufferedReader {
io led
(new InputStreamReader (System.in)); public static void main(String args[]) throws IOException
String str; {
int m;
System.out.println("Enter two numbers:");
ic ow
res=a/b;
Pu ch
m=Integer.parseInt(str);
System.out.println("The Quotient=" + res); try
} {
Te
} if(m>12 || m<1)
throw new NumberFormatException();
Output 1
System.out.println("Month number entered is"+m);
Enter two numbers: }
3 catch(NumberFormatException ne)
4 {
The Quotient=0 System.out.println("Invalid month number");
}
Explanation
}
In this case we have simply indicated that the }
main() method throws an IOException.
Output 1
ge
Enter month number:
This can also be done by making a new 13
exception class say for example Invalid Month Number
io led
MonthNumberException. We will see this
Explanation
concept in the next program.
We have made our own class named as
ic ow
Program 5.6.2 : Write a program to accept and display the MonthNumberException. This class must
extend i.e. derived from the class Exception.
n
month number. Throw an exception if improper month
bl kn
import java.io.*;
Pu ch
5.7 Exception Handling in C++ The general syntax of the try catch block is as
(SPPU - May 17, May 19, Dec. 19) shown below :
try {
Q. Explain how the exception is handled in C++.
//statements that can cause exception;
(May 17, 3 Marks)
}
Q. How exception handling mechanism works in C++? catch(data_type arg)
(May 19, 7 Marks) {
Q. Explain need of exception handling. Explain it with //statements to be executed in case of the exception is
generated.
example. (Dec. 19, 6 Marks)
}
Exception handling refers to handling of catch(data_type arg)
abnormal or unexpected events. {
Some of these abnormal conditions are known //statements to be executed in case of the exception is
ge
to the compiler while some occur during run generated.
time and are unknown to the compiler.
io led }
catch(data_type arg)
‘Exception’ is a class and it has sub classes.
{
The different sub classes are the according to
//statements to be executed in case of the exception is
exceptions possible.
ic ow
generated.
Exception as discussed is an error condition }
n
occurrence. For example if a integer is As shown in the syntax, there can be multiple
bl kn
expected and a character is entered, then catch blocks associated with one try block.
while Thus using the exception handling i.e. the try-
at
Pu ch
If the exception does not occur, the try block is 5.8.2 Implementing User Defined Exception
completely executed and thereafter the control is
Q. Implement a user defined exception and explain the
transferred to the statements followed by the
same using program example.
catch block.
Let us see some program examples for the Program 5.8.2 : Write a program to accept password and
throw an exception if the password has less than 6
exception handling in C++.
characters or does not contain a digit.
ge
int i;
{
cout<<"Enter a password:";
try
gets(x);
{
io led
try
if(x>=0 && x<=9) throw x;
{
else throw "not a single digit number";
for(i=0;x[i]!='\0';i++)
ic ow
} {
catch(int i)
n
if(x[i]>='0' && x[i]<='9') throw "Incorrect
bl kn
{ password format";
cout<<"The number is single digit"; }
at
catch(char a[100]) }
{ catch(char a[100])
Te
cout<<a; {
cout<<a;
}
}
}
getch();
void main()
}
{
int p; Output
ge
{ 5.9 What are Generics?
for(i=0;x[i]!='\0';i++)
The generic function defines a set of statements
{
io led
that are common for the different types of data.
if(x[i]>='0' && x[i]<='9') throw "Incorrect
Hence instead of writing multiple functions for
password format";
various data types, we can use generic functions
ic ow
}
if the set of statements that are to be executed
if(i<=5) throw "Incorrect password format";
are same for all the data types.
n
}
bl kn
cout<<"Incorrect password format"; sort data will be same irrespective of the type of
cout<<"\nEnter password again:"; data. Hence this can be implemented by the use
Te
The class type can be any random class name Program 5.9.2 : Write a program to write a generic function
or template and demonstrate swapping of multiple types of
that will be used as a generic data type in the data using the same
function. This will be more clear in the #include<conio.h>
Program 5.9.1.
#include<iostream.h>
The main advantage of the generic function as template <class x> void swap(x &a, x &b)
discussed earlier is that instead of writing
{
multiple functions and increasing the code size,
x temp;
one can use templates and the task of writing
the program will also be simple for the temp=a;
programmer. a=b;
ge
Program 5.9.1 : Write a program to write a generic function
{
or template and demonstrate addition of multiple types of
data using the same. int a=4,b=5;
io led
#include<conio.h> float p=3.5,q=4.2;
cout<<"a="<<a<<"\tb="<<b<<" before calling
#include<iostream.h>
swap function"<<endl;
ic ow
{ swap(p,q);
cout<<add(3,5)<<endl; cout<<"p="<<p<<"\tq="<<q<<" after calling
Te
swap function"<<endl;
cout<<add(3.5,6.2)<<endl;
getch();
cout<<add(2.0,4.5)<<endl;
}
getch();
} Output
} }
void main() while(i<=size-2)
{ {
int p,q,r,s,t; array[i]=array[i+1];
float v,w,x,y,z; i++;
cout<<"Enter five integers:"; }
cin>>p>>q>>r>>s>>t; return(size-1);
cout<<"Average="<<avg(p,q,r,s,t)<<endl; }
cout<<"Enter five float numbers:"; template <class vector> void display(vector array[], int
cin>>v>>w>>x>>y>>z; size)
cout<<"Average="<<avg(v,w,x,y,z)<<endl;
{
getch();
int i;
}
ge
for(i=0;i<=size-1;i++)
Output
{
Enter five integers : 1
io led cout<<array[i]<<"\t";
2
}
3
cout<<endl;
ic ow
4
}
5
void main()
n
Average=3
bl kn
{
Enter five float numbers : 1.2
int m,n,i,a[100];
2.3
at
float b[100],x;
Pu ch
3.4
cout<<"Enter size of integer array:";
4.5
cin>>n;
Te
5.6
for(i=0;i<=n-1;i++)
Average=3.4
{
Program 5.9.4 : Write a program to create a vector class cout<<"Enter an integer:";
template to add, delete and display values from the vector.
cin>>a[i];
#include<conio.h>
}
#include<iostream.h> cout<<"1. Add an element\n2. Delete an element\n3.
template <class vector> int insert(vector data, vector Display\nEnter your choice:";
array[], int size)
cin>>i;
{
switch(i)
array[size]=data;
{
return(size+1);
case 1: cout<<"Enter element to insert:";
}
cin>>i;
template <class vector> int remove(vector data, vector
n=insert(i,a,n);
array[], int size)
cout<<"After insertion:\n";
{
display(a,n);
int i;
break;
for(i=0;i<=size-1;i++)
case 2: cout<<"Enter element to be deleted:";
{
cin>>i;
if(data==array[i]) break;
n=remove(i,a,n);
ge
3. Display
cin>>b[i];
Enter your choice : 2
}
io led Enter element to be deleted : 2.25
cout<<"1. Add an element\n2. Delete an element\n3. After deletion:
Display\nEnter your choice:"; 1.5 3.75
ic ow
cin>>i;
Program 5.9.5 : Write a C++ program using a class
switch(i)
template to read any parameterized data type such as float
n
{ and integer and print them in sorted form.
bl kn
m=insert(x,b,m);
template <class x> void sort(x a[], int n)
cout<<"After insertion:\n";
{
display(b,m);
Te
int i,j;
break;
x temp;
case 2: cout<<"Enter element to be deleted:";
for(i=0;i<=n-2;i++)
cin>>x;
{
m=remove(x,b,m);
for(j=0;j<=n-2;j++)
cout<<"After deletion:\n";
{
display(b,m);
if(a[j]>a[j+1])
break;
{
case 3: display(b,m);
temp=a[j];
break;
a[j]=a[j+1];
default:cout<<"Invalid choice\n";
a[j+1]=temp;
}
}
getch();
}
}
}
Output
ge
cout<<endl; template <class x> x add(x a, x b)
cout<<"Enter number of float numbers:"; {
cin>>m;
io led
return (a+b);
for(i=0;i<=m-1;i++)
{ }
cout<<"Enter a float number:"; char add(char x, char y)
ic ow
cin>>b[i]; {
}
n
return(x+y-64);
sort(b,m);
bl kn
cout<<"Sorted array:\n"; }
for(i=0;i<=m-1;i++) void main()
at
Pu ch
{ {
cout<<b[i]<<"\t"; cout<<add(3,5)<<endl;
}
Te
cout<<add(3.5,6.2)<<endl;
cout<<endl;
getch(); cout<<add('A','B')<<endl;
} getch();
}
Output
Output
Enter number of integers : 3
Enter an integer : 4 8
Enter an integer : 2 9.7
Enter an integer : 6 C
Program 5.9.7 : Write a program to write a generic function An example of such a generic class can be as
or template and demonstrate addition of multiple types of given below :
data using the same. Write overloaded template for showing template <class x> class Test
addition of char type data and integer type data.
{
#include<conio.h> x a,b,c;
#include<iostream.h> public:
template <class x> x add(x a, x b) void get_data();
{ void put_data();
return (a+b); void display();
} };
template <class x>x add(char a,x y)
5.9.5 Overview and Use of Standard
{
Template Library (STL)
return(a+y-64);
ge
} Q. List the use of Standard Template Library.
void main()
It is a collection of many libraries to help in C++
io led
{
programming. It consists of four major libraries :
cout<<add(3,5)<<endl;
1. Algorithms
cout<<add(3.5,6.2)<<endl;
ic ow
2. Containers
cout<<add('A',3)<<endl;
3. Functional or Functors
n
getch();
bl kn
} 4. Iterators
The algorithms section consists of a large
at
Output
Pu ch
5. Random access iterate : Used to access a It has almost the same methods as that of the
data from the array randomly, to be read or “List” interface.
written. The main difference is that the add() method
of class implementing “Set” interface has to
5.10 Introduction to Language Specific add the object only if its new and not a
Collection Interface : List Interface duplicate element, as it is making a set.
and Set Interface
5.11 Collection Classes : ArrayList Class
In Java, the collection interface defines many
and LinkedList Class
types of collection. It enables to work with group
of data or objects. Similar to the collection interfaces, Java also
has collection classes.
The interfaces “List”, “Set” and “SortedSet” are
extended from the interface “Collection”. Besides Some of the collection classes are
“AbstractCollection”, “AbstractList”,
these three, there are many other interfaces also
ge
“LinkedList”, “ArrayList”, etc.
extended from the interface “Collection”.
We will see the “ArrayList” and “LinkedList”
We will see the two interfaces in detail namely:
collection classes in the subsequent sub-
io led
the “List” and “Set” interfaces sections
5.10.1 List Interface 5.11.1 ArrayList Class
ic ow
If a collection cannot be modied, the exception problem is handled by ArrayList class objects.
named “UnsupportedOperationException” will
Thus the ArrayList can increase or decrease
Te
ge
a.add("K");
a.add("e"); a.add("n");
System.out.println("Size of ArrayList object after adding a.add("o");
io led
elements="+a.size()); a.add("w");
System.out.println("Contents of ArrayList object are: a.add("l");
ic ow
"+a); a.add("e");
} a.add("d");
n
} a.add("g");
bl kn
a.add("e");
Output
System.out.println("Contents of LinkedList object are:
at
Pu ch
ge
ArrayList<String> a=new ArrayList<String>();
Entire list is:
a.add("Jay");
Jay
a.add("Ajay");
io led
Ajay
a.add("Vijay");
Vijay
a.add("Sanjay");
Sanjay
ic ow
a.add("Sujay"); Sujay
String str=a.get(3);
n
bl kn
at
Pu ch
Te
Syllabus
File Handling : Introduction, Concepts of Stream, Stream Classes, Byte Stream Classes, Character Stream, Classes,
Using Stream, Other Useful I/O Classes, Using the File Class, Input/output Exceptions, Creation of Files, Reading/Writing
Character, Reading/Writing Bytes, Handling Primitive Data Types, Concatenating and Buffering Files, Random Access
ge
Files. Design Patterns : Introduction, Types of Design Patterns, Adapter, Singleton, Iterator.
io led
Each of the stream has an associated class that
6.1 File Handling : Introduction
contains various functions for dealing a
particular type of data.
ic ow
They are :
The file handling is mainly required to access
large data and also to store the data of one 1. Default constructor : This creates an object
Te
execution of a program to be used when the of the stream class which is not associated with
same is executed another time. any file.
In the following sections we will various streams 2. Initialization constructor : The first
available to access file in C++. argument passed is the file name with which
the object is to be associated. The second
6.2 Concepts of Stream parameter indicates the file open mode.
6.3.1 File Stream Classes The ios class is virtual class for the "istream"
(SPPU - May 19) and "ostream" i.e. input stream and output
Q. Explain the any two file stream classes needed for stream respectively. The "istream" is a class
the file manipulation. (4 Marks) derived from "ios" for input while "ostream" is
Q. What are stream extraction and stream insertion for output.
operators ? (4 Marks)
The class "iostream" has a multiple inheritance
Q. Which classes are used in file stream operations
explain it in details. (May 19, 6 Marks) i.e. it is derived from classes "istream" and
"ostream", hence used for both input as well as
The three classes for handling files are :
output.
Similarly the classes "ifstream" is for input from
files and "ofstream" is for output to files. The
"fstream" class is for both input and output.
ge
6.3.2 Advantages of Stream Classes
input files.
capabilities
2. ofstream : This class is used to handle output
n
The classes work as an abstraction for the user
files.
bl kn
and output stream to read a stream or sequence 6.4 Other Useful I/O Classes
of bytes and similarly write a stream i.e.
sequence of bytes. As seen in the Fig. 6.3.1, there are many classes
that are useful in I/O Stream handling.
The stream class has an hierarchy as shown in
the Fig. 6.3.2. Although the main classes used are “ifstream”
for reading from a file and “ofstream” for writing
on to a file, there are other useful IO classes
The base class is ios as seen in the Fig. 6.3.1.
The classes derieved from this class are
ifstream, ofstream, streambuf and other classes
like ostream, istream, filebuf, fstream and
fstreambase. Each of these I/O classes have
their own significance.
Fig. 6.3.2 : Stream class hierarchy Some of those are discussed here:
We have been using some of these in this book 1. filebuf : The main purpose of this class is to
with the help of the extraction (>>) and set the file buffers as input or output as
insertion (<<) operators i.e. with the "cin" and reqiored.
"cout" statements. These are derived from the
"ios" class.
2. fstreambase : It is mainly used to provide 6.6 Creation of Files and Using the File
the operations that are common to all the Class
classes, like opening and closing a file. (SPPU - Dec. 16)
3. ifstream : This class is used to read as Q. List file mode operation. (3 Marks)
discussed earlier and will also be seen in Q. Explain flags ios::binary and ios::ate. (4 Marks)
quite a lot detail in later sections
Q. Explain tellg and seekp functions. (4 Marks)
4. ofstream : This class is used to write on to
Q. Explain various file mode parameters in C++. Write
the file and will also be seen in detail in the
a program to copy the contents of a source file
subsequent sections
student1.txt to a destination file student 2.txt
5. fstream : It is mainly used to perform character by character. (7 Marks)
simultaneous read and write operations onto Q. Explain ios::app and ios::ate flags. (3 Marks)
a file. Hence it has functions to do both read
Q. Explain the functions used to read and write data in
as well as write operations.
ge
binary file. (4 Marks)
6.5 Input/Output Exceptions Q. Explain the following file mode ios::trunk, ios::app,
io led ios::ate, ios::binary. (Dec. 16, 4 Marks)
There are various cases wherein there can be
problems while accessing files, such as : Tellg and Seekp functions
ic ow
Using this function, the position of the get Returns the absolute position of the put pointer.
pointer is set to an offset value relative to some The put pointer determines the location in the
specific point determined by the parameter output sequence where the next output
direction. offset is of the member type off_type, operation is going to take place.
which is also an integer type. Syntax
And direction is of type seekdir, which is an pos_type tellp()
enumerated type (enum) that determines the
The tellp() function is used with output streams,
point from where offset is counted from.
and returns the current "put" position of the
3. seekp pointer in the stream. It has no parameters and
return a value of the member type pos_type,
The seekp method changes the location of a
which is an integer data type representing the
stream object's file pointer for output (put or
current position of the put stream pointer.
ge
write.) In most cases, seekp also changes the
To work with files as discussed in the earlier
location of a stream object's file pointer for
section we need to include the header file
io led
input (get or read.)
"fstream.h".
4. seekp (position) We need to first create an object of the stream
class before opening a file. This stream object
ic ow
file.
5. seekp (offset, direction)
The object of that class may be created based on
at
Sr. Mode Function Program 6.7.1 : Write a program to write and read a string
No. from/to a file.
ge
in out mode, it will be done by the following two ifstream i;
statements : i.open("test0",ios::out);
i>>msg;
ofstream o;
io led
cout<<msg<<endl;
o.open("test",ios::out);
i>>msg;
Another example to open a file "test" in input
cout<<msg<<endl;
ic ow
Output
For opening a file in input and output mode, the
HelloFriends!!
at
ifstream i; Bye!!
i.open("test",ios::in | ios::out);
Te
i>>roll; o<<msg;
i>>fee; }
cout<<"Name:"<<name<<endl; o.close();
cout<<"Roll No."<<roll<<endl;
in.close();
cout<<"Fee:"<<fee<<endl;
in.open("test123",ios::out);
getch();
while(!in.eof())
}
{
Output
in.get(msg);
Name:Ajay
cout<<msg;
Roll No.24
Fee:55988.449219 }
getch();
ge
6.7.1 Reading/Writing Bytes and Detecting
End of File }
Output
io led
To detect an end of file we have the function
this is a bench.
eof() that can be called by the ifstream class
object. This function returns a true of false Program 6.7.4 : Write a program that opens two text files
ic ow
based on the pointer pointing to the end of file or for reading data. It creates a third file that contains the text of
first file and then that of second file (text of second file to be
not respectively.
n
appended after text of the first file, to produce the third file).
Let us see a program example for the same.
bl kn
#include<iostream.h>
#include<fstream.h>
Program 6.7.3 : Write a program that reads a text file and
#include<conio.h>
at
Pu ch
char msg;
#include<conio.h>
int i;
#include<iostream.h> ofstream o;
#include<fstream.h> o.open("test11",ios::in);
void main() ifstream in;
in.open("test0",ios::out);
{
while(!in.eof())
clrscr(); {
char msg; in.get(msg);
o<<msg;
ofstream o;
}
o.open("test123",ios::in); o.close();
ifstream in; in.close();
in.open("test0",ios::out); o.open("test11",ios::app);
while(!in.eof()) in.open("test00",ios::out);
while(!in.eof())
{
{
in.get(msg); in.get(msg);
if(msg>='A' && msg<='Z') o<<msg;
msg=msg+'a'-'A'; }
ge
Data from concatenated file:
This is a bench. This is a car. cout<<i<<"-"<<j<<"="<<i-j;
}
io led
Program 6.7.5 : Write a program to copy the contents of a
source file student1.txt to a destination file student2.txt void main()
character by character.
{
#include<conio.h>
ic ow
clrscr();
#include<iostream.h>
n
#include<fstream.h> Fptr ptr;
bl kn
clrscr();
char msg; cout<<endl;
ofstream o; ptr=&subtract;
Te
o.open("student1.txt",ios::in); ptr(3,2);
ifstream in;
getch();
in.open("student2.txt",ios::out);
while(!in.eof()) }
{ Output
in.get(msg);
o<<msg; 1+2 = 3
} 3-2 = 1
o.close(); The function pointer ptr, initially points to the
in.close(); Add function and then to the subtract function.
in.open("student2.txt",ios::out); Accordingly the parameters are passed to those
while(!in.eof()) functions and the function is called and executed.
{
Sr. Manipulators ios member function
in.get(msg);
No.
cout<<msg;
} 1. Manipulators do not ios member functions
getch(); return value. can return value.
} 2. We can create our We cannot create our
own manipulators. own functions for ios.
ge
display employee details from file. Create a class 'employee'.
6.8 Handling Primitive Data Types and
Random Access Files #include<iostream.h>
#include<fstream.h>
io led
Q. Explain the use of binary files in C++ with a #include<conio.h>
program. (7 Marks) #include<stdio.h>
class employee
ic ow
void accept()
Pu ch
} Output
}; !00002
void main() reganaM
{ yajA
employee e;
e.accept(); 6.9 Concatenating and Buffering Files
e.display();
In some cases, we need to access multiple files.
getch();
The files may need to be concatenated or
}
separated for doing certain operations.
Output
We will see some program exampled in case
Enter name, designation and net pay:Ajay where we will use multiple files by buffering
Manager them or concatenating them
ge
20000
Program 6.9.1 : Write a C++ program to read character
Ajay
data from a file. Create one file to store all capital alphabets
Manager
io led and another file to store all small case alphabets. Also
20000 display contents of both files.
#include<iostream.h>
ic ow
#include<fstream.h>
{
#include<conio.h>
at
char msg;
Pu ch
void main()
{ int i;
cout<<msg<<"\t"; in.close();
} o.close();
cout<<"\n\n\nReading from file 2:"<<endl; in.open("test0",ios::out);
in.close(); cout<<"\n\n\nReading from concatenated file "<<endl;
in.open("test01",ios::out); for(i=1;i<=52;i++)
for(i=1;i<=26;i++) {
{ in>>msg;
in>>msg; cout<<msg<<"\t";
cout<<msg<<"\t"; }
} in.close();;
in.close();; getch();
getch(); }
ge
} Output :
Output : Reading from concatenated file
io led
Reading from file 1: A B C D E F GH I J
A B C D E F G H I J K K L M N O PQR S T
L M N O P Q R S T U V UV W X Y Z a b c d
ic ow
W X Y Z e f g h I j k l m n
Reading from file 2: o p q r s t u v wx
n
y z
bl kn
a b cd e f g h i j k
l m n o p q r s t u v Program 6.9.3 : A file "student.txt" contains roll numbers
at
w xy z
Pu ch
in.open("test02",ios::out); }
do in.close();
{ getch();
in>>roll; }
in>>name; Output
}while(search!=roll); Ajay 12345
cout<<"roll number "<<search<<" is of student with Jay 01267
name "<<name;
getch(); 6.10 Design Patterns : Introduction
}
There are various design patterns used in the
Output
making of softwares. The design pattern to be
24 Ajay used depends on the case.
ge
16 Jay
Design patterns are basically used to give the
48 Vijay
method for designing the software or application
64 Digvijay
io led
based on the class diagram.
Enter roll number of student to search:16
roll number 16 is of student with name Jay We need to decide the best design pattern that is
ic ow
John 23406
Ahmed 56789 patterns may be required at different parts in
at
our software.
Pu ch
For example, if we have an existing class “A” in The user therefor need not bother about the
a particular application, but it doesn’t have a various classes or interfaces. Instead the user
required interface “B”; then we will make class “D” needs to extend only the Iterator class
another class called as adaptor class “C” that is “C”
extended from the class “A” and implements the
interface “B”
This can be as shown in the Fig. 6.11.1.
ge
io led 6.12 Student Management System
Fig. 6.11.1 :Adaptor Storing the information of students is a very
6.11.2 Singleton important requirement in colleges.
Information like name, fee, exam marks etc
ic ow
some of these .
Hence in this case, the client or the user made
import java.util.*;
at
class Department
be obtained by some method like getInstance().
{
The field members of the instance or object may
Te
ge
sortStudents();
active=1;
System.out.println("Student added, press 7 to know roll
}
numbers");
io led public int checkIfActivatedJustNow(int x)
}
{
public void sortStudents()
if(active==0) return (x+1);
{
else return x;
ic ow
int i,j;
}
for(i=0;i<=student_count-2;i++)
n
public boolean searchStudentByName(String str)
{
bl kn
{
for(j=i;j<=student_count-2;j++)
int i;
{
at
flag=-1;
Pu ch
if(student[j].compareTo(student[j+1])>0)
for(i=0;i<=student_count-1;i++)
{
{
temp=student[j];
Te
if(str.equalsIgnoreCase(student[i])) flag=i;
student[j]=student[j+1];
}
student[j+1]=temp;
if(flag!=-1) return true;
}
else return false;
}
}
}
public int getStudentNumber()
}
{
public int returnDeptNunber()
return flag;
{
}
return dept_number;
public void removeStudent(int x)
}
{
public boolean activity()
int i;
{
showStudentInfo(x);
if(active==0) return false;
for(i=x;i<=student_count-2;i++)
else return true;
{
}
student[i]=student[i+1];
public boolean searchDepartmentByName(String str)
}
{
student_count--;
if(str.equalsIgnoreCase(dept_name)) return true;
System.out.println("Removed");
else return false; }
} public boolean checkVacancy()
ge
{
{
System.out.println((code_number+i+1)+"\t"+student[i]);
System.out.println("Enter branch name");
}
io led test_string=sc.nextLine();
}
test_string=test_string.toUpperCase();
public void updateIntake()
for(i=0;i<=count-1;i++)
{
ic ow
{
int copy=intake;
if(d[i].searchDepartmentByName(test_string))
System.out.println("Present Intake = "+intake);
n
{
Scanner sc = new Scanner(System.in);
bl kn
copy=1;
do
data=i;
{
at
Pu ch
break;
System.out.print("Enter new intake(must be greater than or
equal to old) : "); }
intake=sc.nextInt(); }
Te
}while(intake<copy); if(count>0&©==0&&choice>1)
System.out.println("Branch not found");
}
}
public int getRollNumber(int x)
switch(choice)
{
{
return (code_number+x+1);
case 1: if(copy==0)
}
{
public boolean numberExists(int x)
d[count]=new
{
Department(count+1,test_string);
if(x%1000<student_count) return true;
count++;
else return false;
dept_count++;
}
}
}
else
public class College
{
{
dept_count=d[data].checkIfActivatedJustNow
public static void main(String args[]) (dept_count);
{ d[data].restartDepartment();
int count = 0, dept_count = 0, dummy_count, choice, i, j, }
copy, data = 0;
break;
String test_string="";
case 2: if(dept_count==0) System. out. Println ("Add a
Department d[] = new Department[100]; branch first");
ge
d[data].addStudent(); {
}
else dummy_count=d[i].getRollNumber(d[i].getStudentNumber());
io led
System.out.println("Branch isn't accepting more students"); break;
} }
break; }
ic ow
case 4: if(dept_count==0)
{ if(dummy_count/100000!=20||!d[((dummy_count-
n
System.out.println("Add a branch first"); 2000000)/1000)-1].numberExists(dummy_count-1))
bl kn
d[((dummy_count-2000000)/1000)-
Pu ch
case 6: if(dept_count==0)
test_string=sc.nextLine();
{
if(test_string.charAt(0)=='2')
dummy_count=Integer.parseInt(test_string); System.out.println("Add a branch first");
for(i=0;i<=count-1;i++) break;
{ }
if(d[i].searchStudentByName(test_string)) else if(copy!=0) d[data].updateIntake();
{ break;
case 7: if(dept_count==0)
dummy_count=d[i].getRollNumber(d[i].getStudentNumber()); {
break; System.out.println("Add a branch first");
} break;
} }
else if(copy!=0) d[data].showAllStudents();
if(dummy_count/100000!=20||!d[((dummy_count- break;
2000000)/1000)-1].numberExists(dummy_count-1)) }
System.out.println("Invalid name OR number"); }while(choice!=8);
else }
d[((dummy_count-2000000)/1000)- }
1].removeStudent(dummy_count%1000-1);
break;
ge
4) Make suitable assumptions, if necessary.
io led
Q. 1 (a) What is constructor? List different types of constructors and write program example for any one.
(b) Explain destructor with a program example. (Refer Section 3.6) (6 Marks)
n
bl kn
(c) Write an object oriented program in Java that uses Euclid’s Algorithm to display the greatest common divisor of
two integers. The parameterized constructor is to be used to initialize the two numbers. Two methods to
at
Pu ch
OR
Te
Q. 2 (a) Explain copy constructor with a program example. (Refer Section 3.2.3) (6 Marks)
(b) Write a program to calculate the area of triangle, rectangle and circle using constructor overloading. The
program should be menu-driven. (Refer Program 3.3.1) (6 Marks)
(c) Write a program to find area of circle using C++. The value of the radius must be accepted from the user in the
main program and passed to the parameterized constructor and the class circle must have two inline functions
namely : (a) compute() for calculating the area. (b) display() for displaying the result.
Q. 3 (a) List the different types of Inheritance in C++ and Write a program to add two numbers using single inheritance
such that the base class function must accept the two numbers from the user and the derived class function
must add these numbers and display the sum. (Refer Section 4.1.1(A) and Program 4.2.1) (6 Marks)
(b) Write a program to calculate percentage of a student using multi level inheritance. The base class function will
accept the marks in three subjects from user. A class will be derived from the above mentioned class that will
have a function to find the total marks obtained and another class derived from this will have functions to
calculate and display the percentage scored.(Refer Program 4.2.6) (6 Marks)
(c) Differentiate between Interface and Abstract class. (Refer Section 4.5.2(C)) (5 Marks)
OR
Q. 4 (a) Write a program to implement single inheritance from following Fig. P. 4.2.3 accept and display the data for one
table. (Refer Program 4.2.3) (6 Marks)
ge
(b) Differentiate between multiple inheritance and multilevel inheritance. (Refer Section 4.2.2) (5 Marks)
(c) List rules of virtual function. Write a program to demonstrate dynamic binding using virtual function.
io led
(Refer Section 4.7.2 and Program 4.7.2) (6 Marks)
Q. 5 (a) Explain the concept of checked and unchecked exceptions with examples.
ic ow
(b) Write a C++ program to demonstrate the use of try catch block with the arguments as an integer and a string
n
using multiple catch blocks. (Refer Program 5.8.1) (6 Marks)
bl kn
(c) Explain LinkedList class with a program example. (Refer Section 5.11.2) (6 Marks)
at
Pu ch
OR
Q. 6 (a) Explain the syntax of try-catch-finally in detail. (Refer Section 5.3) (6 Marks)
Te
(b) Write a Java program to perform division of two numbers accepted from user. Handle the IO Exception, Number
format exception and also handle the divide by zero exception using multiple try catch block (Program 5.4.2)(6
Marks)
(c) What are generics? Write a C++ program using a class template to read any parameterized data type such as
float and integer and print them in sorted form. (Refer Section 5.9 and Program 5.9.5) (6 Marks)
Q. 7 (a) Which classes are used in file stream operations explain it in details. (Refer Section 6.3.1) (6 Marks)
(b) Write a program to store employee names with their designation and net pay to a file on console. Also display
employee details from file. Create a class 'employee'. (Refer Program 6.8.2) (6 Marks)
(c) Explain the following file mode ios::trunk, ios::app, ios::ate, ios::binary. (Refer Section 6.6) (5 Marks)
OR
Q. 8 (a) List and explain the IO Exceptions. (Refer Section 6.5) (6 Marks)
(b) Explain the design patterns: Adaptor, Singleton and Iterator (Refer Sections 6.10 and 6.11) (6 Marks)
(c) Write a program to write and read a string from/to a file. (Refer Program 6.7.1) (5 Marks)