Sie sind auf Seite 1von 89

WWW.VIDYARTHIPLUS.

COM
CS2311 OBJECT ORIENTED PROGRAMMING
UNIT-I
Problem solving approaches:
There are two problem solving approaches:
i) Procedural programming
ii) Object Oriented Programming
Difference between procedural & Object Oriented Programming:
UQ: Difference procedure oriented and object oriented programming.

PROCEDURE ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING


 It executes series of procedures  It is a collection of object.
sequentially.
 This is top-down approach.  This is bottom up approach.
 Major focus on procedures.  Major Focus on objects.
 Data Reusability is not possible.  Data reusability is one of the features.
 Data hiding is not possible.  Data hiding can be done by making it private.
 It is simple to implement.  It is complex to implement
Example: Example:
C,FORTRAN,COBOL C++,JAVA
OBJECT ORIENTED PROGRAMMING CONCEPT:
UQ: Explain the elements of object oriented programming. (M/J’12-10M, A/M’11-4M)
 Object Oriented Programming concept also called as characteristics of oops (or) Elements of oops (or) basic
concept of oops.
 Various Characteristics of OOPS Languages are:
1. Object
2. Class UNIT I
3. Data Abstraction Object oriented programming
4. Data Encapsulation concepts – objects-classes- methods and
5. Inheritance messages-abstraction and encapsulation-
6. Polymorphism inheritance- abstract classes-
7. Dynamic Binding polymorphism. Introduction to C++-
8. Message Passing objects-classes constructors and
1. Object: destructors
 Object is an instance of class.
 Object is a runtime (or) real world entity.
 It represents a person, place or any item that a program handles.
 In C++ the class variables are called Objects.
 Using Objects we can access the member variables (Attributes) & member function (procedures).
 A Single class can create any number of objects.
Example:
Cycle Student

Make Move() Name Total()


Frame size Repair() Roll no Avg()
Wheel size Assemble() DOB Display()
Material Marks

Member Variables Member Functions


SYNTAX:
Object creation
Classname Objectname1, Objectname2….
Member Function Access
Objectname1.function_name( );
Example:
Student S1,S2;

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
S1.total( );

2) Class:
 A class is an entity in which data and function are put together.
 It is also collection of objects.
 Member function are defined in two ways:
i. Inside of the class
ii. Outside of the class
 “Scope Resolution Operator (::)” used to define the function in outside of class.
 Access Specifier is a main role in class.
 Access Specifier is specifying the access method of data (or) Functions.
 Access Specifier Classified into 3 types:
i. private - Access with in class
ii. protected-Access with in class & inherited class
iii. public-Anywhere access
 In definition of class must put a semicolon (;) at the end.
 “class” is the keyword used to define the class.
SYNTAX:
INSIDE OF CLASS OUTSIDE OF CLASS
Class class_name Class class_name
{ {
Access_Specifier: Access_Specifier:
Variable declarations; Variable declarations;
___ ___
___ ___ Access_Specifier:
Access_Specifier: function declarations;
Function definitions; ___
__ ___
__ };
}; return_type class_name::function_name()
{
------------------------
-------------------------
}
Example:
//Inside of the class: OUTPUT:
class rectangle Enter the Length & Breath:10
{ 20
private: Area = 200
int len,br,area; Enter the Length & Breath:10
public: 40
void get_data() Area = 400
{
cout<<”enter the length & breadth:”;//Output Statement
cin>>len>>br;//Input Statement
area=len*br;
cout<<”area=”<<area;
}
};
void main()
{ OUTPUT:
rectangle r1,r2,r3; Enter the Length & Breath:10
r1.get_data(); 20
r2.get_data(); Area = 200
} Enter the Length & Breath:10
//Outside of the class: 40
class rectangle Area = 400
{

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
private:
int len,br,area;
public:
void get_data();
};
void rectangle::get_data()//Scope resolution operator
{
cout<<”enter the length & breadth:”;//Output Statement
cin>>len>>br;//Input Statement
area=len*br;
cout<<”area=”<<area;
}
void main()
{
rectangle r1,r2,r3;
r1.get_data();
r2.get_data();
}
3. Data Abstraction:
 Data Abstraction means representing only essential features without including background (or)
Implementation details.
 In C++, Class is an entity used for data abstraction purpose.
 Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).
Example:
class student
{
int roll;
char name[10];
public:
void input();
void display();
}
 In the main function we can access the functions of class using object.
student obj;
obj.input();
obj.display();
4. Data Encapsulation:
 They wrapping up of data and function into a Single Unit (class) is known as encapsulation.
 The data is not accessible to the outside world.
 These functions provide the interface between the objects data & Program.
 Data Encapsulation is also called as “Data Hiding” (or) “Information Hiding”.
Example:
Other Object
Own Object
Data
5. Inheritance:
 Inheritance is the Process by which Objects of one class acquire (join) the Properties of objects of
another class.
 It is a process of deriving new classes from existing class.
 It supports the concept of Hierarchical classification.
 Exiting class - Baseclass (or) Superclass
 Derivedclass - New class (or) Subclass
 The concept of inheritance provides “reusability”.
 We can add additional features to an existing class without modifying it.
Type of Inheritances:
i. Single Inheritance
ii. Multiple Inheritances
iii. Multilevel Inheritance
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
iv. Hierarchical inheritance
v. Hybrid (or) Multipath Inheritance
A
i) Single Inheritance:
One base class, one derived class.
B
A B
ii) Multiple Inheritance: A
Two base class, one derived class.

iii) Multilevel Inheritance: C


B
One base class, one intermediate class, one derived class.
A
iv) Hierarchical Inheritance:
One base class, more than one derived class. C

v) Hybrid (or) Multipath Inheritance:


More than one inheritance combined together. B C

Hierarchical
Inheritance
B C
Multiple
Inheritance

D
6. Polymorphism:
 Polymorphism is a Greek term; it means the ability to take more than one form.
 Poly => Many
 Morphs =>Forms.
 An Operation may exhibit (display or Show) different behaviors on the types of data used in the
Operation.
 Polymorphism divide into two types:
i. Compile Time Polymorphism
ii. Runtime Polymorphism
i) Compile-time Polymorphism:
 It can be execute the code in compile time.
 It’s divide into two types
1. Operator Overloading
2. Function Overloading
1. Operation Overloading:
 The Process of making an Operator to exhibit different behaviors in different instance is known as
Operator Overloading.
 Operation of addition
For two numbers, the Operation will generate a “Sum”.
For two strings, the Operation will produce a third String by “Concatenation”.
2. Function Overloading:
 Using a Single Function name to perform Different types of tasks is known as function overloading.
 A Single function can be used to handle different number & different types of arguments.
 A Particular word having several meanings depending on the context.
 Polymorphism plays an important role in allowing objects having different internal
structures.
Example:

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM

7. Dynamic Binding:
 Binding refers to the linking of a Procedure (or) function call to the code to be executed in response to
the call (function definition).
 Two types of binding
i. Static Binding
ii. Dynamic Binding
1) Static Binding:
 In Static binding which function is to be called for object is determined at “Compile time”.
2) Dynamic Binding:
 Dynamic Binding means that the code associated with a given procedure (or) function call at “run
time”.
 It is associated with Polymorphism & Inheritance.
 It is also called “Late Binding”.
Example:
fun(a,b);//Function Calling

void fun(int x,int y)//Function Definition


{
__
__
}
Binding
8. Message Passing:
 An object Oriented Program consists of a set of objects that communicate each other.
 Process of sending message through objects is called message passing.
 Message Passing involves the following steps:
1. Creating Classes
2. Creating Objects from class definitions
3. Establishing communicate with One another by Sending & receiving information.
Syntax:
Object_name.function_name(arguments);
Example: Circle.draw(10);
 A Message for an object is a request for execution of a procedure and receiving object that generates
the desired result.
 Sending information through arguments of function.
Methods & Messages
Messages:
 A function calling with help of object is called message.
 This message can send & receive the information through objects.
 Information is called as arguments.
Example:
Obj.fun();
Methods:
 A function can return any information (response) to message is called method.
Types:
i. With response
ii. Without response
 Above two types of methods can divide with their responses.
1) With Response:
 Information can send & receive through messages.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
2) Without responses:
Information can send only through messages.
Applications of oops:
 Applications of oops are beginning to gaining importance in many areas:
1) Real-time systems.
2) Simulation & modeling
3) Object Oriented Databases.
4) Artificial Intelligence (AI) & Expert Systems.
5) Neural networks & Parallel Programming.
6) Decision Support Systems.
7) Office Automation Systems.
Introduction to C++:
Language Developed by Year
C Tennis Riche 1976
C++ Bjarne Stroustroup 1980
JAVA James Gosling 1991
 C++ is a One of the advanced language of ‘C’.
Difference between C and C++:
S.No. C C++
1. C is a Procedure Oriented Language. C++ is an Object Oriented Program Language.
2. It use top down approach of problem solving. It uses bottom-up approach of problem solving.
Input & Output is done using scanf & printf The input & Output is done by using “cin” and
3.
functions. “cout”.
I\O Operations are supported by “iostream.h” header
4. I\O Operations are supported by stdio.h header files.
file.
Control strings are used (%D, %C, %s) for getting Control strings are no need for getting input &
5.
input & printing Output. printing output.
C does not support inheritance, polymorphism, class C++ supports inheritance polymorphism, Virtual
6.
& objects. functions, classes & object concepts.
Structure of C++:
// title of the Program
Include file section
Preprocessor Section
Global variable section
Class declaration
Member function definition
Main function section

Simple C++ program:


1) Open Commend prompt & type of the following instructions:
>cd\
>cd TC
>Cd bin
>TC
2) Now new editor window will be open.
3) Type the Program & Save as “filename.cpp” that means C plus plus.
4) Compiling C++ Program using “Ctrl +F9” Short cut key.

Example:
// A simple Program
#include<iostream.h>
void main()
OUTPUT:
WWW.VIDYARTHIPLUS.COM Hello World V+ TEAM
WWW.VIDYARTHIPLUS.COM
{
cout<<”Hello World”;
}
Tokens:
 The smallest individual units in a program are known as tokens.
 C++ has the following tokens:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators
 A C++ Program is writing using these tokens, white spaces and the syntax of the language.

1) Keywords:
 The keywords are known as “Reserved words”.
 So these words cannot be used for other Purposes.
 All keywords are “Lower case”.
 Keywords are “Predefined Identifiers”.
 The Keywords Supported by “C language” and also available in C++. (32 Keywords)
1. auto 9. double 17. int 25. struct
2. break 10. else 18. long 26. switch
3. case 11. enum 19. register 27. typedef
4. char 12. extern 20. return 28. union
5. const 13. float 21. short 29. unsigned
6. continue 14. for 22. signed 30. void
7. default 15. goto 23. sizeof 31. volatile
8. do 16. if 24. static 32. while
 The following keywords are “Only supported in C++” (16 keywords)
1. asm 5. friend 9. private 13. this
2. catch 6. inline 10. protected 14. throw
3. class 7. new 11. public 15. try
4. delete 8. operator 12. template 16. virtual
2) Identifiers:
 Identifiers are used to give names to variables, functions, arrays, classes, etc..,
 They are the fundamental requirement of any language.
 Identifier used to identify something.
 Identifier has the following RULES:
1) Only alphabetic characters, digits & Underscores are permitted.
2) The name cannot start with a digit.
3) Identifiers are “case sensitive” i.e. lower vase (or) Upper case.
4) Keywords are not allowed.
5) The maximum number of characters used in forming an identifier=32 char.
Variables:
 A Variables is an entity whose value “can be changed” during Program execution.
 Variable names are identifiers used to name variables.
3) Constants:
 A Constant does not change its value during the entire execution of the program.
 They can Classified as
i. Integer constant
ii. Character constant
iii. Floating Point constant
iv. Enumeration constant
4) Strings:
 Group of (or) Set of Characters, digits and Symbols are enclosed with in double quotation marks are called
string.
Example:
“Apple”, “7sent”, “a+b”, ”a+92t>”…
String handling functions:
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 The C++ library has a large number of string handling functions.
 The most commonly used string handling functions.
1) strcat() - concatenates (join) two strings
2) strcmp() - compares two strings.
3) strcpy() - copies one string over another.
4) strlen() - finds the length of a string.
5) strupr() – convert strings into upper case
6) strlwr() - convert strings into lower case.
5) Operators:
 An Operator is a symbol that specifier an Operator to be Performed on the Operands.
 Some Operators require two Operands called “Binary Operators”.
 Some Operators require only one Operand called “Unary Operators”.

Types of operators:
C & C++ Provides following Operators:
1) Arithmetic Operator (+, -,*,/,%,)
2) Relational Operator (<,>,<=,>=,!=,==)
3) Logical Operators (&&.||,!)
4) Assignment Operator ( = )
5) Increment & decrement Operator (++,--)
6) Conditional (or) Ternary Operator (? , : )
7) Bitwise Operator (&,!,|,^)
8) Special Operator (, sizeof,&&*, .&->)
 Arithmetic Operators has Operators Precedence “BODMAS”  “B”racket “O”f “D”ivision
“M”ultiplication “A”ddition “S”ubtraction.
 Some other Operators in C++:
1) Scope Resolution Operator ( :: )
2) Pointer to member declaratory ( :: , * )
3) Pointer to member Operator (->, *, &, >* )
4) delete – Memory release Operator
5) new – Memory allocation Operator
6) endl – Line feed Operator
7) setw – field width Operator
Scope Resolution Operator ( :: )
 C,C++ is also a block Structured language.
 Blocks & Scope can be used in Constructing Programs.
Datatypes:
 Datatypes specify the size and type of values that can be stored.
 The variety of data types available allow the programmer to select the type appropriate to needs of the
application.
Types of Datatypes:
1. Built-in-type
2. User-defined type.
3. Derived type
1. Built-in-type:
 Both C and C++ compilers support all the built-in(also known as basic or fundamental) datatypes.
 Except void, the basic datatypes may have several modifiers preceding them to serve the needs of
various situations.
 The modifiers signed, unsigned, long and short may be applied to character and integer.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM

void datatype:
 Uses of void datatype:
1. To specify the return type of a function when it is not return any value.
2. To indicate an empty argument list to a function.
3. The declaration of generic pointers.
Example:
void function(void);//return type and argument list
void *gp;//Generic pointer
int *ip; gp=ip;
2. User-defined datatype:
 User can define the type of data.
 It is divided into following types:
1. Structure
2. Union
3. Enumeration
4. Class
1. Structure:
 Structures are used for grouping together elements with dissimilar types.
Syntax:
struct structure_name
{
datatype member1;
datatype member2;
….
};

Example:
struct book
{
char title[25];
char author[25];
int pages;
float price;
};
struct book book1,book2,book3;
2. Union:
 Union also used for grouping together elements with dissimilar types.
 But the differences the size of union is equal to the size of largest member element.
 Structures and union are same in declaration.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
3. Enumerated datatype:
 It provides a way for attaching names to numbers, thereby increasing at length
(comprehensively) of the code.
 The enum keyword automatically enumerates a list of words by assigning them values 0,1,2
and so on.
Syntax:
enum enum_name{Item1,Item2,…..};
Example:
enum shape{circle, square, triangle};
4. Class:
Refer the page No.1
3. Derived Datatype:
 Derived datatype is deriving the data from the existing.
 It is divided into following types:
a. Array
b. Function
c. Pointer
Control structures:
1. Sequence structure (straight line)
2. Selection structure (branching)
i) if – else (two way branch)
ii) switch (multiple branch)
3. Loop structure (iteration or repetition)
i) do – while (exit controlled)
ii) while (entry controlled)
iii) for (entry controlled)
Default Arguments:
 C++ allows calling a function without specifying all its arguments.
 In such cases the function assigns a default value to the parameters which does not have a matching
argument.
 Must add defaults from right to left.
 Cannot provide a default value in the middle of an argument list.

Valid:
int mul(int i=2,int j=5,int k=10)
int mul (int i,int j=5,int k=10)
In valid:
int mul(int i=5,int j)
int mul(int i=5,int j,int k=10)

Function overloading:
 More than one function definition for same function name.
 It can be different from parameter passing with particular datatypes.
Example:
//Function Overloading and Default Argument
#include<iostream.h>
#include<conio.h>
class volume
{
int l,b,h,a1,b1,c1;
int vol1,vol2,vol3; OUTPUT:
public: Enter the value of l,b,h:4
void get() 5
{ 6
cout<<"Enter the value of l,b,h:";
The volumes are:
cin>>l>>b>>h;
Vol1=120
vol1=l*b*h;
} Vol2=210
Vol3=60
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
void get(int x,int y,int z)
{
l=x;b=y;h=z;
vol2=l*b*h;
}
void get(int x,int y=12)//Default Argument
{
a1=x;b1=y;
vol3=a1*b1;
}
void display()
{
cout<<"The volumes are:";
cout<<"\nVol1="<<vol1<<"\nVol2="<<vol2<<"\nVol3="<<vol3;
}
};
void main()
{
clrscr();
volume v;
v.get();
v.get(5,6,7);
v.get(5);
v.display();
getch();
}

Inline Function:
 To eliminate the cost of calls to small function the C++ Provides inline function.
 It execute faster.
 Some of the situations inline function may not work:
1) Returning values if a loop, a switch or goto.
2) Not return values, if a return statement exits.
3) If contain static variables.
4) If inline functions are recursive.
Syntax:
inline return_type function_name (argument)
{
=======================
}
Example:
inline int sqr(int x)
{
return(x*x*x);
}
void main()
{
cout<<sqr(4);
getch();
}
Pointers:
 It is a Derived Datatype.
 It can be used to access and manipulate data stored in the memory.
 Ordinary Variable:
int a=5;
aaccess the value
&a access the address of variable.
a variable
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
5 value
4002 address
Constructors:
 Objects need to initialize the variables. If the variables are not initialized then they hold some
“garbage value”.
 To avoid that above problem use the special member function is called constructor.
 The constructor can be called automatically whenever a new object is created.
 The constructor name as the class name.
 It should not have return type.
Properties (or) Characteristics (or) Rules for constructor:
1) The constructor name must be as class name.
2) It can call automatically when object is created.
3) It must be declared with “public” access specifier.
4) It cannot return any value.
5) Constructors cannot be virtual.
Types of Constructors:
1) Default constructor
2) Parameterized constructor
3) Constructor with dynamic allocation
4) Copy constructor
5) Default argument constructor
6) Destructor

1) Default constructor:
 Default constructor is the basic constructor.
 It is non parameterized constructor.
 It just initializes the variables.

Syntax:
class classname
{
public:
classname()
{
__
__
}
};
2) Parameterized constructor:
 Passing arguments (or) parameters to the constructor function when the object is created.
 The constructors that can take arguments (or) parameters are called “Parameterized
constructor”.
 We can call the Parameterized constructor using two ways:
i. Implicit calling
ii. Explicit calling
Syntax:
i) Implicit calling:
classname objectname(args);
ii) Explicit calling:
classname objectname=classname(args);

3) Constructor with dynamic allocation:


 The constructor can also be used to allocate memory while creating objects.
 The amount of memory for each object varying one. So that memory allocate for the each object to
saving of memory.
 Allocation of memory to objects at the time of their construction is known as dynamic memory allocation
(or) dynamic constructors.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 The memory is allocated with the help of “new” operator.
Syntax: variablename = new datatype[length];
4) Copy constructor:
 Copy constructor is used to declare and initialize an object from another object.
 The process of initializing through a Copy constructor is known “copy initialization”
 Send object as parameter.
Syntax:
classname object1;
classname object2(object1);//Implicit passing
classname object3=object2;//Explicit passing
5) Default argument constructor
 Give the initial values to inside the argument list of constructor.
 If any value is missing this will be taken from the argument list values in definition of
constructor.
Syntax:
constructorname(datatype variable=value, ….)
{
___
___
}
6) Destructors:
 Destructor is used to destroy the objects that have been created by a constructor.
 Like a constructor the destructor is a member function whose name is the class name but is
preceded by “tilde (~)” symbol.
Syntax:
~destructorname()
{
___
___
}
Example:
//Example for Multiple constructor or Constructor overloading & Destructor
#include<iostream.h>
#include<conio.h>
#include<string.h>
class stu
{
int m1,m2,m3,total;
float avg;
long int regno;
char *name,dept[10];
public:
stu()//Default Constructor
{
m1=m2=m3=total=0;
}
stu(int n1,int n2,int n3,long int regno1,char *name1,char *dept1="EEE")//Default argument, Parameterized
constructor
{
int length;
m1=n1;m2=n2;m3=n3;
regno=regno1;
strcpy(dept,dept1);
length=strlen(name1);
name=new char(length+1);//Dynamic allocation constructor
strcpy(name,name1);
total=m1+m2+m3;
avg=total/3.0;

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
}
stu(stu &o1)//Copy constructor
{
cout<<o1.name<<"\t"<<o1.regno<<"\t"<<o1.dept<<"\t"<<o1.m1<<"\t"<<o1.m2<<"\t"<<o1.m3<<"\t"<<o1.total<<"\t
"<<o1.avg<<endl;
}
~stu()//Destructor OUTPUT:
{
} Name Regno Dept Mark1 Mark2 Mark3 Total Average
};
void main() senthil 656566 EEE 45 56 35 136 45.333332
{
clrscr(); kumar 756566 IT 55 76 95 226 75.333336
stu s1;
cout<<"\nName\tRegno\tDept\tMark1\tMark2\tMark3\tTotal\tAverage"<<endl;
stu s2(45,56,35,656566,"senthil");
stu s3=s2;
stu s4(55,76,95,756566,"kumar","IT");
stu s5=s4;
getch();
}

University Questions:
PART-A
1. Difference procedure oriented programming and object oriented programming.(N/D’11,M/J’12)
2. Write the significance of void datatype. (N/D’11)
3. What is an inline function? (N/D’11
4. What is a copy constructor? (N/D’11,M/J’12, A/M’11)
5. What is mean by dynamic constructor? (N/D’10)
6. Differentiate Object based programming languages and Object Oriented programming languages.(N/D’12)
7. Write any four string manipulation functions. (N/D’12
8. Define inline function with example. What are the restrictions for writing inline function? (N/D’12,10
9. What do you mean by constructor? List out the important characteristics of constructor. (N/D’12, A/M’11
10. What is Object Oriented paradigm? (M/J’12
11. How are data and functions organized in an object oriented programming? (M/J’12
12. What are the datatypes in C++? (A/M’11
13. Define an array. (A/M’11
14. List out the types of operators. What are the operators that are specific only to C++. (A/M’11, N/D’10
15. How will you define a string? (A/M’11
16. Define a Class and object. (A/M’11
17. Write any five differences between C and C++. (M/J’13
18. What do you mean by dynamic utilization of variable? (M/J’13
19. What is the significance of empty paranthesis in a function declaration? (M/J’13
20. What is mean by data hiding in OOP? (N/D’10
21. List the various unconditional branching statements. (N/D’10
22. Give the applications of OOP. (N/D’10
23. What is the use of ‘this’ pointer in C++? (N/D’10
24. Compare overloading and overriding. (N/D’10
25. What will happen to an object if a destructor is not coded in the program? (N/D’10

PART-B
1. Explain the various datatypes available in c++.(N/D’11-10,N/D’12-8, M/J’13-8)
2. Explain the concept of pointers in detail.(N/D’11-8M, M/J’13-8M,
3. Write the program to find number is ODD or EVEN.(N/D’11-8M
4. Explain how objects can be passed and returned from a function with an example.(N/D’11-8M
5. Explain in detail the concept of constructor overloading (or) multiple constructors. Explain the different
types of constructors with example. (ND’11,12-16M,M/J’12-16M, N/D’11-8M, M/J’13-8M
6. Explain function overloading with example. (N/D’11-10,N/D’12-16, M/J’13-8)
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
7. Create a function to compute simple interest. Supply default arguments to the function. (N/D’11-6M)
8. What is an array? Write a C++ program to find the maximum of n numbers and arrange a set of numbers in
ascending order using array. (N/D’11-8, A/M’11-8)
9. Write a C++ program to print the following output using for loops.(N/D’12-8M
1
22
333
……
10. Write a C++ program for the following: (N/D’12-8M
SUM=1+(1/2)2 + (1/3)3 + (1/4)4
11. Write a C++ program which gets student details and sort them according to the Name using Class and
Objects. (N/D’12-16M, A/M’11-8M,
12. Explain the elements of object oriented programming. (M/J’12-10M, A/M’11-4M,
13. Explain special operators in C++. (M/J’12-8M
14. Write any five differences between C and C++. (M/J’12-8M
15. How will you access an element from a two-dimensional array? Implement a program that multiplies two
matrixes and stores the result in third matrix. (A/M’11-6M, N/D’10-6M
16. Give the syntax and its uses of control statements.(A/M’11-6M,N/D’10-6M
17. How will you initialize an object in C++? (A/M’11-4M
18. How does a C++ type string differ from C type string? Explain. (M/J’13-8M
19. What are the features of OOP? Briefly comment on them. (N/D’10-12M
20. Describe about default and parameterized constructor. (N/D’10-12M
21. Give notes on i) Expressions ii) String operations. (N/D’10-12M

UNIT-2

UNIT - II
Operator overloading - friend functions- type conversions- templates -
Inheritance – virtual functions- runtime polymorphism.

Operator Overloading:
UQ: Define a class string and overload +, =, == and <= operators using C++ program. (M/J’12-16M)
Write a program to explain unary operator overloading. (N/D’12-8M)
What do you mean by operator overloading? (A/M’11-4M)
Create a class FLOAT that contains one float data member overload all the four arithmetic operators so
that they operate on the objects of FLOAT. (M/J’13-8M)
 An operator that has multiple meanings is called Operator overloading.
 Operator overloading can be defined as an ability to define a new meaning for an existing operator.
 Operator can use to define special member function of a class is called operator overloading.
Syntax:
Definition Part: Calling part:
return_type operator operator_symbol(args) symbol Object1;
{ (or)
___ object1 symbol object2;
___ (or)
} object1= object2 symbol object3;
Rules for Operator overloading:
UQ: What are the various rules for overloading operators? (N/D’11)
a) The order of precedence cannot be changed.
b) Default arguments may not be used.
c) No new operators can be created.
d) Number of operands cannot be changed.
e) Declare the operator function in “public”. If can be either normal member function or friend function.
Some operators are cannot overloadable:
UQ: Write any four operators that cannot be overloaded. (N/D’12)

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
1) Conditional operator (?:)
2) Scope resolution operator (::)
3) Class member access operator (., .*, ->*)
4) Sizeof operator (sizeof())
5) Pointer to member declarator(:: *)
Types of overloading:
i. Unary operator overloading
ii. Binary operator overloading
iii. New and delete operator overloading
iv. Overloading with friend function
v. Stream operator overloading
vi. Assignment operator overloading
i) Unary operator overloading:
UQ: How many arguments are required in the definition of an overloaded unary operator member
function? (M/J’13)
 Unary operator can take only one operand and process it.
 In unary operator overloading no arguments need in definition part.
 Unary operators are: Unary -, unary +, ++, --
 Take unary minus symbol can change the sign of the number.
Syntax:
Definition Part: Calling part:
retutn_type operator operator_symbol() Symbol object_name;
{
}

Limitations of increment/decrement operators:


 Postfix increment/decrement code not affected. Because of updated after value is used.
ii) Binary operator overloading:
 Binary operators have the two operands.
 The first object as an implicit operand and second operand must be passed explicitly.
 The data member of the first object is accessed without using “dot” operator, another object
works conversely.
 Binary operators are:
(a-b, a+b, a*b, a/b, a%b, a>b, a>=b, a<b, a<=b, a==b)
Syntax:
Definition Part: Calling part:
retutn_type operator operator_symbol(class_name object) Obj1=obj2 symbol obj3;
{
___
___
}
iii) New & delete operator overloading:
 New & delete are used for allocating & de-allocating memory dynamically.
 Overloading these two operators memory allocation for members of the class.
 This operator overloading using two operators: new & delete
Syntax:
New:
Definition Part: Calling part:
void * operator new(size_t item) Pointer_Obj1=new classname();
{
___
___
}
Delete:
Definition Part: Calling part:
void operator delete(void *p) delete pointer_Obj1;
{

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
___
delete p;
}
iv) Overloading with friend function:
 Operator overloading can be do with the friend function.
Rules:
1) Some operators cannot be overloadable with friend function:
a. Assignment operator =
b. Function call operator ()
c. Class member access operator ->
d. Subscripting operator []
2) It requires two arguments.
Syntax:
Definition Part: Calling part:
Class classname Obj1=obj2 symbol obj3;
{ (or)
___ Obj1 symbol obj2;
___
friend operator operator_symbol(arg1,arg2)
{
___
___
}
};

v) Stream operator overloading:


 Left operand of type ostream &
 Such as cout object in cout << classObject
 To use the operator in this manner where the right operand is an object of a user-defined class, it
must be overloaded as a global function.
 Similarly, overloaded >> has left operand of istream &
 Thus, both must be global functions.
Syntax:
Cin:
Definition Part: Calling part:
friend istream & operator >>(istream &is,classname &obj) Cin>>Obj1;
{
___
is>>obj.variable;
return is;
}
Cout:
Definition Part: Calling part:
friend ostream & operator <<(ostream &os,classname &obj) Cout<<Obj1;
{
___
os<<obj.variable;
return os;
}
vi) Assignment operator overloading:
 It acts as the copy constructor.
 Assignment operator another name is “copy” operator.
 Assignment operator is symbol denoted by “=”.
Syntax:
Definition Part: Calling part:

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
void operator =(classname obj) Obj1=classname(obj2);
{
___
___
}
Example:
//new, delete, stream, unary, binary, assignment Operator overloading
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include<ctype.h>
class new1
{
public:
char fname[20],dept[10],result[10],lname[20];
int rollno,m1,m2,m3,total;
float avg;
void * operator new(size_t s)//new operator overloading
{
void *t=new size_t(s);
if(!t)
return NULL;
else
{
cout<<"\nNow allocate memory";
return t;
}
}
void operator delete(void *p)//delete operator overloading
{
cout<<"\nNow de-allocate the memory";
delete p;
}
friend istream & operator >>(istream &is,new1 &n1)//stream operator overloading with friend function
{
cout<<"\nEnter the Fname,Dept,Rollno,M1,M2,M3:";
is>>n1.fname>>n1.dept>>n1.rollno>>n1.m1>>n1.m2>>n1.m3;
return is;
}
friend ostream & operator <<(ostream &os,new1 &n1)
{
cout<<"\nFname\t\tDept\tRollno\tM1\tM2\tM3"<<endl;
os<<n1.fname<<" "<<n1.dept<<"\t"<<n1.rollno<<"\t"<<n1.m1<<"\t"<<n1.m2<<"\t"<<n1.m3;
return os;
}
new1 operator +(new1 &n1)//Binary operator overloading
{
strcat(fname,n1.lname);
cout<<"\nAfter join the FName and LName:"<<fname<<endl;
return n1;
}
void operator -())//Unary operator overloading
{
m1+=10;
m2+=10; OUTPUT:
m3+=10; Now allocate memory
}
}; Enter the Fname,Dept,Rollno,M1,M2,M3:senthil
void main() it
555
WWW.VIDYARTHIPLUS.COM V+ TEAM
44 33 22
WWW.VIDYARTHIPLUS.COM
{
clrscr();
char c;
new1 *n1,n2,n3,n4,n5;
n1=new new1();
cin>>n2;
cout<<n2;
strcpy(n3.lname,"kumar");
n4=n2+n3;
cout<<"\nU want to add some marks:";
cin>>c;
if(c=='y')
-n2;
n5=n2;//Assignment operator overloading
cout<<n5;
delete n1;
getch();
}
Friend Function:
UQ: What is friend function? (M/J’13)
 It is a function that is not a member of the class but it can access the private & protected members in the
class.
 This function is given by a keyword “friend”.
 Friend function declared anywhere in the class but have given special permission to access the private
members of the class.
 It can use in single class also more than one class is called friend class.
Example:
//friend function
#include<iostream.h>
#include<conio.h>
class class2;
class class1
{
public:
int m1,m2,m3,total;
void get()
{
cout<<"\nEnter the 3 Marks for Class1:";
cin>>m1>>m2>>m3;
total=m1+m2+m3;
cout<<"\nTotal="<<total;
}
friend void compare(class1,class2);//friend function declaration
};
class class2
{
public:
int m1,m2,m3,total;
void get()
{
cout<<"\nEnter the 3 Marks for Class2:";
cin>>m1>>m2>>m3;
total=m1+m2+m3;
cout<<"\nTotal="<<total;
}
friend void compare(class1,class2); //friend function declaration
};
void compare(class1 c1,class2 c2) //friend function definition

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
{
if(c1.total>c2.total)
cout<<"\nClass-1 is top"; OUTPUT:
else Enter the 3 Marks for Class1:56
cout<<"\nClass-2 is top"; 45
} 67
void main()
{ Total=168
clrscr(); Enter the 3 Marks for Class2:67
class1 o1; 87
class2 o2; 67
o1.get();
Total=221
o2.get();
Class-2 is top
compare(o1,o2);
getch();
}
Type conversion:
UQ: What do you mean by implicit type conversion? (N/D’11)
 One type of data convert into another type of data is called type conversion.
 These type conversions use some operator functions.
 The assignment operator is automatically converted to the type of left variable sometimes is called
“implicit conversion”.
Example:
int m; float x=3.145;
m=x;
But it stored only m=3
 The user-defined type conversions can be divided into 3 types:
i) Conversion from basic to class
ii) Conversion from class to basic
iii) Conversion from one class to another
i) Conversion from basic to class:
 Conversion of basic datatype values to object in a class is called basic to class conversion.
 Basic datatypes  int, float, char, double.
 Here used constructor for conversion.
Syntax:
Definition Part: Calling part:
constructorname(datatype variable) Obj1= variable (or) value;
{
___
___
}
ii) Conversion from class to basic:
 This conversion is done by casting operator function. This function is called conversion function.
Syntax:
Definition Part: Calling part:
Operator type_name() variable= type_name(object);
{
___
___
}
iii) Conversion from one class to another:
 Assign the value of one class to another class.
 It is also done by using copy constructor.
 One class object can send as parameter to another class.
Syntax:
Definition Part: Calling part:
constructorname(classname object) Classname Obj1(obj2);

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
{
___
___
}
Example:
//Basic to class, class to basic and class to class type conversion
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include<ctype.h>
class hours
{
public:
int hour,min,sec,rsec;
hours()
{
hour=min=sec=0;
}
hours(int i) //basic to class
{
rsec=i;
cout<<"\nTotal Seconds="<<i<<endl;
hour=i/3600;
min=(i%3600)/60;
sec=(i%3600)%60;
cout<<hour<<" : "<<min<<" : "<<sec;
}
operator int()//class to basic OUTPUT:
{ Total Seconds=5604
int s1=(hour*3600)+(min*60)+sec; 1 : 33 : 24
return s1; Total Seconds=5604
} Increased seconds(100):5704
};
class another_hour
{
public:
another_hour(hours h2) //class to class
{
cout<<"\nIncreased seconds(100):"<<h2.rsec+100;
}
};
void main()
{
clrscr();
int s;
hours h1;
h1=5604;//basic to class
s=int(h1);//class to basic
cout<<"\nTotal Seconds="<<s;
another_hour ah(h1);//class to class
getch();
}
Templates:
 Template support generic programming which allows developing reusable components such as
functions, class, etc.
 It supports different datatypes in single framework.
 It reduces the number of functions (or) classes in program. Because template perform the same
operation on different datatypes.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 Types of templates:
1. Function template
2. Class template
1. Function template:
 It is performed with the keyword “template” and list of template type arguments.
 It is declared in front of function definition.
 At least one argument must be template type.
 If a program contain more than one function template for same function name is called function
template overload.
Syntax:
template<class T>
return_type function_name(arguments)
{
___
___
}
Example:
// Example for function template and overloading function template
#include<iostream.h>
#include<conio.h>
template<class T>
void add(T a)
{
T b=10;
cout<<"\nTotal="<<a+b<<endl;
} OUTPUT:
template<class T> Total=15
void add(T a,T b)
{ Total=30
cout<<"\nTotal="<<a+b<<endl;
} Total=12
template<class T> Senthil
void add(char *a,T n) Senthil
{ Senthil
for(int i=0;i<n;i++)
cout<<a<<endl;
}
void main()
{
clrscr();
add(5);
add(20,10);
add(5.7,6.3);
add("Senthil",3);
getch();
}
2. Class Template:
 It is used proceeding of class is called class template.
 The template can use throughout the class end.
Example:
//Example for Class Template
#include<iostream.h>
#include<conio.h>
template<class T1,class T2>
class avg
{
T1 a,b;//integer or float data type for template class T1
T2 c;//float data type for template class T2

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
public:
void get()
{ OUTPUT:
cin>>a>>b; Class Template
}
void disp()
Enter the two integer numbers:2 5
{ A=2
cout<<"\nA="<<a<<"\nB="<<b; B=5
c=(a+b)/2.0; //find average here Average:3.5
cout<<"\n\tAverage:"<<c;
} Enter the two float numbers:3.6 4.7
}; A=3.6
void main() B=4.7
{
Average:4.15
clrscr();
cout<<"\n\tClass Template";
avg<int,float> a1; //creating object for template class in <int,float>
cout<<"\nEnter the two integer numbers:";
a1.get();
a1.disp();
avg<float,float> a2; //creating object for template class in <float,float>
cout<<"\nEnter the two float numbers:";
a2.get();
a2.disp();
getch();
}
Inheritance:
UQ: Define inheritance. What are the types of inheritance?
1. Give a brief note on hybrid inheritance with an example.
2. Create a base class called vehicle and add relevant data members and functions to it. Create derived classes
that directly inherit the base class called two wheeler and four wheeler and relevant data members and
functions to them. Write a main program and create objects for derived class and access the member
functions.
3. Illustrate multiple inheritance with an example.
4. Explain the different types of inheritance with sample code.
 Inheritance is one of important features of OOP.
 Add some properties in existing class is called inheritance.
 A new class derived from the existing class.
 The inheritance can be achieved by incorporating the definition of one class into another.
 It is mainly used for “reusability” purpose.
 New class- sub class, derived class, child class.
 Existing class- super class, base class, parent class.
Syntax:
class class-name1
{
__
__
}
class class-name2 : access_specifier class-name1
{
__
__
}
Types of Inheritance:
1) Single Inheritance
2) Multilevel Inheritance
3) Multiple Inheritance.
4) Hierarchical Inheritance

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
5) Hybrid Inheritance
1) Single Inheritance:
UQ: Write down the different access specifiers. (N/D’10)
 It contains only one super class, and sub class.
 The sub class is specialized for adding some properties.
 The access specifier is used for mode of access class members
 The access specifiers are:
o Private, protected, public
Syntax:
class class-name1
{
__
A
__
}
class class-name2 : access_specifier class name1. B
{
__
__
}
2) Multilevel Inheritance:
 A new class derived from existing class from that class derived new class is called multilevel Inheritance.
 In multilevel inheritance there is one super class, one intermediate class, and one derived (or) sub class.
 This act as relationship:

Grandfather Father Son


Syntax:
class A ADD A
{
__
__
__ SUB B
}
class B : access_specifier A
{
__ MUL C
__
}
class C : access_specifier B
{
__
__
}
3) Multiple Inheritance:
 A class can inherit the attributes of two or more classes are called multiple inheritance.
 It allows combining the features of several existing class.
 It will achieve two base classes are inherit in single derived class.
Syntax:
class A
{
__
__ A B
__
}
class B
{ C
__
__

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
}
class C : access_specifier A, access_specifier B
{
__
__
}
4) Hierarchical Inheritance:
 This type of inheritance shares the information to other classes.
 That means one super class, many sub class in this inheritance.
 Hierarchy is followed one head other classes are Labors.
 In this inheritance some problem will occur.
 So that we can use abstract class as “Super class”.
Syntax:
class A
{ MUL
A
__
__
}
class B : access_specifier A
{ B C DIV MOD
__
__
}
class C : access_specifier A
{
__
__
}
5) Hybrid Inheritance:
 To apply more than two inheritances for design a program is called hybrid.
 It is also called as multipath inheritance (or) virtual base class.
Example:
//Example for Single, Multilevel, Multiple, Hierarchical, Hybrid Inheritance
#include<iostream.h>
#include<string.h>
#include<conio.h>
class Basic_Info
{
public:
int regno;
char name[20],dept[5];
void get_Basic_Info()
{
cout<<"\nEnter Regno, Name, Dept:";
cin>>regno>>name>>dept;
}
};
class academic:public Basic_Info
{
public:
int m1,m2,m3,total; Basic_Info
float avg; Single
char result[5]; Inheritance
void get_academic() Multilevel
{ Academic
Inheritance
cout<<"\nEnter the 3 Subjects marks:";
cin>>m1>>m2>>m3;
total=m1+m2+m3;
Personal
WWW.VIDYARTHIPLUS.COM V+ TEAM
Hierarchical
WWW.VIDYARTHIPLUS.COM
avg=total/3.0;
if(m1<50||m2<50||m3<50)
strcpy(result,"Fail");
else
strcpy(result,"Pass");
}
};
class personal: public academic
{
public:
char address[20],blood_group[5];
long int phno;
void get_personal()
{
cout<<"\nEnter the address, blood Group, Phone Number:";
cin>>address>>blood_group>>phno;
}
};
class hoppy : virtual public personal
{
public:
char sports[20], cultural[20];
void get_hoppy()
{
cout<<"\nEnter the Sports and Cultural Details:";
cin>>sports>>cultural;
}
};
class Extra : virtual public personal
{
public:
char event[20],prize[10];
void get_Extra()
{
cout<<"\nEnter the Event and Prize:";
cin>>event>>prize;
}
};
class display : public hoppy,public Extra
{
public:
void get_display()
{
cout<<"\nStudent Details\n";
cout<<"------------------\n";
cout<<"\nRegNo\tName\t\tDept\tM1\tM2\tM3\tTotal\tAvg\tResult\n";
cout<<"--------------------------------------------------------------\n";
cout.precision(2);
cout<<regno<<"\t"<<name<<"\t"<<dept<<"\t"<<m1<<"\t"<<m2<<"\t"<<m3<<"\t"<<total<<"\t"<<avg<<"\t"<<result
;
cout<<"\nAddress\t\tBloodGroup\tPhno\n";
cout<<"--------------------------------------------------------------\n";
cout<<address<<"\t"<<blood_group<<"\t\t"<<phno;
cout<<"\nSports\t\tCultural\n";
cout<<"--------------------------------------------------------------\n";
cout<<sports<<"\t"<<cultural;
cout<<"\nEvent\t\tPrize\n";
cout<<"--------------------------------------------------------------\n";
cout<<event<<"\t"<<prize;
OUTPUT:
WWW.VIDYARTHIPLUS.COM Student Details V+ TEAM
------------------
WWW.VIDYARTHIPLUS.COM
}
};
void main()
{
clrscr();
display d;
d.get_Basic_Info();
d.get_academic();
d.get_personal();
d.get_hoppy();
d.get_Extra();
d.get_display();
getch();
}

Polymorphism:
 Polymorphism is a Greek term; it means the ability to take more than one form.
 Poly => Many
 Morphs =>Forms.
 An Operation may exhibit (display or Show) different behaviors on the types of data used in the Operation.
 Polymorphism divide into two types:
iii. Compile Time Polymorphism
iv. Runtime Polymorphism

Polymorphism

Compile-Time Run-Time

Function Operator Virtual Pure Virtual


Overloading Overloading functions function

ii) Compile-time Polymorphism:


 It can be execute the code in compile time.
 It’s divide into two types
3. Operator Overloading
4. Function Overloading
3. Operator Overloading:
 The Process of making an Operator to exhibit different behaviors in different instance is known as
Operator Overloading.
 Operation of addition
For two numbers, the Operation will generate a “Sum”.
For two strings, the Operation will produce a third String by “Concatenation”.
4. Function Overloading:
UQ: What do you mean by function overloading? (A/M’11)

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Write a program to find the area of different shapes using function overloading and explain it. (N/D’10-
12M)
 Using a Single Function name to perform Different types of tasks is known as function overloading.
 A Single function can be used to handle different number & different types of arguments.
 A Particular word having several meanings depending on the context.
 Polymorphism plays an important role in allowing objects having
different internal structures.

Example:
#include<iostream.h>
#include<string.h>
#include<conio.h>
void area(int a) OUTPUT:
{ Cube Area:1000
cout<<"\nCube Area:"<<(a*a*a); Rectangle Area:200
} Rectangular Box Area:6000
void area(int b,int l)
{
cout<<"\nRectangle Area:"<<(l*b);
}
void area(int l,int b,int h)
{
cout<<"\nRectangular Box Area:"<<(l*b*h);
}
void main()
{
clrscr();
area(10);
area(10,20);
area(10,20,30);
getch();
}

iii) Run-Time Polymorphism:


 It can be execute the code in Run time.
 It’s divide into two types:
1. Virtual Functions
2. Pure virtual functions

Virtual Functions:
UQ: Define virtual functions. (M/J’12, A/M’11, M/J’13)
 It is a function that is declared within a base class & redefined by a derived class.
 Use the same function name in both the base & derived class.
 The function in base class is declared as virtual using the keyword “virtual” preceding its normal
function.
 Multiple functions performing different task that is mean by polymorphism.
Rules:
i) It must be members of some class.
ii) They cannot be static members.
iii) They are accessed by using pointer objects.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
iv) It can be friend of another class.
v) It is in a base class must be defined even though it may not be used.
Advantages:
UQ: What are the main advantages of virtual functions? (N/D’12)
1. Used to support polymorphism with pointers and references
2. Declared virtual in a base class
3. Can be overridden in derived class
Example:
//Example for Virtual function
#include<iostream.h>
#include<string.h>
#include<conio.h>
class base
{
public:
void display()
{
cout<<"\nDisplay Base";
}
virtual void show()//virtual function
{
cout<<"\nShow Base using virtual function";
}
};
class derived : public base
{
public:
void display()
{
cout<<"\nDisplay Derived";
}
void show()
{
cout<<"\nShow Derived";
}
}; OUTPUT:
void main() Display Base
{ Show Base using virtual function
clrscr(); Display Derived
base b,*p; Show Derived
derived d,*p1;
p=&b;
p->display();
p->show();
p1=&d;
p1->display();
p1->show();
getch();
}

Pure virtual function (or) Abstract class:


UQ: What is an abstract base class?
What is pure virtual function? Give its syntax.
 It is a function declared in a base class that has “no definition”.
 Such functions are called “do-nothing” functions.
 If the base class is abstract class, should create the pointer object for that class.
 This same function name re-declared in the derived class.
 If the class contains the pure virtual function is act as “abstract class” or “abstract base class”.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 This abstract class is mainly used in hierarchical inheritance.
 These classes are usually outcome of generalization process which finds out common elements of class.
Syntax: virtual return_type function_name()=0;
Example:
//Example for pure virtual function (or) Abstract base class
#include<iostream.h>
#include<string.h>
#include<conio.h>
class shape
{
public: Shape
virtual void area()=0;
};
class circle:public shape
{
public: Circle Rectangle Triangle
void area()
{
cout<<"\nCircle Area";
}
};
class rectangle:public shape
{
public:
void area()
{
cout<<"\nRectangle Area";
}
};
class triangle:public shape
{
public:
void area() OUTPUT:
{ Circle Area
cout<<"\nTriangle Area"; Rectangle Area
} Triangle Area
};
void main()
{
clrscr();
shape *p;
circle c;
rectangle r;
triangle t;
p=&c;
p->area();
p=&r;
p->area();
p=&t;
p->area();
getch();
}
Explanation:
 The base class represented as the “shape” & other classes are rectangle, circle and triangle.
 This above example represents the hierarchical inheritance.
University Questions:
PART-A
1. What do you mean by implicit type conversion? (N/D’11)

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
2. What are the various rules for overloading operators? (N/D’11)
3. Write any four operators that cannot be overloaded. (N/D’12)
4. What are the main advantages of virtual functions? (N/D’12)
5. What is an abstract base class? (M/J’12)
6. Define virtual functions. (M/J’12, A/M’11, M/J’13)
7. Define inheritance. What are the types of inheritance? (A/M’11, N/D’10)
8. What do you mean by function overloading? (A/M’11)
9. What is friend function? (M/J’13)
10. How many arguments are required in the definition of an overloaded unary operator member function?
11. What is pure virtual function? Give its syntax. (N/D’10)
12. Write down the different access specifiers. (N/D’10)

PART-B
5. Give a brief note on hybrid inheritance with an example. (N/D’11-8M)
6. Create a base class called vehicle and add relevant data members and functions to it. Create derived classes
that directly inherit the base class called two wheeler and four wheeler and relevant data members and
functions to them. Write a main program and create objects for derived class and access the member
functions. (N/D’11-8M)
7. Illustrate multiple inheritance with an example. (N/D’12-8M)
8. Explain the different types of inheritance with sample code. (M/J’12-16M, A/M’11-8M)
9. Define a class string and overload +, =, == and <= operators using C++ program. (M/J’12-16M)
10. Write a program to explain unary operator overloading. (N/D’12-8M)
11. What do you mean by operator overloading? (A/M’11-4M)
12. Create a class FLOAT that contains one float data member overload all the four arithmetic operators so
that they operate on the objects of FLOAT.( M/J’13-8M)
13. Describe how an object of a class that contains objects of other classes created. (M/J’13-8M)
14. Describe the different ways by which the public member function can be accessed. (M/J’13-8M)
15. Write a program to find the area of different shapes using function overloading and explain it. (N/D’10-
12M)

Unit-3
Exception Handling
UQ: What is an exception? (M/J’11, N/D’09, M/J’12)
How is an exception handled in C++? (N’09, 10)
What are the types of exceptions? C++ provides what type of exceptions. (M/J’07)
Explain how exception handling is achieved in C++. Give 3 different constructs and explain the working of
them.
 Exception refers to unusual conditions in a program.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 The unusual conditions could be faults, causing an error which in turn causes the program to fail.
 The error handling mechanism of C++ is general referred to as exception handling.
UQ: What is mean by asynchronous and synchronous exception?( N/D’10)
Exceptions two types:
1. Synchronous
2. Asynchronous.
1. Synchronous:
 The exception occurs due to wrong input,
logic is not suitable to handle the data.
 Errors such as:
1. Out of range
2. Over flow
try Block
3. Under flow
4. Divide by zero
 The above errors are within a program. statement
2. Asynchronous:
 The asynchronous exception occurs due to extend throw-1
events of the program or beyond the control of program.
 Errors such as:
 Keyboard interrupts throw-2
 Hardware mal functions
 Disk failure & so on.

Exception handling model: throw-n


 This exception handling model contains blocks.
 Blocks also called as constructs
 Those are:
1. try Block
2. throw Block catch-1
3. catch Block
Action statement
 The diagrammatical representation of
Exception handling models is catch-2
1. try block (or) Construct:
 The main job of the try block is to find the abnormal Action statement
conditions for the given statements.
 Then using throw blocks it throws the exception objects.
The general form: catch-n
try
{
Action statement
Statement-1;
__ a
__
__
Statement-n;
}

2. Throw-Block (or) Construct:


 This throw block is used to throw the selected exception objects.
The general form:
throw error obj;
(or)
throw (error obj);
(or)
throw;

3. Catch Block (or) Construct:

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 This catch block is used to catch thrown exception objects by the try block.
 Then it executes the required action statement handle the exceptions.
The general form:
catch (errorobj)
{
Statement-1
__ __
__ __
__ __
Statement A;
}
Rules:
1. Catch block should immediately follow the try block.
2. Catch object & throw object should match.
Tasks of Exception Handling:
1. Detect the exception
2. Inform that an error has occurred
3. Receive the error Info
4. Take correct actions

Example:
fun()
{
if(operation fail)
throw object 1;
}
try
{
fun();
if (over fail)
throw object 2;
}
catch (object1)
{
//take corrective actions for operation fail.
}
catch (object 2)
{
//take corrective action for over flow
}
Terminate & Unexpected functions:
There are some exception handling events
1. Divide by zero
2. Array reference out of bound
3. Overflow (stack)
4. Underflow(stack)

Exception specification: List of exceptions


UQ: Explain multiple catch statement with help of suitable C++ coding. (M/J’07-8M)
 Defining the possible exceptions excepted in a program by the user.
 It is implemented with functions.
 This function should be defined before try block.
General form:
return type function-name (list of arg) throw (list of error objects)
{
Statement-1;
__ __ __
WWW.VIDYARTHIPLUS.COM __ __ __ V+ TEAM
statement n;
WWW.VIDYARTHIPLUS.COM

Example:
//Divide by zero
void test (int x, int y ) throw (int, float, char)
{
if (y==0)
throw ’z’;
else if (x!=0)
throw x;
else
throw 0.0;
}
void main()
{
try
{
cout <<”\n Enter a&b value:”;
cin>>a>>b;
test (a,b);
}
catch (char c)
{
cout <<”Division by zero”;
}
catch (int m)
{
cout<<”The value:”<<a/b;
}
catch (float f)
{
cout <<”The value =0”;
}
}
Array Reference out of bound:
 If any attempt is made to refer to an element whose index is beyond array size an exception raised.
Example:
const int size=10;
class array
{
int arr[size];
public:
class range{}; // range abstract class
int & operator [] (int i)
{
if (i<0|| i>=size)
throw range();
return arr[i];
}
};
void main()
{
array a[size];
cout<<”max array size allowed:”<<size;
try
{
cout<<”trying to refer a[i]……….”;
a[1]=10;
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
cout<<”succeeded”;
cout<<”trying to refer a[15]……”;
a[15]=10;
cout<<”succeeded”;
}
catch (array : : range)
{
cout<<”out of range in array reference”;
}
}
Catch all exceptions:
 Catch all the exceptions during the exception handling.
Syntax
catch(…..)
{
statement for processing all exceptions
}
Example:
void test (int x)
{
try
{
if (x= =0) throw x;
if (x= =-1) throw ’x’;
if(x= =1) throw 1.0;
}
catch (…..) //catch all
{
cout<< caught an exception”;
}
}
void main()
{
test(-1);
test(0);
test(1);
}
Streams:
UQ: Define stream and file stream class. list its types.( N/D’10)
 It is a channel on which data flow from a source to destination.
 A stream is a sequence of bytes.
 The stream is divided into two categories:
(i)Input Stream
(ii)Output Stream
(i)Input Stream:
The source stream that provides data to the program is called the Input stream.
(ii)Output stream:
The destination stream receives output from the program is called output stream.

Input Stream
Input
Device
Extraction >>

program

Output Stream Insertion <<


Output
Device
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM

Stream classes:
 The C++ I/O system contains a hierarchy of classes that are used to define various streams. These classes are
called stream classes.
 Figure shows hierarchy of the stream classes used for Input & Output operations.
 These classes are declared in the header file iostream.

Stream Classes ios

istream streambuf ostream

Input iostream Output

istream_withassign iostream_withassign ostream_withassign

 The class ios provides the basic support for formatted & Unformatted I/O operations.
istream -> for formatted & Unformatted Input.
ostream->for formatted & Unformatted Output.
iostream -> Both Input & Output Stream.
 istream-withassign, ostream-withassign, iostream-withassign add assignment operators to these classes.
I/O Manipulators:
UQ: What are manipulators? (M/J’12, N/D’10)
What are manipulators? Explain in detail various manipulators used for I/O operations with example. (M/J’12,
N/D’09,10,11-10M
 Manipulators are the operators in C++ that are used for formatting the output.
 The header file “iomanip” provides a set of functions called manipulators.
 The various manipulators are:
1. setw()
2. setprecision()
3. setfill()
4. endl
1. setw()
This function is used to set the minimum field width.
Syntax: setw(int)
2. setprecision()
This function is used to numbers of digits to be displayed after the decimal point.
Syntax: setprecision(int);
3. setfill()
This function fill up the characters in the unused space.
Syntax: setfill(char);
4. endl:
This operator is used to end the line (or) return the cursor in the first point of line.
Example: (I/O Manipulators)
#include <iostream.h>

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
#include<math.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
clrscr();
int i;
for(i=0;i<=3;i++)
{
cout<<setw(i+7);
cout<<"SENTHIL"<<"\n";
}
for(i=0;i<=3;i++)
{
cout<<setprecision(i+1);
cout<<1.23456890<<"\n";
}
for(i=0;i<=3;i++)
{
cout<<setfill('*');
cout<<setw(i+7);
cout<<"SENTHIL"<<"\n";
}
getch();
}
OUTPUT:
SENTHIL
SENTHIL
SENTHIL
SENTHIL
1.2
1.23
1.234
1.2345
SENTHIL
*SENTHIL
**SENTHIL
***SENTHIL
Unformatted I/O operations:
UQ: Explain in briefly about formatted and unformatted I/O operations with example.(N/D’10-12M)
Overloaded operators >> and <<
 We have used the objects (cin & cout) for Input & Output of data of various types.
 This has been made possible by overloading the operators >> & <<.
 The >> operator is overloaded in the istream class.
 The << operator is overloaded in the ostream class.
Syntax: cin >> variable 1>> variable2>> …….>>variable n;
Example: int a,b,c,d;
cin>>a>>b>>c>>d;
Syntax: cout<<variable1(or)item1<<item2<<…..<<item n
Example: cout<<a<<b<<c<<d;
 Variable1…..n already declared in the starting itself.
 Item1….n are may be variables or constant (or) strings [cout<<”Enter the value:”]
Put () & get () functions:
 The classes isteam & ostream two member functions get() & put().
 The two functions to handle the single character I/O operations.
get()->read single char input
put()->Display single char output
Syntax: cin.get(char ch); | cout.put(char ch);

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Example:
#include<iostream.h>
void main() OUTPUT:
{ Input Text:Senthil
int count=0; Senthil
char c; Total No. of Characters:7
cout<<”input text”;
cin.get (c);
while (c!=’\n’)
{
cout.put(c);
count ++;
cin.get(c);
}
cout<<”total no. of characters:”<<count;
getch();
}
Get line () and write () functions
We can read and display a line of text more efficiently using the line-oriented I/O functions “getline()”
and “write()”.
getline():
This function reads a whole line of text that ends with a new line character.
Syntax: cin.getline(line,size);
write():
This function display a whole line of text.
Syntax: cout.write(line, size);
Example:
void main()
{ OUTPUT:
int cl; Enter the name:
char name[20]; Senthil Kumar
cout<<”enter the name:”; Using the write function
cin.getline(name,20); Senthil Kumar
cout<<”using the write function”; Sentil Ku
cout.write(name,20); se
cout.write(name,10);
cout.write(name,2);
getch();
}
Formatted I/O:
 C++ supports a number of features that could be used for formatting the output.
 These features are include:
o ios class functions
o Manipulators
 ios class functions:
o This ios class contains some member functions.
o Those functions are:
1. width()
2. precision()
3. fill()
1. width()
 To specify the required field size for displaying an output value.
Syntax: cout.width(int);
2. precision()
 To specify the number of digits to be displayed after decimal point of a float value.
Syntax: cout.precision(int);
3. fill()
 To specify a character that is used to fill the unused portion of a field.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Syntax: cout.fill(char);
Example:
//Example for Formatted I/O
#include<iostream.h>
#include<math.h>
#include<conio.h>
void main()
{
clrscr();
int i;
for(i=0;i<=5;i++)
{
cout.width(i+7);//width function
cout<<”SENTHIL”<<”\n”; OUTPUT:
} SENTHIL
for(i=0;i<=5;i++) SENTHIL
{ width SENTHIL
cout.precision(i+1);//precision function SENTHIL
cout<<1.234567890<<”\n”; SENTHIL
} 1.2
for(i=0;i<=5;i++) 1.23
{ Precision 1.234
cout.fill(‘*’);//fill function 1.2345
cout.width(i+7); 1.23456
cout<<”SENTHIL”<”\n”; SENTHIL
} *SENTHIL
getch(); **SENTHIL
} Fill ***SENTHIL
File Handling ****SENTHIL
UQ: Explain file and its operations.(N/D’09)
Using file handling methods of C++ write a program and explain how to merge the contents of two files into one
file.( N’09,10,11-16M)
 A file is a collection of related data stored in a particular area on a disk.
 Programs can be designed to perform the read & write operations on these files.
Input Stream
Read Data

Data Input
Disk
Program
Files
Output Stream Data Output
Write Data

Classes for file stream operations

ios

istream streambuf ostream

iostream
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM

Open file operation


Manipulation of a file involves the following steps:
1. Name the file on the disk.
2. Open the file to get the file pointer.
3. Process the file (read/write)
4. Check for errors while processing
5. Close the file after its complete usage.
 The file operations are associated with the object of one of the classes: if stream, of stream (or) f stream.
 The file can be opened by the function called “open()”.
Syntax:
File stream object. Open (filename,mode);
Close file operation
 To close the file the member function “close()” is used.
 The close function takes no parameter and returns no value.
Syntax: File stream object.close();
 Detect when the end of an input file has been reached by the eof() member function of ios.
 It returns “true” when end of file or otherwise.
Read content from file:
 If you want read the content from the file using read().
 Read the content in two ways:
1. Using file pointer
2. Using stream object
1. Using file pointer:
 First create the file pointer with help of fstreams. Next open the stream.
Syntax: ifstream object-name;
Example:
ifstream f1;
f1.open(“Input.txt”);
f1>>a;
2. Using stream object:
 Create & open the stream object.
 Next step read the file content and assign the values to local variable.
Syntax:
ifstream in;
in.read(char*) & variable, size of (variable);
Example1: in.read (char*) &b,size of (b));
Example2:
//Read & Write in file (or) Multiple file Handling
void main()
{
ofstream out;
int a[10]={1,2,3,4,5}, b[10];
out.open(“input.txt”);
out.write((char*) &a, size of (a));

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
out.close();
ifstream in;
ofstream fp1, fp2;
in.open(“input.txt”);
in.read((char*) &b, size of (b));
fp1.open (“even.txt”);
fp2.open(“odd.txt”);
for (int i=0; i<10; i++)
{
if (b[i]%2==0)
fp1<<b[i]<<” ”;
else
fp2<<b[i]<<” “;
}
in.close();
fp1.close();
fp2.close();
if stream fp;
char ch;
fp.open (“even.txt”);
cout<<”the even file contents are:”;
while (fp)
{
fp.get(ch); //(or)fp>>ch;
cout<<ch;
}
fp.close();
fp.open(“odd.txt”);
cout<<”the odd file contents are:”;
while (fp)
{
fp.get(ch); //(or)fp>>ch;
cout<<ch;
}
fp.close();
getch();
}
FILE MODES:
 File mode specifies the purpose for which the file is opened.
 File mode is included in the “ios” operations.
 Some file modes and meaning of file modes:
1. ios: :app-Append to end of file.
2. ios: :ate-Go to end of file on opening.
3. ios: :binary-Binary file.
4. ios: :in-open file for read only.
5. ios: :nocreate-open fails if the file does not exist.
6. ios: :noreplace-open fails if the file already exists.
7. ios: :out-open file for writing only.
8. ios: :trunc-Delete the contents of the file.
Example:
fin.open(“Input.txt”, ios: :in);
Detecting End-of-File: (eof)
Detecting eof in two ways:
(i)while(fin):
It returns valus “0” when reaching eof condition.
(ii)if (fin.eof()!=0)
 Eof()-member function of “ios” class.
 It returns a non-zero(1) values, if the eof condition.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
RANDOM ACCESS:
UQ: Explain the concept of random access in file and namespace. (M/J’07,05,A/M’06-16M)
 While performing file operations, we must be able to reach at any desired position inside the file.
 For this purpose there are two operations used.
(1) seek
(2) tell
(1) Seek:
The seek operation is using two functions:
1. seekg()-get pointer location for “reading”
2. seekp()-get pointer location for “writing”
Syntax:
Object.seekg(offset, reference-position);
Object.seekp(offset, reference-position);
Where offset-any constant specifying location
Reference.position-position is beginning, end or current position
If can be specified
ios: :beg->for beginning
ios: :end->for end
ios: :cur->for current
(2) Tell:
This function tells us current position.
Example:
S1.tellg()-Current position of get pointer
S2.tellp()-Current position of put pointer
Example: (Random Access)
void main()
{
ifstream in;
in.open(“stu.txt”);
char data[80];
cout<<”initial statement”;
in.seekg(0,ios::beg);
in.getline(data,80);
cout<<data;
cout<<”at the end”;
in.seekg(-14,ios::end);
in.getline(data,80);
cout<<data;
in.close();
}
Error handling during file operations:
UQ: What are the error handlings functions used in file systems?( N/D’10)
1) Eof()-It returns value(1) if end-of-file.
2) Fail()-returns true(1) when an input (or) output operation has failed.
3) Bad()-returns true(1) if an invalid operation.
Namespaces:
UQ: What is standard namespace? How it differs from other namespaces?(N/D’09)
What are the ways of using namespaces? (M/J’12)
 Namespace avoids the name conflict problem.
 Namespaces are used to group the entities like class, variables, objects, and functions under a name.
 The namespaces help to divide global scope into sub-scopes, where each sub-scope has its own name.
 To access the variables from outside of namespace use scope resolution operator(::).
 The keyword “using” is used to introduce the namespace being used currently.
Example:
#include<iostream>
#include<stdlib.h>
using namespace std;
namespace ns1

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
{
int a=5;
}
namespace ns2
{
char a[]="hello";
}
int main()
{
cout<<ns1::a<<endl;
cout<<ns2::a<<endl;
system("PAUSE");
return 0;
}
Std Namespace:
 It is a namespace where the standard library functions are defined.
 All the library files declared within std namespace.
 std namespace cannot be extended.
 That’s why in the C++ program the std namespace is declared as,
#include<iostream>
using namespace std;
Which uses any entity declared in iostream.
ANSI String Objects:
UQ: Give the possible operations on string objects.(N/D’09)
List out and explain string functions in ANSI.(A/M’06)
Explain the ANSI string objects with example.(A/M’05,08,11-12M)
Need for String Objects:
 Strings are implemented in “C” as character arrays.
 However, character arrays have a few limitations when treated as strings:
1. They cannot be compared like other variables.
2. They cannot be assigned.
3. Initializing with another string is not possible.
 Therefore, it is treat as separate objects. C++ overcomes by providing string objects.
 Here used sstream library file, which is used to perform string based I/O operations.
Operations on strings:
1. Creation of strings.
2. Substring operations:
a. Finding location of substring.
b. Find the location at the character.
c. Inserting a specific substring.
d. Replacing specific characters.
e. Appending substring to a string.
3. Operations involving multiple strings:
a. Concatenation, Copy and Comparison function.
b. Swapping two strings.
4. Finding characteristics of a string.
5. Erasing a string.
1. Creation of strings:
 A string object can be created in three ways:
i. Defining a string object in normal way:
 Ex: string str1;
ii. Using initialization:
 Ex: string str2=str1;
iii. Using a Constructor:
 Ex: str1(“Kumar”); (or) str1=”Kumar”;
2. Substring operations:
 Various functionalities provided by string class are
Sno. Function Name Description

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
1) append() Appending one string to another
2) at() Get the char at specific location
3) find() Searching
4) insert() Inserting char or string
5) replace() Replaces char or string
3. Operations involving multiple strings:
Sno. Function Name Description
1) + Concatenation of two strings
2) = Assigning one string to another
3) <, >, ==, != Comparing between two strings
4) swap() Swapping two strings
4. Finding characteristics of strings:
Sno. Function Name Description
1) size() It returns size of the string
2) empty() If string is empty it returns “true” that means 1
3) max_size() It return maximum permissible size of string
4) resize() It resizes the string by the number of supplied as argument
5. Erasing a string.
Sno. Function Name Description
1) erase() Removing the specified char
Example:
#include<iostream>
using namespace std;
int main()
{
string str1("Hello"),str2("India"),str3;//string datatype
str1+=str2;//concatenation
cout<<"\nEnter the string:";
cin>>str3;
str1.insert(5,str3);//insert
cout<<"\nAfter insert:" <<str1;
cout<<"\nEmpty :"<<str1.empty();//find Empty or not
str1.erase(5,6);//erase
cout<<"\nAfter erase of 6Characters:" <<str1;
cout<<"\nSize of Str1:"<<str1.size();//size
string str4=str1.substr(2,3);//substring
cout<<"\nFind substring in Str4:" <<str4;
cout<<"\nMaximum Size of str4:"<<str4.max_size();//Max Size
str2.swap(str4);//swap
cout<<"\nAfter swap:" <<"\nstring2:"<<str2 <<"\nstring4:"<<str4<<endl;
system("PAUSE");
return 0;
}
OUTPUT:
Enter the string:Greate
After insert:HelloGreateIndia
Empty :0
After erase of 6Characters:HelloIndia
Size of Str1:10
Find substring in Str4:llo
Maximum Size of str4:1073741820
After swap:
string2:llo
string4:India
Press any key to continue . . .
Standard Template Library(STL)
UQ: What is Standard Template Library? List the components of STL. (M/J’12-16M)

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 The Standard Template Library(STL) is collection of well structured generic C++ classes (templates) and
functions.
 Already programmed functions are consisting in STL.
 Basic STL consist of three components:
1) Container 2) Algorithms 3) Iterators
 These three components works in conjunction with one another.
Block diagram of STL
Algorithm1

Iterator1 Container

Iterator2

Object1 Object2 Algorithm2

Object3

Iterator3

Algorithm3
Container:
o Container is an object that actually stores data.
o It is a way data is organized in memory.
o STL implemented by template classes & therefore to hold different types of data.
o Container categories into 3 groups. Those are:
1) Sequence container
2) Associate container
3) Derived container
 Container types in represent block diagram.

Container

Sequence Derived
Associate
container container
container
Vectors Stack
Set
Deque Queue
Multiset
List Priority queue
Map
Multimap
1) Sequence container:
 It store elements in a linear sequence like as line.
 Each element is related to other elements by its position along the line.

Element0 Element1 Last


Element
Iterator

Begin() End()

 The Sequence container provides three types of applications:
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
SNo. Container Description
1. Vector A dynamic array allows insertions and deletions at back. Permit direct access to any
element.
2. List A bi-directional linear list. Allows insertions and deletions anywhere.
3. Deque A double ended queue. Allows insertions and deletions at both ends.
2) Associative container
 These are designed to support direct access to elements using keys.
 They are not sequential.
 There are four types of associative containers:
SNo. Container Description
1. Set For storing unique sets. Allows rapid look-up.
2. Multiset For storing non-unique sets.
3. Map For mapping unique key with value pairs. Each key is associated with only one value.
4. Multimap For storing key with value pairs which one key may be associated with more than one value.
3) Derived container:
The derived containers are created from sequence containers.
The derived containers are:
SNo. Container Description
1. Stack A standard stack.(LIFO)
2. Queue A standard queue.(FIFO)
3. Priority Queue A priority queue, first element out is always the highest priority element.
Algorithms:
o Algorithms are functions that can be used for processing their contents.
o Although each container provides functions for its basic operations.
o STL algorithms based on the nature of operations and types of algorithms:
1. Relative or non-mutating algorithms
2. Mutating algorithms
3. Sorting algorithms
4. Set algorithms
5. Relational algorithms
1. Relative or non-mutating algorithms:
This algorithm has some operations:
Count(), countif(), equal(), find(), find_if(), for_each(), etc
2. Mutating algorithms:
The summarized operations of mutating algorithms:
Copy(), fill(), generate(), remove(), replace(), reverse(), rotate(), swap(), etc.
3. Sorting Algorithms:
Sorting algorithms are processed various methods:
Binary_search(), partial_sort(), sort_heap(), merge(), etc.
4. Set algorithms:
It is used to do some set operations:
Set_difference(), set_intersect(), set_union(), equal(), max(), min(), mismatch(). Etc.
5. Relational algorithms:
Relational algorithms used to do some relational operations.
Equal(), max(), min(), mismatch(), etc.,
Iterators:
o Iterators behave like pointers and are used to access container elements.
o They are often used to traverse from one element to another.
o Some operations of iterators:
Input(), output(), forward(), bi-directional(), random(), etc.
University Questions:
PART-A
1. What is an exception? (M/J’11,N/D’09,M/J’12)
2. How is an exception handled in C++? (N’09,10)
3. What are the types of exceptions? C++ provides what type of exceptions. (M/J’07)
4. Define multiple catch statements. Write the syntax for that. (N/D’10)
5. What is mean by asynchronous and synchronous exception?( N/D’10)
6. What are the ways of using namespaces? (M’12,
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
7. What are manipulators? (M/J’12, N/D’10
8. Define stream and file stream class. list its types.( N/D’10,
9. What are the error handlings functions used in file systems?( N/D’10,
10. Explain file and its operations.(N/D’09,
11. What is standard namespace? How it differs from other namespaces?(N/D’09,
12. Give the possible operations on string objects.(N/D’09,
13. What is container? What are the three types of containers? Explain.
14. What is Standard Template Library? List the components of STL
15. List out and explain string functions in ANSI.(A/M’06)

PART-B
1. Explain multiple catch statement with help of suitable C++ coding. (M/J’07)
2. Explain how exception handling is achieved in C++. Give 3 different constructs and explain the working of
them. (A/M’08, N/D’11,M/J’12)
3. What are manipulators? Explain in detail various manipulators used for I/O operations with example.
(M/J’12, N/D’09,10,11
4. Discuss in detail about Standard Template Library. (M/J’12,
5. Using file handling methods of C++ write a program and explain how to merge the contents of two files into
one file.( N’09,10,11)
6. Explain in briefly about formatted and unformatted I/O operations with example.(N/D’10)
7. Explain the ANSI string objects with example.(A/M’05,08,11)
8. Explain the concept of random access in file and namespace. (M/J’07,05,A/M’06)

UNIT-4
Introduction to Java
 Java was invented by James Gosling at Sin micro systems in 1991.
 This language was initially called “Oak”&renamed as “Java” in 1995.
 Java must be at least one class present.
Java features:
UQ: List the features of java.(M/J’12), Explain the various features of Java in detail (N/D’11-10M)
1. Simple
2. Object oriented Syllabus:
3. Distributed UNIT IV
4. Multithreaded Introduction to JAVA , bytecode,
5. Dynamic virtual machines – objects – classes
6. Portable & Platform Independent
7. High performance
– Javadoc – packages –
8. Robust Arrays – Strings
9. Secure
1. Simple:
 Java is a simple programming language.
 Java like as C, C++ Language.
 But java there is not use Pointer, Structure & Union, Operator overloading, Virtual base class, go to statement.
2. Object Oriented:
 Java is a true Object Oriented language.
 The object model in java is simple & easy to extend.
3. Distributed:
 Java is designed as distributed language for creating applications on networks.
 This can be achieved by Remote Method Invocation (RMI).
4. Multithreaded:
 Multithreaded means handling multiple tasks simultaneously.
 This means that we need not wait for the application to finish one task before beginning another.
 Java supports multithreaded programs.
5. Dynamic:

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 Java is more dynamic language than C,C++.
 Libraries can freely add new method & instance variable without any effect.
6. Portable & Platform Independent:
1. Java programs can be executed on variety of systems.
2. Java ensures portability in two ways:
1. Java compiler generates bytecode instructions that can be implemented on any machine.
2. The sizes of primitive datatypes are machine independent.
7. High performance:
 The bytecode can be translated on the fly into machine code for particular CPU, the application is running
on.
8. Robust:
 It has strict compile time & run time checking for datatypes.
 It is designed as garbage collected language.
9. Secure: UQ: How is Java more secured than other languages? (M/J’13)
 Java enables construction of virus free, tamper free system.
 Reading or writing file without permission.
Difference between C++ and JAVA:
UQ: Can we write a JAVA program without class? Justify your answer. (N/D’10)
Sno. C++ JAVA
1. The C++ is platform dependent. Java is platform independent.
C++ does not support multithreading, Graphical User Java supports multithreading, Graphical User
2.
Interface (GUI), Scripting language. Interface (GUI), Scripting language.
Database handling using C++ is very complex. Java servlet can be created which can interact
3.
with the database.
C++ supports multiple inheritances, pointers, Java does not support multiple inheritances,
4.
Templates. pointers, Templates.
5. C++ we can write a program without a class. Java must be at least one class present.
6. C++ is simple to use & implement. JAVA is safe & more reliable.
7. C++ can be compiled with variety of compilers. Java can be compiled using unique compiler.

JAVA program structure: UQ: Give the JAVA program structure. (A/M’11)
Documentation section

Package statement

Import statement

Interface statement

Class definitions
Main method class
{
Main method definition
}
Simple JAVA program:
//Example simple java program
import java.io.*;
class Simple
{
public static void main(String args[])
{
System.out.println("It is simple JAVA Program");
}
}
Compilation & Output:

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
C:>javac Simple.java
C:>java Simple
It is simple JAVA Program

//Example another simple java program


import java.io.*;
class inside
{
void display()
{
System.out.println("It is simple JAVA Program");
}
}
class Simple
{
public static void main(String args[])
{
inside i=new inside();
i.display();
}
}
Compilation & Output:
C:>javac Simple.java
C:>java Simple
It is simple JAVA Program

UQ: Write a program to print the first n Armstrong numbers (accept n as command line argument) (N/D’11-
6M)
How will you access class members in JAVA? (A/M’11,-6M)
//Example java program for Armstrong Numbers
import java.io.*;
import java.io.DataInputStream;
class armstrongno
{
public static void main(String args[]) throws IOException
{
int r,max,i,j=1,m;
System.out.println("Program for Armstrong Numbers");
System.out.println("Enter the limit:");
try
{
DataInputStream din=new DataInputStream(System.in);
max=Integer.parseInt(din.readLine());
System.out.println("The Armstrong Numbers are:");
while(j<=max)
{
i=j;
m=0;
while(i>0)
{ OUTPUT:
r=i%10; Program for Armstrong
m=m+(r*r*r);
Numbers
i=i/10;
Enter the limit:
}
if(j==m) 500
System.out.println(j); The Armstrong Numbers are:
j++; 1
} 153
370
WWW.VIDYARTHIPLUS.COM 371 V+ TEAM
407
WWW.VIDYARTHIPLUS.COM
}
catch(IOException e)
{
System.out.println(e);
}
}
}
JAVA Tokens: UQ: List few tokens available with JAVA. (N/D’10)
 Smallest individual units in program are knows as tokens.
 Java language includes five types of tokens:
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
1. Keywords:
 Keywords are an essential port of language definition.
 Keywords are must be in lower case letters.
 Java language has reserved 50 words as keywords.
Some keywords:
final, extends, implements, package, import, super, interface, boolean, byte, native, etc,.
2. Identifiers: UQ: Enumerate the rules for creating identifiers in Java. (M/J’13)
 Identifiers are programmer-designed tokens.
 They are used for naming class, methods, variables, objects, labels, packages, interfaces of thee program.
Rules:
1. They can have alphabets, digits, underscored & dollar sign.
2. They must not begin with digit.
3. Upper case & lower case are distinct.
4. They can be any length.
3. Literals:
 Literals in java are sequence of characters that represent constant values.
 Java language specifies five major types of literals. They are:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
4. Operators: UQ: What are the various types of operators in JAVA? (A/M’11-4M)
 Operators are used in programs for manipulating data and variables.
 An operator performs a function on one, two, or three operands operates on them to produce a result.
 An operator that requires one operand is called a unary operator.
Example: ++ is a unary operator that increments the value of its operand by 1.
 An operator that requires two operands is a binary operator.
Example: = is a binary operator that assigns the value from its right-hand operand to its left-
hand operand.
 A ternary operator is one that requires three operands. The Java programming language has one
ternary operator ?:
 Types of operators:
1. Arithmetic operators (+,-,*,/,%)
2. Relational (<,>,<=,>=,==,!=)
3. Logical (&&,||,!)
4. Assignment (=)
5. Increment & decrement (++,--)
6. Conditional (?:)
7. Bitwise (&, |, !)
8. Special [.(dot), instance of]
5. Separators:

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 Separators are symbols used to indicate where groups of code are divided & arranged.
 Some separators:
1. Parentheses()--- for function
2. Braces{}--- for creating blocks
3. Brackets[]--- for array
4. Semicolon;--- for end of statement
5. Comma,--- separate the variables, objects…
Constants: UQ: Define constant in JAVA. (A/M’11)
Constants are referring to fixed values.
That does not change during the execution of program.
Types of constants:
1. Integer constants
2. Real (or) floating point constants
3. Character constants
4. String constants
Java virtual machine (JVM) UQ: What are JVM and JDK? (N/D’10, 11, M/J’12)
1. Java platform:
 A platform is the hardware or software environment in which a program runs.
 Operating system is called platform.
 The java platform is a software only platform that runs on other hardware based platforms.
Java platform components:
1. The Java virtual Machine (JVM)
2. The Java Application programming Interface (API)
Myprogram.java
Compiler Interpreter

Application Programming Java


Interface(API) Platform

Java Virtual Machine(JVM)


Hardware-based Platform
 Java virtual machine is a set of software & program components.
 It is virtual machine that can execute Java byte code.
 JVM is divided into several components:
1. Stack
2. Garbage collected heap
3. Registers
4. Method area

Program Counter Vars Frame Optop


(PC) Registers

Garbage
Method
Stack Collected
Heap Area

1. The stack
The stack is performing following functionalities:
I. Storing the local variables of the method.
II. Storing various arguments passed to the method.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
III. Keeps track of method being invoked.
2. Garbage collected heap:
 The memory for objects can be allocated from this heap area.
 When memory of these objects gets free, it is returned to this heap area.
 Java supports automatic garbage collection mechanism.
3. Registers:
 A stack performs manipulation of data with the help of vars, frame & optop.
 The vars-point to the local variable in the stack.
 Frame- the stack operations are pointed.
 Optop- point out the current byte code instruction.
4. Method area:
 This area stores the byte code of various methods.
 Using program counter (PC) JVM keeps track of the currently execution instruction.
 There can be multiple threads of a single process & all these threads can access the method area at a time.
Byte code:
 Bytecode is an intermediate form of java programs.
 Bytecode consists of optimized set of instructions that are not specific to processor.
 The bytecode is to be executed by Java Runtime Environment which is called Java Virtual Machine (JVM).
 JVM is also called Interpreter.
Java source Java Java Network
program compiler (or)
bytecode
filesystem

Bytecode JVM
Java Operating
byte code Verifier
System
Java Just In
Time (JIT)
compiler

 The programs that are running on JVM must be compiled into a binary format which is denoted by .class.
 Some times for easy of distribution multiple class files are packaged into one .jar file.
 The JVM executes it or using a Just-In-Time (JIT) compiler.
 It is used in most JVM’s today to achieve greater speed.
 The bytecode verifier verifies all the bytecode before it is executed.
 This verification helps to prevent the crashing of host machine.
Java Doc:
UQ: Explain about Java Doc in detail. (N/D’10-12M)
 Java doc is a standard way to document your java code.
 Java doc is a special format of comments.
 There are some utilities that read the comments & generate HTML document based on the comments.
 There are two types of comments:
1. Class level comments
2. Member level comments
 The java doc comments start with /** and end with */
Example:
/** This is java doc comment */
1. Class level comments:
 The class level comments provide the description and purpose of the classes.
Example:
/**
*@ author Kumar
* The employee class contains salary of each employee
*/
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
public class Employee
{
=// Employee class code
}
2. Member Level Comments
 The member level comments describe the data members, methods & constructors used in class.
 In this type of comments special tags are used to describe the things.
 The most commonly used tags:
Tags Description

@author The name of author who is writing the documents.


The name of the method used in the class (or) method’s
@param parameter

@return The return tag of the method (or) method’s return value

@throws The exception that can be thrown by the method

@exception The exception thrown by a method

Example:
/**
*@ author Kumar
* The Employee class contains salary of each employee
*/
class Employee
{
/**
*Employee info for knowing the salary
*/
private int amtsalary;
/**
*Constructor defined to initialise the salary
*/
Employee()
{
this.amtsalary=0;
}
/**
*This method returns the salary
*@ return integer value for salary
*/
public int get_salary()
{
return amtsalary;
}
/**
*@ param int no-of-days-worked
*@ param int payscale is for payment scale
*/
public void setsalary(int no_of_days_worked, int payscale)
{
this.amtsalary = no_of_days_worked*payscale;
System.out.println("Salary="+amtsalary);
}
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
public class EmpJavaDoc
{
public static void main(String args[])
{
Employee e=new Employee();
e.setsalary(10,4500);
}
}
OUTPUT:
L:\Programs>javac EmpJavaDoc.java

L:\Programs>java EmpJavaDoc
Salary=45000

L:\Programs>javadoc EmpJavaDoc.java
Loading source file EmpJavaDoc.java...
Constructing Javadoc information...
Standard Doclet version 1.7.0_02
Building tree for all the packages and classes...
Generating \EmpJavaDoc.html...
Generating \package-frame.html...
Generating \package-summary.html...
Generating \package-tree.html...
Generating \constant-values.html...
Building index for all the packages and classes...
Generating \overview-tree.html...
Generating \index-all.html...
Generating \deprecated-list.html...
Building index for all classes...
Generating \allclasses-frame.html...
Generating \allclasses-noframe.html...
Generating \index.html...
Generating \help-doc.html...

Along with the above mentioned tags some HTML tags can also be included in javadoc comments.

Data types: UQ: Write short notes on DataTypes in Java. (N/D’10-4M)


Describe various datatypes used in Java. Give examples. (M/J’13-16M)
 Datatypes specify the size and type of values that can be stored.
 The variety of data types available allow the programmer to select the type appropriate to needs of the
application.
 Data types divided into two major categories:
1. Primitive (or) Built-In Types
2. Derived (or) Reference Types Data types

Primitive Derived

Numeric Non-numeric Classes Interface Arrays

char Boolean
Int Floating Point

WWW.VIDYARTHIPLUS.COM V+ TEAM
byte Int
WWW.VIDYARTHIPLUS.COM

S.No Data type Size Example


1 Byte 1byte byte a=10;
2 Short 2bytes short b=1070;
3 Int 4bytes int c=32507;
4 Long 8bytes long d=343210;
5 Float 4bytes float e=34.75f;
6 double 8bytes double f=
7 Char 2bytes char g=’a’;
Command Line Arguments: UQ: What are the command line arguments? (A/M’11)
Command line arguments are parameters that are supplied to the application program at the time of invoking it
for execution.
Example:
Class comline
{
Public static void main (String args[])
{
int count=0;
count=args.length;
System.out.plintln (“Number of arguments”; count;
}
}
Wrapper class: UQ: What is wrapper class? (N/D’11)
 Wrapper classes are used to convert of primitive type into object of classes.
 So that they stored in collection classes such as Vector, List, Set, etc.
 Some of wrapper classes are Integer, Float, Character, Boolean, etc.
Scope of Variables UQ: How will you identify scope of variables in JAVA? (A/M’11)
Java variables are classified into three kinds:
1. Instance variables
2. Class variables
3. Local variables
Scope:
The area of the program where the variable is accessible is called Scope.
1. Instance variable:
They are created when the objects are instantiated & therefore they are associated with the objects.
They take different values for each object.
Rectangle
r1;
r=new rectangles
2. Class variables:
 They are global to a class & belong to the entire set of objects that class creates.
 Only one memory location is created for each class variable.
3. Local variables:
 They are declared & used inside methods can functions are called local variables.
 They are not available for outside of method definition.

{
Block-1
int a=10;
{
Block-2
=
int b=20;
WWW.VIDYARTHIPLUS.COM = V+ TEAM
}
WWW.VIDYARTHIPLUS.COM

JDK (Java Development Kit): UQ: What are JVM & JDK? (N/D’10, 11, M/J’12)
 Java environment includes a large number of development tools & hundreds of classes & methods.
 The development tools are part of the system known as Java Development Kit (JDK).
 JDK is a collection of tools that are used to developing & running java programs.
Widening Conversion UQ: What is meant by widening conversion? (N/D’10)
An automatic type conversion will take place if the following conditions are met:
1. The source & target types are compatible.
2. The destination type is larger than or equal to source type.
 When these two conditions met a widening conversion takes place.
 Widening conversion all numeric types are compatible with each other.
Example:
Byte bt=100;
Int x=bt;
Ternary Operators: UQ: What is the use of ternary operator? (N/D’10)
 It is also called as conditional operator.
 Symbol=> ? :
 Which can be thought of as short hand for if-else statement.
 It is also has three operands so that called ternary operator.
Ex:
Result = value<50? “fail” : “pass”;
Java Control Structures: UQ: Write the syntax & explain the various Java control & looping statements.
(N/D’11-6M)
 Programmers can take decisions in their program with help of control statements.
 Types of control statements:
1. Decision making (or) selection
2. Looping (or) Iteration
3. Branching (or) Jump
1. Decision making (or) Selection Statements:
Types of decision making Statements.
1. Simple if
2. If ….else
3. Nested if ….else
4. Switch case
1. Simple if:
If statement in which one or more statement is followed by this statement
Syntax:
if(condition)
Statement
Example:
If (a>b)
{
System.out.println (“A is big”)
}

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
2. If ….else:
 Given Condition is true execute the if block, condition is false execute the else block.
Syntax:
if(condition)
{
__
__
__ } statement-1
}
else
{
__
__
__} statement-2
}
Example:
if(a>b)
{
System.out.println(“A is big”);
}
else
{
System.out.println(“B is big”);
}
3. Nested if …. Else Statement:
A if ….else is have one or more if…else statement ….is called nested if….else statement.
if(condition1)
{
if(condition 2)
{
Statement2
}
else
{
Statement3
}
}
else
{
Statement 4
}

Example:
if(a>b)
if(a>c)
System.out.println(“A is big”);
else
if(b>c)
System.out.Println(“B is big”);
else
System.out.println(“c is big”);
else
System.out.println(“B is big”);
4. switch case statement:
 The switch statement is multiway branch statement.
 It provides select the operation with the proper condition.
 In the switch – case statement has the “break” statement.
 This break statement used to break the each set of operation.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
Syntax:
switch (expression)
{
case value1:
Statement-1;
break;
case value2:
Statement-2;
break;
default:
Statements;
break;
}
2. Looping (or) Iteration statements
 Iteration (or) Looping statements enable program execution to repeat one or more statements.
 These statements repeatly execute the same set of instructions until a termination the condition.
 Java’s Looping Statements are:
1. While
2. Do-while
3. For
1. While statement:
 The while loop is most fundamental looping statement.
 It repeats a statement (or) block while its controlling expression is true.
 It has the only condition checking expression.
Syntax:
While (condition)
{
___
___ / / body of the loop
}
2. Do-while statement:
 There is only difference b/w while & do-while that while loop first evaluates the condition and if it is true
then only the program enters into the loop. In case of do-while will enter into the loop without evaluating
condition for the first time.
Syntax:
do
{
___
___
}while (condition);
3. For:
There are three portion is used. Those are initialization, conditional checking, and Increment/decrement
operation.
Syntax:
for (i=0; i<=n; i++)
{
}
4. Jump statement:
 These statements transfer control to another part of the program.
 These statements are: break, continue, and return.
(i) Break:
The break statement has two uses:
1. It terminates a statement
2. It can be used to exit a loop.
(ii) Continue:
Some of the code not execute in the program just jump the line of codes.
(iii) return:
1. It is returns from the method.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
2. Control is returned back to the caller of the method.
Packages: UQ: What do you mean by package in JAVA? (N/D’10, A/M’11)
Explain how to design a Java package with an example. Explain about Java API packages. (A/M’11, N/D’10,
11, 12, M/J’12, 13-16M)
 Packages are container for classes.
 Java classes can be grouped into the packages.
 The package name must be the same as the directory (or) folder name.
 The name of the package should be written as the first statement in program.
 Java program can import the system packages.
 Package can create with keyword “package”.
Benefits:
 The packages of other programs can be easily reused.
 In packages, classes can be unique compared with classes in other packages.
 Packages provide a way to “hide” classes.
 Packages also provide a way for separating “design” from “coding”.
Syntax:
package name-of-the-package;
Multiple hierarchies of packages:
package pkg1.Pkg2.pkg3;
Steps for creating a package:
Step1: The above program create saved as file name “Balance.java”
Step2: The file must store in the folder “mypack” as the package name.
Step3: Compile the program “C: /jdk1.40/mypack>javac Balance.java”.
Step4: Now create other java file outside of the package directory.
Step5: Import the package in our java program like as “import mypack.Balance.*;”.
Step6: Compile the java program like as “javac Account.java”.
Step7: Run the java program like as “java Account”.

Example:
Package Program:
package mypack;
public class Balance
{
String name;
float bal;
public Balance (string n, float f))
{
name = n;
bal = b;
}
public void show ()
{
System.out.println(name+”:Rs.”+bal);
}
}

Main Program:
import mypack.Balance.*;
class Account
{
public static void main (String args[])
}
Balance a1= new Balance (“Senthil”,2000.00);
Balance b1= new Balance (“Kumar”, 500.00);
a1.show();
b1.show();
}
}

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
OUTPUT
Senthil: Rs.2000.00
Kumar: Rs.500.00

Another Example:
I ) Package student
package student;
public class ClassA
{
public int rollno;
public String name;
public ClassA(int rl,String nl)
{
rollno=rl;
name=nl;
}
public void displayA()
{
System.out.println("Roll Number : "+rollno);
System.out.println("Name :"+name);
}
}
Output:
E:\j2sdk l.4\bin\student>javac ClassA.java
II) Package college:
package college;
public class ClassB
{
public int mark1;
public int mark2;
public ClassB(int m1,int m2)
{
mark1=m1;
mark2=m2;
}
public void displayB()
{
System.out.println("Mark 1 :"+mark1);
System.out.println("Mark 2 :"+mark2);
}
}
OUTPUT:
E:\j2sdk l.4\bin\college>javac ClassB.java
Import the Packages College and student
import student.ClassA;
import college.ClassB;
class PackageTest
{
public static void main(String args[])
{
int total;
ClassA objectA=new ClassA(1001,"Raja");
ClassB objectB=new ClassB(90,100);
total=objectB.mark1+objectB.mark2;
objectA.displayA();
objectB.displayB();
System.out.println(" Total: "+total);
}
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM

OUTPUT:
E:\j2sdk l.4\bin>javac PackageTest.java
E:\j2sdk l.4\bin>java PackageTest

Roll Number :1001


Name :Raja
Mark 1: 90
Mark 2: 100
Total: 190

Java API or Core packages:


 Various classes and interfaces from java library packages using the import statement.
 The specific class that needs to be used in our program from a particular package then it can be mentioned
in import statement.
For example-
 Specify it as import java.net.*;
 Here*means all the classes from java.net package.
 Some of the useful packages are enlisted as below:
1. Java.io
2. Java.net
3. Java.lang
4. Java.util
5. Java.awt
6. Java.applet
Java.io
 This package provides useful functionalities for performing input and output operations through data
streams or through file system.
Java.net
 This package is for providing the useful classes and interfaces for networking applications which are
used in sockets and URL.
Java.lang
 This package provides core classes and interfaces used in design of Java language.
Java.util
 Some commonly used utilities are random number generation, event model, date and time facilities,
system properties are stored in util package.
Java.awt
 This package contains all the interfaces and classes that are required for creating the graphical user
interface (GUI).
Java.applet
 The java.applet package contains all necessary classes and interfaces are required for handling
applets.
Constructor: UQ: Construct a class with constructor in JAVA to print a pay slip of an employee. (A/M’11-8M)
 Constructor is a special member function.
 It is used to initialize the variables.
 Class name and function name are same.
 Constructor automatically called whenever object is created.
Types of Constructor:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Multiple Constructor or Constructor Overloading
1) Default constructor:
 Default constructor is the basic constructor.
 It is non parameterized constructor.
 It just initializes the variables.
Syntax:

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
class classname
{
classname()
{
__
__
}
};
2) Parameterized constructor:
 Passing arguments (or) parameters to the constructor function when the object is created.
 The constructors that can take arguments (or) parameters are called “Parameterized
constructor”.
 We can call the Parameterized constructor using two ways:
i. Implicit calling
ii. Explicit calling
Syntax:
iii) Implicit calling:
classname objectname(args);
iv) Explicit calling:
classname objectname=classname(args);

3) Copy constructor:
 Copy constructor is used to declare and initialize an object from another object.
 The process of initializing through a Copy constructor is known “copy initialization”
 Send object as parameter.
Syntax:
classname object1;
classname object2(object1);//Implicit passing
classname object3=object2;//Explicit passing
4) Multiple Constructor or Constructor Overloading:
 Any program having more than one constructor (Default, Parameterized, Copy constructor) is
called multiple constructors or Constructor Overloading.

Example:
//Example for Default, Parameterized, Copy, Multiple Constructor and Constructor Overloading
import java.io.*;
class consr
{
int length, breath;
consr()//Default Constructor
{
length=10;
breath=20;
}
consr(int l, int b)//Parameterized Constructor
{
length=l;
breath=b;
}
consr(consr s)//Copy Constructor
{
length=s.length;
breath=s.breath;
}
void function()
{
System.out.println("\n Length = "+length + " Breath = "+breath);
System.out.println("\n The Area of the Rectangle="+(length*breath));

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
System.out.println("\n The Perimeter of the Rectangle="+(2*(length+breath)));
}
}
class constructor
{
public static void main(String args[])
{
consr defaut= new consr();
consr parameter=new consr(30,40);
consr copy=new consr(parameter);
System.out.println("\n <=========== Default Constructor =========>");
defaut.function();
System.out.println("\n <=========== Parameterized Constructor =========>");
parameter.function();
System.out.println("\n <=========== Copy Constructor =========>");
parameter.function();
}
}
Output:
G:\KARTHI\JAVA>java constructor
<=========== Default Constructor =========>
Length = 10 Breath = 20
The Area of the Rectangle=200
The Perimeter of the Rectangle=60
<=========== Parameterized Constructor =========>
Length = 30 Breath = 40
The Area of the Rectangle=1200

The Perimeter of the Rectangle=140


<=========== Copy Constructor =========>
Length = 30 Breath = 40
The Area of the Rectangle=1200
The Perimeter of the Rectangle=140
G:\KARTHI\JAVA>
Static members: UQ: Explain the use of static members in java. (M/J’12-6M)
 Static variables are used when we want to have a variable common to all instances of a class.
 Java creates only one copy for a Static variable which can be used even if the class is never actually instantiated.
 Static methods can be caused without using the objects.
 They are also available for use by other classes.
Restrictions:
1. They can only call other static methods.
2. They can only access static data.
3. They cannot refer to this (or) super in any way.
Example:
class mathoperation
{
static float mul(float x, float y)
{
return x*y;
}
static float div (float x, float y)
{
return x/y;
}
}
class mathapplication
{
public static void main(String args [])

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
{
float a=mathoperation.mul(4.0,5.0);
float b=mathoperation.div(a,2.0);
System.out.println (“b=”+b);
}}
Arrays:
UQ: How will you define a two-dimensional array in JAVA? (A/M’11)
Write a program and explain about Arrays to perform matrix multiplication using array. (A/M’11,N/D’11,12-
16M)
 Array is a collection of similar type of elements.
 Thus grouping of similar kind of elements is possible using arrays.
 The individual values are called elements.
 Typically arrays are written along with size of them.
Syntax:
Datatype array-name[]=new datatype[size];
Example:
Int a []=new int[5];
 Array name represent name of the array
 ”new” keyword is used to allocate the memory for arrays.
 datatype specifies type of data array elements.
 size represent the size of
2 3 7 10 5 the array.
a[0]=2 a[1]=3 a[2]=7 a[3]=10
a[4]=5

Initialization of arrays:
 The values put into the array created. This process is known as initialization.
Syntax:
Datatype arrayname[]= {List of values};
Example:
int a[]= {10,20,30,40,50};
Types of arrays:
 One dimensional Array
 Two dimensional Array

One Dimensional Array:


 A list of items can be given one variable name using only one Subscript is called one dimensional
Array.
Example:
Int a[]= new int [10];
Two Dimensional Arrays:
 There will be situations where a table of values will have to be stored.
 Table as a matrix consisting of rows & columns.
 Java allows us to define such tables of items by using two-dimensional arrays.
Syntax:
int myarray [] []= new int [3] [4];
Example:
//Example Matrix Multiplication for Arrays
import java.io.*;
public class matrix_array
{
public static void main(String args []) throws IOException
{
int i,j;
int a[][] = {{10,20,30},{40,50,60},{70,80,90}};
int b[][] = {{1,2,3},{4,5,6},{7,8,9}};
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
int c[][] =new int[3][3];
char choice;
System.out.println("Main menu \n1.Addition \n2.Substraction \n3.Multiplication \nEnter your choice:");
choice = (char)System.in.read();
switch (choice) OUTPUT:
{ Main Menu:
case '1': 1. Addition
for(i=0;i<3;i++) 2. Subtraction
for(j=0;j<3;j++) 3. Multiplication
c[i][j]= a[i][j]+b[i][j];
System.out.println("The Addition:"); Enter your choice:
for(i=0;i<3;i++) The addition:1
{ 11 22 33
for (j=0; j<3; j++) 44 55 66
System.out.print(c[i][j]+" "); 77 88 99
System.out.println(); Enter your choice:2
} The subtraction:
break; 9 18 27
case '2': 36 45 54
for(i=0;i<3;i++) 63 72 81
for(j=0;j<3;j++) Enter your choice:3
c[i][j]= a[i][j]-b[i][j]; The Multiplication:
System.out.println("The Substraction:"); 10 40 90
160 250 360
for(i=0;i<3;i++)
490 640 810
{
for(j=0;j<3;j++)
System.out.print(c[i][j]+" ");
System.out.println();
}
break;
case '3':
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]= a[i][j]*b[i][j];
System.out.println("The Multiplication:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print(c[i][j]+" ");
System.out.println();
}
break;
}
}
}
Final Variable, methods & classes
UQ: When do we declare a method or a class as Final? (N/D’10, 12)
Explain Final variable, methods and class. (N/D’12-8M, M/J’12-8M)
(i) Final variable:
 All methods & variables can be overridden by default in subclasses.
 To prevent the subclasses from overriding the members of the superclass.
 Declare them as final using the keyword “final” as a modifier.
 The value of final variable can never be charged. (constant)
Example:
final int SIZE = 100;
(ii) Final method:
Making a method final ensures that the functioning defined in this method will never be altered in any way.
Example:

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
final void show ()
{
__
__
}
(iii) Final classes:
 Sometimes to prevent a class being further sub classes for security reasons.
 A class that cannot be subclassed is called a final class.
 This is achieved in java using the keyword “final”.
Example:
final class A class
{
__
__
}
final class B extends some class
{
__
__
__
__
}
(iv) Finalizer Methods:
 A constructor method is used to initialize an object when it is declared.
 Java Supports a concept called finalization, which is just Opposite to initialization.
 Java is an automatic garbage collection system. It automatically frees up the memory resources used by the
objects.
 But objects may hold other non-object resources such as file descriptors (or) system fonts.
 The garbage collector cannot free these resources.
 In order to free these resources we must use a “finalizer” method.
 The finalizer method simply “finalize()” & and can be added to any class.
Strings:
UQ: List any four string functions. How does Java handle strings? (A/M’11, M/J’12,13)
Write a Java program to add, compare and find the length of an input string. (A/M’10,11-6M,N/D’10-
8M)
 String is a collection of characters.
 In java strings are class Objects & implemented using two classes:
1. String 2. String Butter.
 A java string is an instantiated object of the string class.
Syntax: String name=new String(“Senthil”);
String Arrays:
 We can also create & use arrays that contains Strings.
Example: String strArrays[]=new Sting [3];
 StrArray of size 3 to hold three strings constants.
 We can assign the strings to the strArray element by element using “for” loop.
 The string class defines a number of methods that allow us to accomplish a variety of string manipulation
tasks.
 Some of the most commonly used string methods:
Methods Description
1) S2=S1.ToLowercase; Converts to lower case.
2) S2=S1.ToUppercase; Converts to upper case.
3) S2=S1.Toreplace(‘x’,’y’); Replace all x with y.
4) S2=S1.trim(); Remove white spaces.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
5) S1.equals(S2) Returns ‘true’ if S, equal to S2.
6) S1.length() Gives the length.
7) S1.charAt(n) Gives nth character.
8) S1.compareTo(S2) Returns –ve if S1<S2, +ve if S1>S2, Zero S1=S2.
9) S1.substring(n,m) Giving substring starting nth char to upto mth char.
10) S1.concat (S2) Join the two strings.
11) P.toString() String representation of object P.
Example:
// Program to add, compare & find length of the string
public class Demostring
{
OUTPUT:
public static void main(String args[]) D:\Javapgms>java Demostring
{ S1=Senthil
String S1=new String ("Senthil"); S2=Kumar
String S2=new String ("Kumar"); S1 greater than S2
System.out.println("S1="+S1+"\nS2="+S2); S1=Senthil
if(S1.compareTo(S2)==0) Length:7
System.out.println("S1&S2 are equal"); S2=Kumar
else if(S1.compareTo(S2)<0) Length: 5
System.out.println("S1 Smaller than S2"); After joining two strings: SenthilKumar
else
System.out.println("S1 greater than S2");
System.out.println("S1="+S1+"\nLength:"+S1.length()+"\n S2="+S2+"\n Length: "+S2.length());
S2=S1.concat(S2);
System.out.println("After joining two strings: "+S2);
}
}
Vectors:
UQ: Define vectors. What is the advantage of vector over arrays? (M/J’12, N/D’12)
What is Vector? How it is created? Explain few methods available in Vector. (N/D’11-8M)
 The vector class contained in the java.util package.
 This class can be used to create a generic dynamic array.
 Vector that can hold objects of any type and any number.
 The objects do not have to be homogeneous.
 Arrays can be easily implemented as vectors.
Vector int Vect=new Vector(); // declaring without size
Vector list =new Vector (3); // declaring with size.
Advantages:
1. It is convenient to use vectors to store objects.
2. A vector can be used to store a list of objects that may vary in size.
3. We can add & delete objects from the list.
Some methods:
list.size()
List.add Element (item)
List.element At (10)
List.remove Element (item)
List.insert Element (item,n).
University Questions:
PART-A
1.List the features of java.(M/J’12)
2.How will you define a two-dimensional array in JAVA? (A/M’11)
3.JAVA is free form language. Comment. (N/D’12)
4.When do we declare a method or a class as Final? (N/D’10, 12)

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
5.Write a program to count the number of objects created from a class. (M/J’12)
6.How is Java more secured than other languages? (M/J’13)
7.Can we write a JAVA program without class? Justify your answer. (N/D’10)
8.Give the JAVA program structure. (A/M’11)
9.List few tokens available with JAVA. (N/D’10)
10.List any four string functions. How does Java handle strings? (A/M’11, M/J’12,13)
11.Enumerate the rules for creating identifiers in Java. (M/J’13)
12.What are the various types of operators in JAVA? (A/M’11-4M)
13.Define constant in JAVA. (A/M’11)
14.What are JVM and JDK? (N/D’10, 11, M/J’12)
15.What are the command line arguments? (A/M’11)
16.What is wrapper class? (N/D’11)
17.How will you identify scope of variables in JAVA? (A/M’11)
18.What are JVM & JDK? (N/D’10, 11, M/J’12)
19.What is meant by widening conversion? (N/D’10)
20.What is the use of ternary operator? (N/D’10)
21.Define vectors. What is the advantage of vector over arrays? (M/J’12, N/D’12)
22.What do you mean by package in JAVA? (N/D’10, A/M’11)

PART-B
1.Explain the various features of Java in detail (N/D’11-10M)
2.Write a program to print the first n Armstrong numbers (accept n as command line argument) (N/D’11-6M)
3.How will you access class members in JAVA? (N/D’12-8M, A/M’11,-6M)
4.Explain about Java Doc in detail. (N/D’10-12M)
5.Describe various datatypes used in Java. Give examples. (N/D’10-4M, M/J’13-16M)
6.Explain how to design a Java package with an example. Explain about Java API packages. (A/M’11, N/D’10,
11, 12, M/J’12, 13-16M)
7.Construct a class with constructor in JAVA to print a pay slip of an employee. (A/M’11-8M)
8.Explain the use of static members in java. (M/J’12-6M)
9.Write a program and explain about Arrays to perform matrix multiplication using array.
(A/M’11,N/D’11,12-16M)
10.Explain Final variable, methods and class. (N/D’12-8M, M/J’12-8M)
11.Write a Java program to add, compare and find the length of an input string. (A/M’10,11-6M,N/D’10-8M)
12.What is Vector? How it is created? Explain few methods available in Vector. (N/D’11)
13.Write the syntax & explain the various Java control & looping statements. (N/D’11-6M)

UNIT-5
Inheritance
UQ: Describe different forms of inheritance with example. (M/J’13-16M)
 Inheritance is one of important features of OOP.
 Add some properties in existing class is called inheritance.
 A new class derived from the existing class.
 The inheritance can be achieved by incorporating the definition of one class into another, using the keyword
“extends”.
 It is mainly used for reusability.
Syntax:
class class-name1
Syllabus:
{
UNIT V
__
__ Inheritance – interfaces and inner
} classes - exception handling – threads -
class class-name2 extends class-name1 Streams and I/O
{
__
__

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
}
Types of Inheritance:
(1) Single Inheritance
(2) Multilevel Inheritance
(3)Hierarchical Inheritance
(4)Multiple Inheritance.
(5)Hybrid Inheritance
New class- sub class, derived class, child class.
Existing class- super class, base class, parent class.
(1)Single Inheritance: A
 It contains only one super class, and sub class.
 The sub class is specialized for adding some properties.
Syntax: B
class class-name1
{
__
__
}
class class-name2 extends class name1.
{
__
__
}
(2)Multilevel Inheritance:
 A new class derived from existing class from that class derived new class is called multilevel Inheritance.
 In multilevel inheritance there is one super class, one intermediate class, and one derived (or) sub class.
 This act as relationship:
Grandfather Father Son
Syntax:
class A
{ ADD
__ A
__
__
}
SUB B
class B extends A
{
__
__ MUL C
}
class C extends B
{
__
__
}

3) Hierarchical Inheritance:
 This type of inheritance shares the information to other classes.
 That means one super class, many sub class in this inheritance.
 Hierarchy is followed one head other classes are labor.
 In this inheritance some problem will occur.
 So that we can use abstract class as “Super class”.
Syntax:
class A
{ MUL
A
__
__

WWW.VIDYARTHIPLUS.COM V+ TEAM
B C DIV MOD
WWW.VIDYARTHIPLUS.COM
}
class B extends A
{
__
__
}
class C extends A
{
__
__
}
(4)Multiple Inheritances:
UQ: Which type of inheritance is not allowed in java? What is the equivalent representation? Explain with
example. (A/M’10)
 In java cannot perform the multiple Inheritance directly.
 The process of creating one sub class from more than one super class is called multiple inheritance.
 We can avoid this problem using “Interfaces”.

(5)Hybrid Inheritance:
 The process of combining more than one inheritance (single, multi level, Hierarchical) in classes is called
Hybrid inheritance.

EXAMPLE:
// Example for Inheritance (Single, Multilevel, Hierarchical and Hybrid Inheritance)
import java.io.*;
class ADD
{
int a,b,c;
public void add_op()
{
a=10;b=5;
c=a+b; OUTPUT:
System.out.println("ADD="+c);
} ADD=15
} SUB=10
class SUB extends ADD //Single Inheritance MUL=50
{
int d,e;
DIV=10
public void sub_op() MOD=0
{
d=5;
e=c-d;
System.out.println("SUB="+e);
}
}
class MUL extends SUB //Multilevel Inheritance
{
int f,g;
public void mul_op()
ADD
{ Single
f=5; Inheritance
g=e*f;
Multilevel
System.out.println("MUL="+g); SUB Inheritance
}
}
class DIV extends MUL
MUL
Hierarchical
Inheritance

{
int h,i;

WWW.VIDYARTHIPLUS.COM DIV MOD V+ TEAM


WWW.VIDYARTHIPLUS.COM
public void div_op()
{
h=5;
i=g/h;
System.out.println("DIV="+i);
}
}
class MOD extends MUL
{
int j,k;
public void mod_op()
{
j=5;
k=g%j;
System.out.println("MOD="+k);
}
}
public class Arith_Inherit
{
public static void main(String args[])
{
DIV d=new DIV();
MOD m=new MOD();
d.add_op();
d.sub_op();
d.mul_op();
d.div_op();
m.mod_op();
}
}

Abstract methods & classes:


UQ: Abstract methods and classes in detail. (M/J’12-8M)
 A method must always be redefined in a sub class, thus making Overriding.
 This is done using the modifier keyword “abstract” in the method definition.
Syntax:
abstract class shape
{
__
__
abstract void draw ();
__
__
}
 When a class contains one or more abstract methods, it should also be declared abstract class.
Conditions:
(1) Cannot use abstract classes to instantiate objects directly.
Ex: Shape S=new shape ();
(2) The abstract methods of an abstract class must be defined in its subclass.
(3) Cannot declare abstract constructors (or) abstract static methods.

Abstract Class Class A

Abstract function Fun1()


Fun2()

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM

Example:
abstract class A
{
abstract void fun1();
void fun2()
{
System.out.println("class A");
}
}
class B extends A
{
void fun1()
{
System.out.println("class B"); OUTPUT:
} Class B
}
class C extends A Class A
{ Class C
void fun1()
{ Class A
System.out.println("class C");
}
}
public class abstract_Demo
{
public static void main(String args [])
{
B b=new B();
C c=new C();
b.fun1(); b.fun2();
c.fun1(); c.fun2();
}
}
Interfaces:
UQ: How Java achieves multiple inheritance? (N/D’11)
How are interfaces different from classes? (N/D’11)
What is an interface in JAVA? (A/M’11, N/D’10)
Explain about the defining extending and implementation of interfaces in java. (M/J’12-8M)
Explain how interfaces are used to achieve multiple. (N/D’11-10M)
Give an example where interface can be used to support multiple inheritances. Develop a standalone Java
program for the example. (M/J’13-16M)
 Java does not support multiple inheritance.
 That is classes in java cannot have more than one super class.
Class A extends B extends C // is not permitted in java
{
__
__
}
 Java provides an alternate approach known as “interfaces” to support the concept of multiple inheritance.

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 Java class cannot be a subclass of more than one super class, it can implement more than one interface.
Defining Interface:
 An interface is basically a kind of class.
 Like classes, interfaces contain methods & variables but with major difference.
 Interface define only abstract methods & final fields.
 This means that interfaces do not specify any code to implement these methods & data fields contain only
constant.
Syntax:
interface interfaceName
{
static final datatype variableName=value;
datatype MethodName (Parameters);
}
 All variable are declared as constants.
 List of methods without anybody statements.
Example:
//Example for Interface and Multiple Inheritance
class student
{ STUDENT SPORTS
int rollno,mark1,mark2;
void get_details(int rno,int m1,int m2)
{
rollno=rno; RESULTS
mark1=m1;
mark2=m2;
}
void put_details()
{
System.out.println("Student Details"); OUTPUT:
System.out.println("RollNo="+rollno); Interface & Multiple Inheritance
System.out.println("Mark1="+mark1); ----------------------------------
System.out.println("Mark2="+mark2); Student Details
} RollNo=1234
Mark1=57
} Mark2=75
interface sports //Interface Creation Sports Wt=7
{ Total=139
final int sportwt=7;
void putwt();
}
class Results extends student implements sports //Interface Implementation
{
int total;
public void putwt()
{
System.out.println("Sports Wt="+sportwt);
}
void display()
{
total=mark1+mark2+sportwt;
put_details();
putwt();
System.out.println("Total="+total);
}
}
class MultipleInheritance
{
public static void main(String args[])
{

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
System.out.println("Example for Interface and Multiple Inheritance");
System.out.println("----------------------------------------------");
Results r1=new Results();
r1.get_details(1234,57,75);
r1.display();
}

Class Interface
The members can be constant or variable. The members are always as constant.
The method can be abstract (or) non abstract. The methods are abstract methods.
It can be instantiated by declaring objects. It cannot be used declare objects. It inherited by a class.
It can use various access specifiers. It can use only public access specifier.
}
Difference between Class & Interface
Difference b/w Abstract Class & Interfaces
UQ: What is the major difference between an interface and abstract class? (N/D’12, M/J’13)
Abstract Class Interfaces
1)The variables are declared by using datatypes. 1)The variables must be final.
2)Methods are declared along with the datatypes. 2)Methods are public abstract methods.
3)Constructors can invoked by the sub classes. 3)There is no constructor defined.
Overriding:
UQ: Explain with example, method overriding in java. (A/M’10)
 Method Overriding is a mechanism in which a subclass inherits the methods of super class.
 Sometimes the subclass modifies the implementation of method defined in superclass.
 The Overridden method must be called from subclass.
 The function called in subclass using “Super” keyword.
Ex:
Super.method name();
Example:
//Example for Overriding
class A OUTPUT:
{
void fun() Class A
{
Class B
System.out.println("Class A");
}
}
class B extends A
{
void fun()
{
super.fun();
System.out.println("Class B");
}
}
class overridingtest
{
public static void main(String args[])
{
B b=new B();
b.fun();
}
}
Overloading:
UQ: Differentiate method overloading & overriding in java. (M/J’12-4M)
What is method overloading in java? (A/M’10)

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 Overloading is a mechanism in which we can use many methods having the same name but number of
parameters may be different (or) different datatypes of parameters.
Syntax:
functionname(datatype variablename);
functionname(datatype variablename1,datatype variablename2);
Example:
//Example for Function Overloading
class overloadingDemo
{ OUTPUT:
public static void main(String args[]) Example for Function Overloading
{ -------------------------------------------
System.out.println("Example for Function Overloading"); Sum of two Integers
System.out.println("--------------------------------");
Sum=30
System.out.println("Sum of two Integers");
Sum of three Integers
sum(10,20);
System.out.println("Sum of three Integers"); Sum=60
sum(10,20,30); Sum of two Floats
System.out.println("Sum of two Floats"); Sum=13.1
sum(5.6f,7.5f);
}
public static void sum(int a,int b)
{
System.out.println("Sum="+(a+b));
}
public static void sum(int a,int b,int c)
{
System.out.println("Sum="+(a+b+c));
}
public static void sum(float a,float b)
{
System.out.println("Sum="+(a+b));
}}
Error:
Error is common to make mistakes while developing as well as typing a program.
Types of Errors:
1. Compile-time Errors
2. Run-time Errors
1. Compile-time Error:
 All syntax errors will be detected and displayed by the compiler; these errors are called compile-time
errors.
 These errors due to typing mistakes.
o Most common compile-time errors are:
 Missing semicolon.
 Missing brackets in classes and methods.
 Misspelling of identifiers and keywords.
 Missing double quotes in strings.
 Use of undeclared variables.
 Incompatible types in assignment or initialization
 Bad references to objects.
 Use of = in place of == operator.

2. Run-Time Errors
 Sometimes, a program may compile successfully creating the .class file but may not run properly.
 Such programs may produce wrong results due to wrong logic or may terminate due to errors such as stack
overflow.
Most common run-time errors are:
 Dividing an integer by zero
 Accessing an element that is out of the bounds of an array

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 Trying to store a value into an array of an incompatible class or type
 Trying to cast an instance of a class to one of its subclasses
 Passing a parameter that is not in a valid range or value for a method
 Trying to illegally change the state of a thread
 Attempting to use a negative size for an array
 Converting invalid string to a number
 Accessing a character that is out of bounds of a string
Exceptions
 Exception in Java is an indication of some unusual event.
 Usually it indicates the run-time error.
Exception Handling:
 The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional
circumstance” so that appropriate action can be taken.
Tasks:
1. Find the problem (Hit the exception).
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
Exceptions fall into two categories:
 Checked Exceptions
 Unchecked Exceptions
 Checked exceptions: these exceptions are explicitly handled in the code itself with the help of try-catch
blocks. Checked exceptions are extended from the java.lang.Exception class.
 Unchecked exceptions: these exceptions are not essentially handled in the program code; instead the JVM
handles such exceptions. Unchecked exceptions are extended from the java.lang.Runtime Exception class.
 It is important to note that checked and unchecked exceptions are absolutely similar as far as their functional
is concerned; the difference lies only in the way they are handled.

Blocks and Keywords:


In Java, exception is handled using five keywords:
try, catch, throw, throws and finally.
try Block
Exception
object creator Statement that caused
an exception

WWW.VIDYARTHIPLUS.COM V+ TEAM
catch Block
WWW.VIDYARTHIPLUS.COM

try block:
 The try block can have one or more statements that could generate an exception.
catch block:
 A catch block defined by the keyword “catch” catches the exception “thrown” by the try block and handles it
appropriately.
 If anyone statement generates an exception, the remaining statements in the block are skipped and execution
jumps to the catch block that us placed next to the try block.
 The catch block too can have one or more statements that are necessary to process the exception. Remember that
every try statement should be followed by at least one catch statement; otherwise compilation error will occur.
 If the catch parameter matches with the type of exception object, then the exception is caught and statements in
the catch block will be executed.
finally block:
UQ: Explain the use of the keyword ‘finally’ in java? (A/M’10)
o Java supports another statement known as finally statements that can be used to handle an exception that is not
caught by any of the previous catch statements.
o Finally block can be used to handle any exception generated within a try block.
o It may be added immediately after the try block or after the last catch block.
throw block:
 Java uses a keyword try to preface a block of code that is likely to cause an error condition and “throw” an
exception.
throws block:
 When a method wants to throw an exception then keyword throws is used.
The syntax is-
Method-name(parameter-list)throws exception-list
{……..}
Types of Exceptions:
Exception Description
ArithmeticException Used for representing arithmetic exceptions. For e.g.Divide by zero.
NullPointerException Attempts to access an object with a Null reference.
IOException When an illegal input/output operation is performed then this
exception is raised.
IndexOutOfBoundsException Array index when gets out of bound, this exception will be caused.
ArrayIndexOutOfBoundsException Array index when gets out of bound, this exception will be caused.
ArrayStoreException When a wrong object is stored in an array this exception must
occur.
EmptyStackException An attempt to pop the element from empty stack

NumberFormatException When we try to convert an invalid string to number this exception


gets caused.
RuntimeException To show general run time error this exception must be raised.
Exception This is the most general type of exception.
Rules:
1. There should be some preceding try block for catch or finally block. Only catch block or only finally block
without preceding try block is not at all possible.
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
2. There can be zero or more catch blocks for each try block but there must be single finally block present at
the end.
Syntax:
try
{
Statement; //generates an exception
}
catch (Exception-type e)
{
Statement; //processes the exception
}
finally
{
Statement; //after processes the exception
}
Example:
//Program for Exception Handling in JAVA
import java.io.*;
import java.util.*;
class ExceptionProg
{
public static void main (String args[])
{
int a[]={10,5};
int c,b=5,d=0,e;
char choice='q';
DataInputStream din=new DataInputStream(System.in);
try
{
System.out.println("Example for Exception");
System.out.println("1.Arithmetic Exception\n2.Array IndexOutof Bound\n3.throw block");
System.out.println("4.throws block\n5.IOException");
System.out.print("Choose your option:");
choice=(char)din.read();
switch(choice)
{
case '1':
try
{
e=b/d;
System.out.println("In Arithmetic Exception");
}
catch(ArithmeticException e1)//ArithmeticException
{
System.out.println("Caught exception: "+e1);
}
finally
{
System.out.println("This is finally of ArithmeticException");
}
break;
case '2':
try
{
c=a[0]/a[2];
}
catch(ArrayIndexOutOfBoundsException e2)//ArrayIndexOutOfBoundsException
{
System.out.println("Caught exception: "+e2);
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
}
finally
{
System.out.println("This is finally of ArrayIndexOutOfBoundsException");
}
break;
case '3':
try
{
throw new Exception("Exception occur");//throw the Exception
}
catch(Exception ea)
{
System.out.println("Caught exception: "+ea);
}
break;
case '4':
try
{
fun1();
}
catch(IllegalAccessException my)
{
System.out.println("Caught exception: "+my);
}
break;
}
}
catch(IOException e3) //IOException
{
System.out.println("Caught exception: "+e3);
}
}
static void fun1()throws IllegalAccessException//throws the Exception
{
throw new IllegalAccessException("Some Operation");
} OUTPUT:
} D:\Javapgms>java ExceptionProg
Example for Exception
1.Arithmetic Exception
2.Array IndexOutof Bound
3.throw block
4.throws block
5.IOException
Choose your option:1
Caught exception: java.lang.ArithmeticException: / by zero
This is finally of ArithmeticException
Choose your option:2
Caught exception: java.lang.ArrayIndexOutOfBoundsException: 2
This is finally of ArrayIndexOutOfBoundsException
Choose your option:3
Caught exception: java.lang.Exception: Exception occur
Choose your option:4
Caught exception: java.lang.IllegalAccessException: Some Operation
Threads:
UQ: Explain with examples of java threads. (N/D’10-12M)
 Thread is a tiny program running continuously. It is sometimes called as light-weight process. But there lies
difference between thread and process.
Sr.No. Thread Process

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
1 Thread is light-weight process. Process is heavy weight process.
Threads do not require separate address space for its Each process requires separate address
2 execution. It runs in the address space of the process to space to execute.
which it belongs to.

Difference between Multithreading and Multitasking (or) Multiprocessing


Sr.No Mulithreading Multiprocessing
Thread is fundamental unit of multithreading. Process is a fundamental unit of
1.
multiprocessing
Multiple parts of a single program gets executed by Multiple programs get executed by means
2.
means of multithreading. of multiprocessing.
During multithreading the processor switches During multiprocessing the processor
3. between multiple threads of the program. switches between multiple programs or
processes.
It is cost effective because CPU can be shared It is expensive because when a particular
4. among multiple threads at a time. process uses CPU other processes has to
wait.

Thread States
Thread always exists in any one of the following states-
 New or create state
 Runnable state
 Waiting state
 Timed waiting state
 Blocked state
 Terminated state
Life Cycle of a Thread
 Thread Life cycle specifies how a thread gets processed in the Java program.
 By executing various methods.
 Following figure represents how a particular thread can be in one of the state at any time.

New
Waiting
Waiting Completion
Runnable Terminated
Waiting
for I/O
Interval
Interval I/O Completed
Ends
request
Blocked
Timed Waiting
New state
When a thread starts its life cycle it enters in the New state or a create state.
Runnable state
 This is a state in which a thread starts executing.
Waiting state
 Sometimes one thread has to undergo in waiting state because another thread starts executing.
Timed waiting state
 There is a provision to keep a particular threading waiting for some time interval.
 This allows executing high prioritized threads first. After the timing gets over, the thread in waiting state
enters in runnable state.
Blocked state

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
 When a particular thread issues an Input/Output request then operating system sends it in blocked state until
the I/O operation gets completed.
 After the I/O completion the thread is sent back to the runnable state.
Terminated state
 After successful completion of the execution the thread in runnable state enters the terminated state.

The Java Thread Model


 The threads can be in various states such as new, runnable, waiting, blocked and so on.
 After successful completion of a thread, it gets terminated.
UQ: What are two methods of creating java threads? (N/D’10)
In Java we can implement the thread programs using two approaches-
 Using Thread class
 Using runnable interface
Following figure shows the thread implementation model

Implementation of thread

Extends Implements

Thread Runnable
(class) (Interface)
Overrides

Run ()
 As given in there are two methods by whichmethod
we can write the Java thread programs one is by extending
thread class and other is by implementing the Runnable interface.
 Various methods used in Thread class are:
Method Description
getName Obtain thread’s name
Run By this method execution of thread is started
Sleep Thread execution can be suspended for some time
Start Starts the thread with the help of run method
isAlive Checks whether thread is running or not
yield() It makes current executing thread object to pause temporarily and
gives control to other thread to execute.
notify() This method wakes up a single thread
notifyAll() This method wakes up all threads
Join Waits for a thread to terminate
Let us now discuss first create the programs containing single thread.
Thread Class
The procedure to extend a thread class is as given below-
Step1: The main class must extend the thread class.
Step2: A thread is created in the class. The thread may be initialized in the method() call.
Step3: Override the method run() by writing the code required to execute a thread.
Runnable Interface
Implementing thread program using Runnable interface is preferable than implementing it by extending the thread
class because of the following two reasons-
1. If a class extends a thread class then it cannot extends any other class which may be required to extend.
2. If a class thread is extended then all its functionalities get inherited. This is an expensive operation.
Example:
class threaddemo extends Thread//Thread Class
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
{
String str="";
void thread_method(String s)
{
str=s;
start();//Initialize the thread
}
public void run()//Execute the thread
{
System.out.println(str);
}
}
class runabledemo implements Runnable//Runnable Interface
{
String str1="";
Thread t=new Thread(this);
void runnable_method(String s1)
{
str1=s1;
t.start(); OUTPUT:
}
public void run() D:\Javapgms>java thread_create
{ Example for Threads
System.out.println(str1); Using Thread Class
} Using Runnable Interface
}
public class thread_create
{
public static void main (String args[])
{
System.out.println("Example for Threads");
threaddemo t1=new threaddemo();
t1.thread_method("Using Thread Class");
runabledemo rt1=new runabledemo();
rt1.runnable_method("Using Runnable Interface");
}
}
Handling Multiple Threads
We can create multiple threads and execute them simultaneously. Multiple threads can be created by either
extending the Thread class (or) by implementing the runnable interface.
Creation of Multiple Threads by extending the Thread class and Implementing Runnable Interface.
In the following Java program, three threads are created and handled.
Example:
//Example for Multithreading using Thread class and runnable interface
class thread_demo extends Thread//Using Thread Class
{
String msg;
thread_demo(String str)
{
msg=str;
start();//directs to the run method
}
public void run()//Thread execution starts
{
for(int i=1;i<=3;i++)
System.out.println(msg);
try
{
Thread.sleep(1000);
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
}
catch(InterruptedException e)
{
System.out.println("Exception in thread");
}
}
}
class runnable_thread implements Runnable//Using Runnable Interface
{
String msg;
Thread t=new Thread(this);
runnable_thread(String str) OUTPUT:
{ Example for Multithreading
msg=str; ---------------------------
t.start();//directs to the run method Multithreading using Thread class
} First thread
public void run() First thread
First thread
{
...Second thread
for(int i=1;i<=3;i++)
...Second thread
System.out.println(msg);
...Second thread
try Multithreading using Runnable Interface
{ ......Third thread
Thread.sleep(1000); ......Third thread
} ......Third thread
catch(InterruptedException e) First thread
{ First thread
System.out.println("Exception in thread"); First thread
} ...Second thread
} ...Second thread
} ...Second thread
public class many_thread ......Third thread
{ ......Third thread
public static void main (String args[]) ......Third thread
{
System.out.println("Example for Multithreading");
System.out.println("---------------------------");
System.out.println("Multithreading using Thread class");
thread_demo t1=new thread_demo("First thread");
thread_demo t2=new thread_demo("...Second thread");
thread_demo t3=new thread_demo("......Third thread");
System.out.println("Multithreading using Runnable Interface");
runnable_thread rt1=new runnable_thread("First thread");
runnable_thread rt2=new runnable_thread("...Second thread");
runnable_thread rt3=new runnable_thread("......Third thread");
}
}
Program Explanation
In the main function we have created three threads namely t1,t2 and t3 having the strings “First thread”, “Second
Thread” respectively. The execution of these threads will be started in run() method. We have invoked the
Thread.sleep method in order to send a thread in timed state. The value passed to this method as an argument denotes
the time in milliseconds. This statement must be within a try-catch block by throwing the exception
InterruptedException.
If you execute the program repeatedly then you may notice that the threads t1,t2 and t3 can execute in any order.
Streams and I/O: UQ: Explain with examples of Streams and I/O. (N/D’10-12M)
Stream is basically a channel on which the data flow sender to receiver. An input object that reads the stream
of data from a file is called input stream and the output object that writes the stream of data to a file is called output
stream.
Types of Streams

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
In Java input and output operations are performed using streams. And Java implements streams within the
classes that are defined in java.io.*; There are basically two types of streams used in Java.

Byte stream

Stream

Character stream
Byte Stream (or) Text Stream:
The byte Stream is used for inputting or outputting the bytes. There are two super classes in byte stream and
those are InputStream and OutputStream from which most of the other classes are derived. These classes define
several important methods such as read() and write(). The input and output stream classes are as shown in.
FileInputStream
BufferedInputStream

PipedInputStream
DataInputStream

FilterInputStream
InputStream LineNumberInputStream
ByteArrayInputStream
PushbackInputStream

SequenceInputStream

StringBufferInputStream

FileOutputStream

PipedOutputStream BufferedOutputStream

OutputStream
FilterOutputStream DataOutputStream

ByteArrayOutputStream PrintStream

Character Stream or Binary Stream:


The character stream is used for inputting or outputting the characters. There are two super classes in
character stream and those are Reader and Writer.
These classes handle the Unicode character streams. The two important methods defined by the character
stream classes are read() and write() for reading and writing the characters of data.
Various Reader and Writer classes are-
FileReader PipeReader
FileWriter PipeWriter
FilterReader BufferedReader
FilterWriter BufferedWriter
DataReader LineNumberReader

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
DataWriter LineNumberWriter
PushbackReader ByteArrayReader
PushbackWriter ByteArrayWriter
SequenceReader StringBufferReader
SequenceWriter StringBufferWriter

I/O Handling using Byte Stream


InputStream is an abstract class for streaming the byte input. Various methods defined by this class are as
follows
Methods Purpose
int available() It returns total number of byte input that are available currently for reading.
void close() The input source gets closed by this method. If we try to read further after
closing the stream then IOException gets generated.
void mark(int n) This method places a mark in the input stream at the current point. This mark
remains valid until the n bytes are read.
boolean marksupported() It returns true if mark() or reset() are supported by the invoking stream.
void reset() This method resets the input pointer to the previously set mart.
long skip(long n) This method ignores the n bytes of input. It then returns the actually ignored
number of bytes.
int read() It returns the next available number of bytes to read from the input stream. If
this method returns the value-1 then that means the end of file is encountered.
int read(byte buffer[]) This method reads the number of bytes equal to length of buffer. Thus it
returns the actual number of bytes that were successfully read.
int read(byte buffer[],int offset,int This method returns the n bytes into the buffer which is starting at offset. It
n) returns the number of bytes that are read successfully.

OutputStream is an abstract class for streaming the byte output. All these methods under this class are of void type.
Various methods defined by this class are as follows
Methods Purpose
void close() This method closes the output stream and if we try to write further after
using this method then it will generate IOException
void flush() This method clears output buffers.
void write(int val) This method allows to write a single byte to an output stream.
void write(byte buffer[]) This method allows to write complete array of bytes to an output stream.
void write(byte buffer[],int offset,int n) This method writes n bytes to the output stream from an array buffer which
is beginning at buffer[offset]

FileInputStream/FileOutputStream
UQ: What is the purpose of getBytes() method? (N/D’10)
The FileInputStream class creates an InputStream using which we can read bytes from a file.
The FileOutputStream can be used to write the data to the file using the OutputStream.
The two common constructors of FileInputStream and FileOutputStream are:
FileInputStream(String filename,Boolean app);
FileInputStream(String fileobject,Boolean app);
FileOutputStream(String filename)
FileOutputStream(Object fileobject)
The app denotes that the append mode can be true or false. If the append mode is true then you can append the
data in the otherwise the data cannot be appended in the file.
In the following Java program, we are writing and reading some data to the file.
Example:
//Example for FileInputStream and FileOutputStream
import java.io.*;
class filesstreamprog
{
public static void main(String[] args)throws Exception
{
int n;
System.out.println("Example for Writing and Reading content in the file");
WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
System.out.println("---------------------------------------------------");
String my_text="India is my Country\n"+"I love my country very much.";
byte b[]=my_text.getBytes();
FileOutputStream foobj=new FileOutputStream("D:/Javapgms/output.txt");
for(int i=0;i<b.length;i++)
foobj.write(b[i]);
System.out.println("\n The data is written to the file");
foobj.close();
FileInputStream fiobj=new FileInputStream("D:/Javapgms/output.txt");
System.out.println("Total available bytes:"+(n=fiobj.available()));
int m=n/2;
System.out.println("\n Reading first "+m+"bytes at a time");
for(int i=0;i<m;i++)
System.out.print((char)fiobj.read());
System.out.println("\n skipping some text");
fiobj.skip(n/4);
System.out.println("\n still available: "+fiobj.available());
fiobj.close();
}
}
OUTPUT:
Example for Writing and Reading content in the file
---------------------------------------------------
The data is written to the file
Total available bytes:48

Reading first 24bytes at a time


India is my Country
I lo
skipping some text

still available: 12

D:\Javapgms>type output.txt
India is my Country
I love my country very much.

FilterInputStream/FilterOutputStream
FilterStream classes are those classes which wrap the input stream with the byte. That means using input
stream you can read the bytes but if you want to read integers, doubles or strings you need to a filter class to wrap the
byte input stream.

The syntax for FilterStream and FilterOutputStream are as follows-


FilterOutputStream(OutptuStream o)
FilterInputStream(InputStream i)

The methods in the Filter stream are similar to the methods in InputStream and OutputStream

DataInputStream/DataOutputStream
DataInputStream reads bytes from the stream and converts them into appropriate primitive data type whereas
the DataOutputStream converts the primitive data types into the bytes and then swrites these bytes to the stream. The
superclass of DataInputStream class is FilterInputStream and superclass of DataOutputStream class is
FilterOutputStream class.

Various methods under these classes are:


Methods Purpose

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
boolean readBoolean() Reads Boolean value from the inputsteam
byte readByte() Reads byte value from the inputstream
char readChar() Reads char value from the inputstream
float readFloat() Reads float value from the inputstream
double readDouble() Reads double value from the inputstream
int readInt() Reads integer value from the inputstream
long readLong() Reads long value from the inputstream
String readLine() Reads string value from the inputstream
String readUTF() Reads string in UTF from.
void writeBoolean(boolean val) Writes the Boolean value to output stream.
void writeBytes(String str) Writes the bytes of characters in a string to output stream.
void writeFloat(float val) Writes the float value to output stream.
void writeDouble(float val) Writes the double value to output stream.
void writeInt(int val) Writes the integer value to output stream.
void writeLong(long val Writes the long value to output stream.
void writeUTF(String str) Writes the string value in UTF from to output stream.
Let us see how these methods can be used in a Java Program-

Java.io.Object Java.io.Object

OutputStream InputStream

FilterOutputStream FilterInptStream

BufferedOutputstream BufferedInputStream
BufferedInputStream/BufferedOutputStream
The BufferedInput
Stream and BufferedOutputStream is an efficient class used for speedy read and write operations. All the methods of
BufferedInputStream and BufferedOutputStream class are inherited from InputStream and OutputStream classes. But
these methods add the buffers in the stream for efficient read and write operations. We can specify the buffer size
otherwise the default buffer size is 512 bytes.
In the following Java program the BufferedInputStream and BufferedOutputStream classes are used.
Example:
import java.io.*;
class BufferedStreamProg
{
public static void main(String[] args)throws Exception
{
DataOutputStream Obj=new DataOutputStream(new BufferedOutputStream(new FileOutputStream("in.txt")));
Obj.writeUTF("Archana");
Obj.writeDouble(44.67); OUTPUT:
Obj.writeUTF("Keshavanand"); Following are the contents of the 'in.txt' file
Obj.writeInt(77); Archana:44.67
Obj.writeUTF("Chitra"); Keshavanand:77
Obj.writeChar('a'); Chitra:a
Obj.close();
DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream("in.txt")));
System.out.println("\nFollowing are the contents of the 'in.txt' file");
System.out.println(in.readUTF()+":"+in.readDouble());
System.out.println(in.readUTF()+":"+in.readInt());

WWW.VIDYARTHIPLUS.COM V+ TEAM
WWW.VIDYARTHIPLUS.COM
System.out.println(in.readUTF()+":"+in.readChar());
}
}
Program Explanation
Note that in above program, along with other simple read and write methods we have used readUTF and
writeUTF methods. Basically UTF is an encoding scheme that allows systems to operate with both ASCII and
Unicode.
Normally all the operating systems use ASCII and Java uses Unicode. The writeUTF method converts the
string into a series of bytes in the UTF-8 format and writes them into a binary stream.
The readUTF method reads a string which is written using the writeUTF method.
The only change is we have added buffers. The creation of buffers is shown by the bold faced statements in.

I/O Handling using Character Stream


Reading the Input
In Java, System is a class defined in java.lang and in, out and err are the variables of the class System. Hence
System.out is an object used for standard output stream and System.in and System.err are the objects for standard
input stream and error.
When we want to read some character from the console we should make use of system.in. The character
stream class BufferedReader is used for this purpose.
In fact we should pass the variable System.in to BufferedReader object. Along with it we should also mention
the abstract class of BufferedReader class which is InputStreamReader.
Hence the syntax is,
BufferedReader object-name=new BufferedReader(new InputStreamReader(System.in));

For example the object named obj can be created as


BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));

Then, using this object we invoke read() method. For e.g. obj.read(). But this is not the only thing needed for
reading the input from console; we have to mention the exception IOException for this purpose. Hence if we are going
to use read() method in our program then function main can be written like this-
public static void main(String args[])throws IOException
Example:
//Reading the input char and string from console
import java.io.*;
class ReadChar
{
public static void main(String args[])throws IOException
{
//declaring obj for read() method
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
int count=0;
char ch,ch1;
String s;
System.out.println("1.Reading char\n2.Reading String");
System.out.println("Enter your Choice:");
ch1=(char)obj.read(); OUTPUT:
switch(ch1) 1.Reading char
2.Reading String
{
Enter your Choice:
case '1':
1
System.out.println("\nEnter five characters");
while(count<5)
Enter five characters:
{ senthil
ch=(char)obj.read();//reading single character s
System.out.println(ch);//outputting it e
count++;//count to keep track of 5 characters n
} t
break; h
case '2':
System.out.println("Enter the strings:"); Enter your Choice:
2
WWW.VIDYARTHIPLUS.COM V+ TEAM
Enter the strings:
WWW.VIDYARTHIPLUS.COM
s=obj.readLine();//for reading the string
while(!s.equals("end"))
{
System.out.println(s);
s=obj.readLine();
}
break;
}}}
This program allows you take the input from console. As given in above program, read() method is used for
reading the input from the console. The method read() returns the integer value, hence it is typecast to char because we
are reading characters from the console.
Note that to read the string input we have used readLine() function. Otherwise this program is almost same as
previous one.
Writing the Output
The simple method used for writing the output on the console is write(). Here is the syntax of using write()
method-
System.out.write(int b)
The bytes specified by b has to be written on the console. But typically print() or println() is used to write the
output on the console.
And these methods belong to PrintWriter class.
University Questions only:
PART-A
1. What is method overloading in java?(A/M’10)
2. Explain the use of the keyword ‘finally’ in java? (A/M’10)
3. Which type of inheritance is not allowed in java? What is the equivalent representation? Explain
with example. (A/M’10)
4. Explain with example, method overriding in java. (A/M’10)
5. What is the purpose of getBytes() method? (N/D’10)
6. What are two methods of creating java threads? (N/D’10)
7. How Java achieves multiple inheritance? (N/D’11)
8. How are interfaces different from classes? (N/D’11)
9. What is an interface in JAVA? (A/M’11, N/D’10)
10. What is the major difference between an interface and abstract class? (N/D’12, M/J’13)

PART-B
1.Explain with examples of Streams and I/O. (N/D’10-12M)
2.Explain with examples of java threads. (N/D’10-12M)
3.Describe different forms of inheritance with example. (M/J’13-16M)
4.Abstract methods and classes in detail. (M/J’12-8M)
5.Give an example where interface can be used to support multiple inheritances. Develop a standalone
Java program for the example. (M/J’12,13-16M, N/D’11-10M)
6. Differentiate method overloading & overriding in java. (M/J’12-4M)
7. Describe in detail about exception handling in java. (N/D’11-16M)

WWW.VIDYARTHIPLUS.COM V+ TEAM

Das könnte Ihnen auch gefallen