Sunteți pe pagina 1din 83

Question Bank –CS2203 Object Oriented Programming

4202- A.C.T COLLEGE OF ENGINEERING & TECHNOLOGY


NELVOY -603107

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

QUESTION BANK

SUBJECT CODE : CS2203

SUBJECT NAME : OBJECT ORIENTED PROGRAMMING

SEM ESTER : III

YEAR : II

REGULATION : 2008

Prepared By

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 1


Question Bank –CS2203 Object Oriented Programming

S.VENKATESAN. B.E.

AP/CSE. A.C.T.C.E.T

1. What is a friend function? What are the merits and demerties of using friend function?
A friend function is a special function in c++ which inspite of not being member fuction of a class has
privalage to access private and protected data of a class.
A friend function is a non member function of a class that is declared as a friend using the keyword
"friend" inside the class. By declaring a function as a friend, all the access permissions are given to the
function.
A friend function is used for accessing the non-public members of a class. A class can allow non-member
functions and other classes to access its own private data, by making them friends. Thus, a friend function
is an ordinary function or a member of another class.

Need for Friend Function:

when a data is declared as private inside a class, then it is not accessible from outside the class. A
function that is not a member or an external class will not be able to access the private data. A
programmer may have a situation where he or she would need to access private data from non-member
functions and external classes. For handling such cases, the concept of Friend functions is a useful tool.

How to define and use Friend Function in C++:


The friend function is written as any other normal function, except the function declaration of these
functions is preceded with the keyword friend. The friend function must have the class to which it is
declared as friend passed to it in argument.

Some important points to note while using friend functions in C++:

* The keyword friend is placed only in the function declaration of the friend function and not in the
function definition.
* It is possible to declare a function as friend in any number of classes. .
* When a class is declared as a friend, the friend class has access to the private data of the class that made
this a friend.
* A friend function, even though it is not a member function, would have the rights to access the private
members of the class.
* It is possible to declare the friend function as either private or public. .

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 2


Question Bank –CS2203 Object Oriented Programming

* The function can be invoked without the use of an object. The friend function has its argument as
objects, seen in example below.

Properties of friend function:

1. if a function to be made friend of a class than it should be declared within body of the class priciding
with keyword friend.
2.freind function never breaks the security.
3.it should not be defined in name of class nor scope resolution operator is used in it's defination even the
keyword freind is also not used while defining friend function.
4.when friend function is called nither name of object nor dot operator is used. however it may accept the
object as argument who's value it want's to access.
5.it doen't matter in which section of the class we have declared a freind function.

Example to understand the friend function:

#include<iostream.h>
class exforsys
{
private:
int a,b;
public:
void test()
{
a=100;
b=200;
}
friend int compute(exforsys e1)

//Friend Function Declaration with keyword friend and with the object of class exforsys to which it is
friend passed
to it
};

int compute(exforsys e1)


{
//Friend Function Definition which has access to private data

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 3


Question Bank –CS2203 Object Oriented Programming

return int(e1.a+e2.b)-5;
}

main()
{
exforsys e;
e.test();
cout<<"The result is:"<
//Calling of Friend Function with object as argument.
}

The output of the above program is

The result is:295

The function compute() is a non-member function of the class exforsys. In order to make this function
have access to the private data a and b of class exforsys , it is created as a friend function for the class
exforsys. As a first step, the function compute() is declared as friend in the class exforsys as:

friend int compute (exforsys e1)


disadvantage of friend function:

They require an extra line of code when you want dynamic binding. To get the effect of a virtual friend,
the friend function should call a hidden (usually protected:) virtual[20] member function.

2. Explain about friend class and friend function with eg.?

The friend function is a ‘non member function’ of a class. It can access non public members of the class.
A friend function is external to the class definition.

A friend function has the following advantages:

- Provides additional functionality which is kept outside the class.


- Provides functions that need data which is not normally used by the class.
- Allows sharing private class information by a non member function.

friend function example:


#include<iostream.h>
class exforsys
{
private:

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 4


Question Bank –CS2203 Object Oriented Programming

int a,b;
public:
void test()
{
a=100;
b=200;
}
friend int compute(exforsys e1)

//Friend Function Declaration with keyword friend and with the object of class exforsys to which it is
friend passed
to it
};

int compute(exforsys e1)


{
//Friend Function Definition which has access to private data
return int(e1.a+e2.b)-5;
}

main()
{
exforsys e;
e.test();
cout<<"The result is:"<
//Calling of Friend Function with object as argument.
}

The output of the above program is

The result is:295

The advantages of using friend classes.

There are situations when private data members need to be accessed and used by 2 classes
simultaneously. In hese kind of situations we can introduce friend functions which have an access to the
private data members of both the classes. Friend functions need to be declared as ‘friend’ in both the
classes. They need not be members of either of these classes.

friend class in C++:

When a class declares another class as its friend, it is giving complete access to all its data and methods
including private and protected data and methods to the friend class member methods. Friendship is one
way only, which means if A declares B as its friend it does NOT mean that A can access private data of B.
It only means that B can access all data of A.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 5


Question Bank –CS2203 Object Oriented Programming

Note: the friend class member function average is passed the object of Numbers class as parameter.

Friend class can be declared as below:

class A
{
private:
//...
public:
//...
friend class B;
}

Here, friend class B has full access to the private data members of class A without being a member of that
class.

declare a class as a friend of another class:

class a
{
friend class b; // with this declaration, class b can access all members of a
};

A friend class and all its member functions have access to all the private members defined within other
class.

friend class example:

#include <iostream>
using namespace std;
class Numbers
{
int a;
int b;
public:
Numbers(int i, int j)
{
a = i;
b = j;
}
friend class Average;
};

class Average
{
public:
int average(Numbers x);
};

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 6


Question Bank –CS2203 Object Oriented Programming

int Average:: average(Numbers x)


{
return ((x.a + x.b)/2);
}

int main()
{
Numbers ob(23, 67);
Average avg;
cout<<”The average of the numbers is: ”<<avg.average(ob);
return 0;
}

3.What is inline function? Explain

An inline function is a combination of macro & function. At the time of declaration or definition, function
name is preceded by word inline.

When inline functions are used, the overhead of function call is eliminated. Instead, the executable
statements of the function are copied at the place of each function call. This is done by the compiler.

Consider following example:

#include <iostream>
using namespace std;

inline int sqr(int x)


{
int y;
y = x * x;
return y;
}
int main()
{
int a =3, b;
b = sqr(a);
cout <<b;
return 0;
}

Here, the statement b = sqr(a) is a function call to sqr(). But since we have declared it as inline, the
compiler replaces the statement with the executable stmt of the function (b = a *a)

Please note that, inline is a request to the compiler. If it is very complicated function, compiler may not be
able to convert it to inline. Then it will remain as it is. E.g. Recursive function, function containing static

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 7


Question Bank –CS2203 Object Oriented Programming

variable, function containing return statement or loop or goto or switch statements are not made inline
even if we declare them so.

Also, small functions which are defined inside a class (ie their code is written inside the class) are taken
as inline by the compiler even if we don’t explicitly declare them so. They are called auto inline
functions.

Inline Function definition:

When the function is defined Inline, the C++ compiler puts the function body inside the calling function.
You can define function as Inline when the function body is small and need to be called many times, thus
reduces the overhead in calling a function like passing values, passing control, returning values, returning
control.

Advantages of inline functions

A function when defined as INLINE, the code from the function definition is directly copied into the
code of the calling function. A function is defined as inline using the inline keyword as shown below:

inline float add(float i, float j) { return i + j};

Advantages:

 It avoids the overhead of calling the actual function. This is because the complier performs and
inline expansion which eliminates the time overhead when a function is called.
 Reduces space as no separate set of instructions in memory is written.

It relieves the burden involved in calling a function. It is used for functions that need fast execution.

Inline function example:

#include<iostream.h>
#include<conio.h>

class line
{
public:
inline float mul(float x,float y)
{
return(x*y);
}
inline float cube(float x)
{
return(x*x*x);
}
};
Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 8
Question Bank –CS2203 Object Oriented Programming

void main()
{
line obj;
float val1,val2;
clrscr();
cout<<"Enter two values:";
cin>>val1>>val2;
cout<<"\nMultiplication value is:"<<obj.mul(val1,val2);
cout<<"\n\nCube value is :"<<obj.cube(val1)<<"\t"<<obj.cube(val2);
getch();
}

Output:
Enter two values: 5 7
Multiplication Value is: 35
Cube Value is: 25 and 343

4. Compare objects oriented methodology with structure programming.

here are some difference between c and c++

1. C is a PROCEDURE oriented programming language.

C++ is a OBJECT oriented programming language.

2. We can do programming through STRUCTURE, but NOT with the help of the CLASS.

We can do programming through CLASS in c++.

3. C is a LOW level language.

C++ is a HIGH level language.

4. C is a TOP->BOTTOM programming approch.

C++ is a BOTTOM->TOP programming approch.

5. C is a collection of FUNCTIONS.

C++ is a collection of FUNCTIONS and/or CLASS.

6. C language main focuses on PROCEDURES.

C++ programming main focuses on OBJECTS.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 9


Question Bank –CS2203 Object Oriented Programming

7. In C, DATA can be MOVE openly around in the system from function to function.

In C++, DATA is hidden. It cannot be accessed by external functions.

8. C cannot support all the feature of the C++.while c++ supports all the features of C.

9. C NEEDS FORMAT CHARACTERS for printing & scanning.

C++ DOES NOT REQUIRED FORMAT SPECIFIER for printing and scanning variable.

10. C variables are DECLARED in declaration section.

C++ variables are DECLARED anywhere in the program.

11. In C,we use PRINTF() ,SCANF() as standard input/output functions.

In C++,we can use COUT<< or CIN>> as standard input/output function.

12. In C,you can NOT OVERLOAD a function.

In C++ ,you can OVERLOAD the operator as well as functions.

13. C does NOT have NAMESPACE for avoid name collisions.

C++ has NAMESPACE feature.

14. C does NOT have REFERENCE variables.

In C++ ,REFERENCE variables are USED in functions.

15. In C,constants are defined as 'MACROS'.

We can make a use of 'CONST' TO declare a constant.

16.In C program , the MAIN() should NOT RETURN a value.

In C++,MAIN() should RETURN a value.

17. C does NOT SUPPORT DEFAULT arguments.

C++ PROVIDES DEFAULT argument concept.

18. C C++
#include<stdio.h>..... #include<iostream.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a,b,c; int a,b;
printf("enter 2 no."); cout<<"enter two number";
scanf("%d%d",&a,&b); . cin>>a>>b;
c=a+b; int c=a+b;
printf("sum is=%d"c); cout<<"sum is="<<c;
Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 10
Question Bank –CS2203 Object Oriented Programming

getch(); getch
();
} }

so from above we know that in c variables are declared in declaration section.


In C++ variable declaration can be anywhere .whenever we need we declare variables.

5. Write a program in C++ to input a four digit number and to write the same in words.

#include<iostream>
using namespace std;
void expand(int);
int main()
{
int num;
cout<<"Enter a number : ";
cin>>num;
expand(num);
}
void expand(int value)
{
const char * const ones[20] = {"zero", "one", "two", "three","four","five","six","seven",
"eight","nine", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen",
"eighteen","nineteen"};
const char * const tens[10] = {"", "ten", "twenty", "thirty","forty","fifty","sixty","seventy",
"eighty","ninety"};

if(value<0)
{
cout<<"minus ";
expand(-value);
}
else if(value>=1000)
{
expand(value/1000);
cout<<" thousand";
if(value % 1000)
{
if(value % 1000 < 100)
{
cout << " and";
}
cout << " " ;
expand(value % 1000);
}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 11


Question Bank –CS2203 Object Oriented Programming

}
else if(value >= 100)
{
expand(value / 100);
cout<<" hundred";
if(value % 100)
{
cout << " and ";
expand (value % 100);
}
}
else if(value >= 20)
{
cout << tens[value / 10];
if(value % 10)
{
cout << " ";
expand(value % 10);
}
}
else
{
cout<<ones[value];
}
return;
}
eg:- Input: 1234

Output: One thousand two hundred thirty-four.

Input: 10

Output: Ten

6. What is polymorphism? Explain with suitable eg

Polymorphism means the ability to take more than one form. An operation may exhibit different behavior in different
instances. The behavior depends on the types of data used in the operation. For example, consider
addition operation. For two numbers, the operation will generation sum. In case of two strings, it will
generate a third string with concatenation. Thus, polymorphism allows objects with different internal
structure to share same external interface. This means that a general class of operations can be
accessed in the same manner even though specific actions associated with each operation may differ.
There are two types of polymorphism:

Compile Time Polymorphism: Achieved using operator overloading and function overloading
Rum Time Polymorphism: Achieved using virtual functions..

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 12


Question Bank –CS2203 Object Oriented Programming

Compile Time Polymorphism:

C++ allows you to specify more than one definition for a function name or an operator in the same
scope, which is called function overloading and operator overloading respectively.

An overloaded declaration is a declaration that had been declared with the same name as a previously
declared declaration in the same scope, except that both declarations have different arguments and
obviously different definition (implementation).

When you call an overloaded function or operator, the compiler determines the most appropriate
definition to use by comparing the argument types you used to call the function or operator with the
parameter types specified in the definitions. The process of selecting the most appropriate overloaded
function or operator is called overload resolution.
Function overloading in C++:

You can have multiple definitions for the same function name in the same scope. The definition of the
function must differ from each other by the types and/or the number of arguments in the argument list.
You cannot overload function declarations that differ only by return type.

Following is the example where same function print() is being used to print different data types:
#include <iostream>
using namespace std;

class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}

void print(double f) {
cout << "Printing float: " << f << endl;
}

void print(char* c) {
cout << "Printing character: " << c << endl;
}
};

int main(void)
{
printData pd;

// Call print to print integer


pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 13


Question Bank –CS2203 Object Oriented Programming

return 0;
}

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

Printing int: 5
Printing float: 500.263
Printing character: Hello C++

Operator overloading in C++:

C++ provides ability to overload most operators so that they perform special operations relative to
classes. For example, a class String can overload the + operator to concatenate two strings.

When an operator is overloaded, none of its original meanings are lost. Instead, the type of objects it can
be applied to is expanded. By overloading the operators, we can use objects of classes in expressions in
just the same way we use C++’s built-in data types.

Operators are overloaded by creating operator functions. An operator function defines the operations that
the overloaded operator will perform on the objects of the class. An operator function is created using the
keyword operator.

For example: Consider class String having data members char *s, int size, appropriate function members
and overloaded binary operator + to concatenate two string objects.

class String
{
char *s;
int sz;
public:
String(int n)
{
size = n;
s = new char [n];
}
void accept()
{
cout <<”\n Enter String:”;
cin.getline(s, sz);
}
void display()
{
cout<<”The string is: ”<<s;
}
String operator +(String s2) // ‘+’ operator overloaded
{
String ts(sz + s2.sz);
for(int i = 0; s[i]!=’\0’;i++)
ts.s[i] = s[i];

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 14


Question Bank –CS2203 Object Oriented Programming

for(int j = 0; s2.s[j]!=’\0’; i++, j++)


ts.s[i] = s2.s[j];
ts.s[i] = ‘\0’;
return ts;
}
};

int main()
{
String s1, s2, s3;
s1.accept();
s2.accept();
s3 = s1 + s2; //call to the overloaded ‘+’ operator
s3.display()
}

If you pass strings “Hello” and “World” for s1 and s2 respectively, it will concatenate both into s3 and
display output as “HelloWorld”
Operator overloading can also be achieved using friend functions of a class.

Run Time Polymorphism:

Overriding:

Defining a function in the derived class with same name as in the parent class is called overriding. In C+
+, the base class member can be overridden by the derived class function with the same signature as the
base class function. Method overriding is used to provide different implementations of a function so that a
more specific behavior can be realized.

Overriding vs. overloading

Overloading helps to create different behaviors of methods with the same name and scope. For instance
we can overload a method to return float values and integer values.Overriding on the other hand changes
the behavior of a class to make it behave different than its parent class.

Overloading means having methods with same name but different signature
Overriding means rewriting the virtual method of the base class

The problem with overriding functions:

Overriding of functions occurs in Inheritance. A derived class may override a base class member function.
In overriding, the function names and parameter list are same in both the functions. Depending upon the
caller object, proper function is invoked.

Consider following sample code:

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 15


Question Bank –CS2203 Object Oriented Programming

class A
{
int a;
public:
A()
{
a = 10;
}
void show()
{
cout << a;
}
};

class B: public A
{
int b;
public:
B()
{
b = 20;
}
void show()
{
cout << b;
}
};

int main()
{
A ob1;
B ob2;
ob2.show(); // calls derived class show() function. o/p is 20
return 0;
}

As seen above, the derived class functions override base class functions. The problem with this is, the
derived class objects can not access base class member functions which are overridden in derived class.

Base class pointer can point to derived class objects; but it has access only to base members of that
derived class.

Therefore, pA = &ob2; is allowed. But pa->show() will call Base class show() function and o/p would be
10.

Virtual functions:

A virtual function is a member function that is declared within a base class and redefined by a derived
class. To create virtual function, precede the function’s declaration in the base class with the keyword

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 16


Question Bank –CS2203 Object Oriented Programming

virtual. When a class containing virtual function is inherited, the derived class redefines the virtual
function to suit its own needs.

Base class pointer can point to derived class object. In this case, using base class pointer if we call some
function which is in both classes, then base class function is invoked. But if we want to invoke derived
class function using base class pointer, it can be achieved by defining the function as virtual in base class,
this is how virtual functions support runtime polymorphism.

Consider following program code:

Class A
{
int a;
public:
A()
{
a = 1;
}
virtual void show()
{
cout <<a;
}
};

Class B: public A
{
int b;
public:
B()
{
b = 2;
}
virtual void show()
{
cout <<b;
}
};

int main()
{
A *pA;
B oB;
pA = &oB;
pA->show();
return 0;
}

Output is 2 since pA points to object of B and show() is virtual in base class A.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 17


Question Bank –CS2203 Object Oriented Programming

Polymorphism is also achieved in C++ using virtual functions. If a function with same name exists in
base as well as parent class, then the pointer to the base class would call the functions associated only
with the base class. However, if the function is made virtual and the base pointer is initialized with the
address of the derived class, then the function in the child class would be called.

Pure virtual functions:

Pure virtual functions are also called ‘do nothing functions’. e.g. virtual void abc() = 0;
When a pure virtual fnction is declared in the base class, the compiler necessitates the derived classes to
define those functions or redeclare them are pure virtual functions. The classes containing pure virtual
functions cannot be used to declare objects of their own. Such classes are called as abstract base classes.

7. Create a class student and write a C++ program to read and display all the students in
your class.

#include<iostream.h>
#include<conio.h>
class student
{
int rollno;
char name[10];
float per;
public:
void getdata()
{
char ch; //to clear buffer
cout<<"\nEnter Roll No. : ";
cin>>rollno;
cout<<"Enter Name No. : ";
cin.get(ch);
cin.getline(name,10);
cout<<"Enter % : ";
cin>>per;
}
void putdata()
{
cout<<"Roll No. : "<<rollno;
cout<<"\nName No. : "<<name;
cout<<"\n% "<<per;
}
int getrollno()
{
return (rollno);
}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 18


Question Bank –CS2203 Object Oriented Programming

};
void main()
{
student s[5];
int rno;
for(int x=0;x<5;x++)
{
cout<<"\nEnter Details for student "<<x+1;
s[x].getdata();
}
cout<<"\n\nNiw enter rollno of student to be displayed : ";
cin>>rno;
for(x=0;x<5;x++)
{
if(s[x].getrollno()==rno)
{
s[x].putdata();
break;
}
}
if(x==5)
cout<<"\nYour RollNo does not exists: ";
getch();
}

(Or)

ALGORITHAM:

1. Start the process


2. Invoke the classes
3. Call the read() function
a. Get the inputs name ,roll number and address
4. Call the display() function
a. Display the name,roll number,and address of the student
5. Stop the process

PROGRAM

#include<iostream.h>
#include<conio.h>
class stu
{
private: char name[20],add[20];
int roll,zip;
public: stu ( );//Constructor
~stu( );//Destructor

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 19


Question Bank –CS2203 Object Oriented Programming

void read( );
void disp( );
};
stu :: stu( )
{
cout<<”This is Student Details”<<endl;
}
void stu :: read( )
{
cout<<”Enter the student Name”;
cin>>name;
cout<<”Enter the student roll no “;
cin>>roll;
cout<<”Enter the student address”;
cin>>add;
cout<<”Enter the Zipcode”;
cin>>zip;
}
void stu :: disp( )
{
cout<<”Student Name :”<<name<<endl;
cout<<”Roll no is :”<<roll<<endl;
cout<<”Address is :”<<add<<endl;
cout<<”Zipcode is :”<<zip;
}
stu : : ~stu( )
{
cout<<”Student Detail is Closed”;
}

void main( )
{
stu s;
clrscr( );
s.read ( );
s.disp ( );
getch( );
}

Output:

Enter the student Name


James
Enter the student roll no
01
Enter the student address
Newyork
Enter the Zipcode
919108

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 20


Question Bank –CS2203 Object Oriented Programming

Student Name : James


Roll no is : 01
Address is : Newyork
Zipcode is :919108

8. Describe briefly the features of input/output supported by C++

The C++ I/O system supplies an interface to the programmer that is independent of the actual device
being accessed. This interface is known as stream. The I/O system contains a hierarchy of the stream
classes used to define various streams to deal with the console and disk files. These classes are known as
stream classes. The base stream class for handling input and output operations with the console and disk
is ios and there are various classes derived from it such as istream, ostream, streambuf etc.

The header file <iostream> declares the stream classes.

As part of the library, the iostream declares certain objects that are used to perform input and output
operations. These are known as Stream objects. They are cin, cout, cerr, clog etc.

Using the standard input and output library, we will be able to interact with the user by printing messages
on the screen and getting the user's input from the keyboard.

C++ uses a convenient abstraction called streams to perform input and output operations in sequential
media such as the screen or the keyboard. A stream is an object where a program can either insert or
extract characters to/from it. We do not really need to care about many specifications about the physical
media associated with the stream - we only need to know it will accept or provide characters sequentialy.

The standard C++ library includes the header file iostream, where the standard input and output stream
objects are declared.

Standard Output (cout)


By default, the standard output of a program is the screen, and the C++ stream object defined to access it
is cout.

cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs).

cout << "Output sentence"; // prints Output sentence on screen


cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen

The << operator inserts the data that follows it into the stream preceding it. In the examples
above it inserted the constant string Output sentence, the numerical constant 120 and variable x
into the standard output stream cout. Notice that the sentence in the first instruction is enclosed
between double quotes (") because it is a constant string of characters. Whenever we want to use
constant strings of characters we must enclose them between double quotes (") so that they can
be clearly distinguished from variable names. For example, these two sentences have very
different results:

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 21


Question Bank –CS2203 Object Oriented Programming

cout << "Hello"; // prints Hello


cout << Hello; // prints the content of Hello variable

The insertion operator (<<) may be used more than once in a single statement:

cout << "Hello, " << "I am " << "a C++ statement";

This last statement would print the message Hello, I am a C++ statement on the screen. The
utility of repeating the insertion operator (<<) is demonstrated when we want to print out a
combination of variables and constants or more than one variable:

cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;

If we assume the age variable to contain the value 24 and the zipcode variable to contain 90064
the output of the previous statement would be:

Hello, I am 24 years old and my zipcode is 90064

It is important to notice that cout does not add a line break after its output unless we explicitly
indicate it, therefore, the following statements:

cout << "This is a sentence.";


cout << "This is another sentence.";

will be shown on the screen one following the other without any line break between them:

This is a sentence.This is another sentence.

even though we had written them in two different insertions into cout. In order to perform a line
break on the output we must explicitly insert a new-line character into cout. In C++ a new-line
character can be specified as \n (backslash, n):

cout << "First sentence.\n ";


cout << "Second sentence.\nThird sentence.";

This produces the following output:

First sentence.
Second sentence.
Third sentence.

Additionally, to add a new-line, you may also use the endl manipulator. For example:

cout << "First sentence." << endl;


cout << "Second sentence." << endl;

would print out:

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 22


Question Bank –CS2203 Object Oriented Programming

First sentence.
Second sentence.

The endl manipulator produces a newline character, exactly as the insertion of '\n' does, but it also has an
additional behavior when it is used with buffered streams: the buffer is flushed. Anyway, cout will be an
unbuffered stream in most cases, so you can generally use both the \n escape character and the endl
manipulator in order to specify a new line without any difference in its behavior.

Standard Input (cin).


The standard input device is usually the keyboard. Handling the standard input in C++ is done by
applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by
the variable that will store the data that is going to be extracted from the stream. For example:

int age;
cin >> age;

The first statement declares a variable of type int called age, and the second one waits for an input from
cin (the keyboard) in order to store it in this integer variable.

cin can only process the input from the keyboard once the RETURN key has been pressed. Therefore,
even if you request a single character, the extraction from cin will not process the input until the user
presses RETURN after the character has been introduced.

You must always consider the type of the variable that you are using as a container with cin
extractions. If you request an integer you will get an integer, if you request a character you will
get a character and if you request a string of characters you will get a string of characters.

// i/o example

#include <iostream>
using namespace std;

int main ()
{ Please enter an integer value: 702
int i; The value you entered is 702 and its double is 1404.
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;
}

The user of a program may be one of the factors that generate errors even in the simplest programs that
use cin (like the one we have just seen). Since if you request an integer value and the user introduces a
name (which generally is a string of characters), the result may cause your program to misoperate since it
is not what we were expecting from the user. So when you use the data input provided by cin extractions
you will have to trust that the user of your program will be cooperative and that he/she will not introduce
his/her name or something similar when an integer value is requested. A little ahead, when we see the

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 23


Question Bank –CS2203 Object Oriented Programming

stringstream class we will see a possible solution for the errors that can be caused by this type of user
input.

You can also use cin to request more than one datum input from the user:

cin >> a >> b;

is equivalent to:

cin >> a;
cin >> b;

In both cases the user must give two data, one for variable a and another one for variable b that may be
separated by any valid blank separator: a space, a tab character or a newline.

cin and strings


We can use cin to get strings with the extraction operator (>>) as we do with fundamental data type
variables:

cin >> mystring;

However, as it has been said, cin extraction stops reading as soon as if finds any blank space character, so
in this case we will be able to get just one word for each extraction. This behavior may or may not be
what we want; for example if we want to get a sentence from the user, this extraction operation would not
be useful.

In order to get entire lines, we can use the function getline, which is the more recommendable
way to get user input with cin:

// cin with strings


#include <iostream>
#include <string>

using namespace std;

int main ()
{
string mystr;
cout << "What's your name? ";

getline (cin, mystr);


cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!\n";
return 0;
}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 24


Question Bank –CS2203 Object Oriented Programming

What's your name? Juan Souli�


Hello Juan Souli�.
What is your favorite team? The Isotopes
I like The Isotopes too!

Notice how in both calls to getline we used the same string identifier (mystr). What the program does in
the second call is simply to replace the previous content by the new one that is introduced.

stringstream
The standard header file <sstream> defines a class called stringstream that allows a string-based object
to be treated as a stream. This way we can perform extraction or insertion operations from/to strings,
which is especially useful to convert strings to numerical values and vice versa. For example, if we want
to extract an integer from a string we can write:

string mystr ("1204");


int myint;
stringstream(mystr) >> myint;

This declares a string object with a value of "1204", and an int object. Then we use stringstream's
constructor to construct an object of this type from the string object. Because we can use stringstream
objects as if they were streams, we can extract an integer from it as we would have done on cin by
applying the extractor operator (>>) on it followed by a variable of type int.

After this piece of code, the variable myint will contain the numerical value 1204.

// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
string mystr;
float price=0; Enter price: 22.25
int quantity=0; Enter quantity: 7
Total price: 155.75
cout << "Enter price: ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << "Enter quantity: ";
getline (cin,mystr);
stringstream(mystr) >> quantity;
cout << "Total price: " << price*quantity << endl;
return 0;
}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 25


Question Bank –CS2203 Object Oriented Programming

In this example, we acquire numeric values from the standard input indirectly. Instead of extracting
numeric values directly from the standard input, we get lines from the standard input (cin) into a string
object (mystr), and then we extract the integer values from this string into a variable of type int (quantity).

9. Explain the nested classes with suitable eg.

Nested class is a class defined inside a class, that can be used within the scope of the class in which it is
defined. In C++ nested classes are not given importance because of the strong and flexible usage of
inheritance. Its objects are accessed using "Nest::Display".

Example:

#include <iostream.h>
class Nest
{
public:
class Display
{
private:
int s;
public:
void sum( int a, int b)
{ s =a+b; }
void show( )
{ cout << "\nSum of a and b is:: " << s;}
};
};
void main()
{
Nest::Display x;
x.sum(12, 10);
x.show();
}

Result:
Sum of a and b is::22

In the above example, the nested class "Display" is given as "public" member of the class "Nest".

(Or)

class Host
{
public:
class Nested
{
public:
void PrintMe()
{
cout << "Printed!\n";
Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 26
Question Bank –CS2203 Object Oriented Programming

}
};
};

int main()
{
Host::Nested foo;
foo.PrintMe();

Host bar;
// nothing you can do with bar to call PrintMe
// Host::Nested and Host are two separate classes

return 0;
}

10.write a C++ program to add two complex number using the concept of passing and
returning objects in member function

#include<iostream.h>
#include<conio.h>

class complex
{
int a,b;
public:
complex(void) //default constructor
{
a=0;
b=0;
}
complex(int c, int d) //parameterized constructor
{
a=c;
b=d;
}
friend complex add(complex,complex); //function for addition of complex number
void put_data(); //function to display number
};

complex complex::add(complex x, complex y)


{
complex z;
z.a=x.a+y.a;
z.b=x.b+y.b;
return (z);
Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 27
Question Bank –CS2203 Object Oriented Programming

}
void complex :: put_data()
{
cout<<"\n"<<a<<" + i"<<b;

int main()
{
complex t4(1,2), t3,(3,4),z;
clrscr();
t4. put_data();
t3. put_data();
z=add(t3,t4); //calling of friend function
z. put_data();
getch();
return (0);
}

11.what are access specifiers? How are the used to protect data in C++?

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the
members of the class can be accessed. Of course, any member of a class is accessible within that
class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the
class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class
derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
};

int main()
{
MyClass obj;
obj.a = 10; //Allowed

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 28


Question Bank –CS2203 Object Oriented Programming

obj.b = 20; //Not Allowed, gives compiler error


obj.c = 30; //Not Allowed, gives compiler error
}

Access specifiers in C++ determine the scope of the class members.

Public: If a class member is public, it can be used anywhere without the access restrictions.

Private: if a class member is private, it can be used only by the members and friends of class.

Protected: If a class member is protected, it can be used only by the members and friends of class and the
members and friends of classes derived from class.

private: It is default one and can be access from class member of the same class.
protected: The protected members can be access from member functions of the same class or friend
classes or from the members of their immediate derived class.
public: The public members can be access from anywhere the class is visible.

12.Explain with an eg, How you would create space for an array of objects using pointer.

13.explain the following with eg

Pointer to object Array of pointers


Pointer to object members

14.Explain the following with an eg.


a.copy constructor
b.parameterized constructor
c.default argument constructor
d.dynamic constructor

The Class Constructor:

A class constructor is a special member function of a class that is executed whenever we create new
objects of that class.

A constructor will have exact same name as the class and it does not have any return type at all, not even
void. Constructors can be very useful for setting initial values for certain member variables.

Copy constructor:

The copy constructor is a constructor which creates an object by initializing it with an object of the same
class, which has been created previously. The copy constructor is used to:

 Initialize one object from another of the same type.


 Copy an object to pass it as an argument to a function.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 29


Question Bank –CS2203 Object Oriented Programming

 Copy an object to return it from a function.

If a copy constructor is not defined in a class, the compiler itself defines one.If the class has pointer
variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The
most common form of copy constructor is shown here:

classname (const classname &obj) {


// body of constructor
}

Example:

#include<iostream.h>
#include<conio.h>
class copy
{
int var,fact;
public:

copy(int temp)
{
var = temp;
}

double calculate()
{
fact=1;
for(int i=1;i<=var;i++)
{
fact = fact * i;
}
return fact;
}
};
void main()
{
clrscr();
int n;
cout<<"\n\tEnter the Number : ";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"\n\t"<<n<<" Factorial is:"<<obj.calculate();
cout<<"\n\t"<<n<<" Factorial is:"<<cpy.calculate();
getch();

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 30


Question Bank –CS2203 Object Oriented Programming

Output:
Enter the Number: 5
Factorial is: 120
Factorial is: 120
b.parameterized constructor

In C++,Constructor is automatically called when object(instance of class) create.It is special member


function of the class.Which constructor has arguments thats called Parameterized Constructor.

 It has same name of class.


 It must be a public member.

 No Return Values.

 Default constructors are called when constructors are not defined for the classes.

Syntax
class class-name
{
Access Specifier:
Member-Variables
Member-Functions
public:
class-name(variables)
{
// Constructor code
}

... other Variables & Functions


}

Example:

/* Example Program For Parameterized Constructor In C++ */

#include<iostream>
#include<conio.h>

using namespace std;

class Example {
// Variable Declaration
int a,b;

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 31


Question Bank –CS2203 Object Oriented Programming

public:

//Constructor
Example(int x,int y) {
// Assign Values In Constructor
a=x;
b=y;
cout<<"Im Constructor\n";
}

void Display() {
cout<<"Values :"<<a<<"\t"<<b;
}
};

int main() {
Example Object(10,20);
// Constructor invoked.
Object.Display();

// Wait For Output Screen


getch();
return 0;
}

Sample Output:
Im Constructor
Values :10 20

C.Default argument constructor


Default constructor is the constructor with no arguments or all the arguments has default values.

A default constructor is a constructor that either has no parameters, or if it has parameters, all the
parameters have default values.

If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a
default parameterless constructor A::A(). This constructor is an inline public member of its class. The
compiler will implicitly define A::A() when the compiler uses this constructor to create an object of
type A. The constructor will have no constructor initializer and a null body.

class X {
public:

// default constructor, no arguments


X();

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 32


Question Bank –CS2203 Object Oriented Programming

// constructor
X(int, int , int = 0);

// copy constructor
X(const X&);

// error, incorrect argument type


X(X);
};

class Y {
public:

// default constructor with one


// default argument
Y( int = 0);

// default argument
// copy constructor
Y(const Y&, int = 0);
};

Like functions, it is also possible to declare constructors with default arguments. Consider the following
example.

power (int 9, int 3);

In the above example, the default value for the first argument is nine and three for second.

power p1 (3);

In this statement, object p1 is created and nine raise to 3 expression n is calculated. Here, one argument is
absent hence default value 9 is taken, and its third power is calculated. Consider the example on the
above discussion given below.

# include <iostream.h>
# include <conio.h>
# include <math.h>

class power

{
private:
int num;
int power;
int ans;

public :

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 33


Question Bank –CS2203 Object Oriented Programming

power (int n=9,int p=3); //


declaration of constructor with default arguments

void show( )
{
cout <<"\n"<<num <<" raise to "<<power <<" is " <<ans;
}
};

power :: power (int n,int p )


{
num=n;
power=p;
ans=pow(n,p);
}

main( )
{
clrscr( );
class power p1,p2(5);
p1.show( );
p2.show( );
return 0;
}

d.Dynamic constructor:

Here is an simple example to demonstrate the use of dynamic constructor:

#include <iostream.h>
#include <conio.h>
class dyncons
{
int * p;
public:
dyncons()
{
p=new int;
*p=10;
}
dyncons(int v)
{
p=new int;
*p=v;
}
int dis()
{ return(*p);
}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 34


Question Bank –CS2203 Object Oriented Programming

};

void main()
{
clrscr();
dyncons o, o1(9);
cout<<"The value of object o's p is:";
cout<<o.dis();
cout<<"\nThe value of object 01's p is:"<<o1.dis();
getch();
}

15.what are virtual functions? Give an eg to highlight its need?

Virtual functions:

A virtual function is a member function that is declared within a base class and redefined by a derived
class. To create virtual function, precede the function’s declaration in the base class with the keyword
virtual. When a class containing virtual function is inherited, the derived class redefines the virtual
function to suit its own needs.

Base class pointer can point to derived class object. In this case, using base class pointer if we call some
function which is in both classes, then base class function is invoked. But if we want to invoke derived
class function using base class pointer, it can be achieved by defining the function as virtual in base class,
this is how virtual functions support runtime polymorphism.

Consider following program code:

Class A
{
int a;
public:
A()
{
a = 1;
}
virtual void show()
{
cout <<a;
}
};

Class B: public A
{
int b;
public:
B()

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 35


Question Bank –CS2203 Object Oriented Programming

{
b = 2;
}
virtual void show()
{
cout <<b;
}
};

int main()
{
A *pA;
B oB;
pA = &oB;
pA->show();
return 0;
}

Output is 2 since pA points to object of B and show () is virtual in base class A.

Polymorphism is also achieved in C++ using virtual functions. If a function with same name exists in
base as well as parent class, then the pointer to the base class would call the functions associated only
with the base class. However, if the function is made virtual and the base pointer is initialized with the
address of the derived class, then the function in the child class would be called.

Pure virtual functions:

Pure virtual functions are also called ‘do nothing functions’. e.g. virtual void abc() = 0;
When a pure virtual function is declared in the base class, the compiler necessitates the derived classes to
define those functions or redeclare them are pure virtual functions. The classes containing pure virtual
functions cannot be used to declare objects of their own. Such classes are called as abstract base classes.

Polymorphism is also achieved in C++ using virtual functions. If a function with same name exists in
base as well as parent class, then the pointer to the base class would call the functions associated only
with the base class. However, if the function is made virtual and the base pointer is initialized with the
address of the derived class, then the function in the child class would be called.

Virtual function is the member function of a class that can be overriden in its derived class. It is
declared with virtual keyword. Virtual function call is resolved at run-time (dynamic binding)
whereas the non-virtual member functions are resolved at compile time (static binding).

A virtual function in C++ is

- A simple member function of a class which is declared with “virtual” keyword


- It usually performs different functionality in its derived classes.
- The resolving of the function call is done at run-time.

16.give the hierarchy of console stream class

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 36


Question Bank –CS2203 Object Oriented Programming

17. Explain how exceptions are handled in C++. Give examples to support your answer.

Exceptions are certain disastrous error conditions that occur during the execution of a program. They
could be errors that cause the programs to fail or certain conditions that lead to errors. If these run time
errors are not handled by the program, OS handles them and program terminates abruptly, which is not
good.
To avoid this, C++ provides Exception Handling mechanism.

The three keywords for Exception Handling are:


Try, Catch and Throw.

The program tries to do something. If it encounters some problem, it throws an exception to another
program block which catches the exception.

Ex:

void main()
{
int no1, no2;
try
{
cout << “Enter two nos:”;
cin >> no1 >> no2;
if (no2 == 0)
throw “Divide by zero”;
else
throw no1/no2;
}
catch (char *s)
{
cout << s;

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 37


Question Bank –CS2203 Object Oriented Programming

}
catch (int ans)
{
cout << ans;
}
}

We know that divide by zero is an exception. If user enters second no as zero, the program throws an
exception, which is caught and an error message is printed else the answer is printed.

Exception handling allows the programmer to manage runtime errors in an orderly fashion. Using
exception handling, the program can automatically invoke an error handling routine when an error occurs.

An exception which is of class type is known as Class Type Exception. The reason to define a class type
for an expression is to create an object that describes the error that occurred. This information can be used
by the exception handler to process the error. In general, exception classes are created to encapsulate
information about an error to enable the exception handler to respond effectively.

Consider following sample code:

Class MyException
{
public:
char str_exc[80];
int exc;
MyException()
{
*str_exc = 0;
exc = 0;
}
MyException(char*s, int e)
{
strcpy(str_exc, s);
exc = e;
}
};

int main()
{
int no;
try
{
cout << “Enter positive no:”;
cin >> no;
if (no <0)
throw MyException(“Not Positive”, no);
}
catch (MyExecption e)
{
cout << e.str_exc<<”: “<<e.exc <<”\n”;

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 38


Question Bank –CS2203 Object Oriented Programming

}
return 0;
}

Sample run:
Enter positive No: -2
O/p: Not positive: -2
Thus, the program prompts the user for a positive no. If negative no is entered, an object of the class
MyException is created which encapsulates the information about the error.

Exception handling in C++ is implemented by using the try{} and catch(){} statements.

When a try block throws an exception, the program leaves the try block and enters the catch statement of
the catch block.

If they type of the object thrown matches the arg type in the catch block, catch block is executed for
handling the code.

If they are not caught, abort() function is executed by default.

When no exception is deteted or thrown then the control goes to the statement below the catch block.

C++ provides a mechanism to handle exceptions which occurs at runtime. C++ uses the keywords –
throw, catch and try to handle exception mechanism. An entity called an exception class need to be
created.

The application should have a separate section called catch block. The code in which an exception is
predicted is authored in the try block.

The following code illustrates to handle the exception.

#include <iostream>
class Excep {
public:
const char* error;
Excep(const char* arg) : error(arg) { }
};

class Test {
public:
int i;
// A function try block with a member initializer
Test() try : i(0) {
throw Excep("Exception thrown in A()");
}
catch (Excep& e) {
cout << e.error << endl;
}
};

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 39


Question Bank –CS2203 Object Oriented Programming

// A function try block


void f() try {
throw E("Exception thrown in f()");
}
catch (Excep& e) {
cout << e.error << endl;
}
void g() {
throw Excep("Exception thrown in g()");
}

int main() {
f();
// A try block
try {
g();
}
catch (Excep& e) {
cout << e.error << endl;
}
try {
Test x;
}
catch(...) { }
}

The following is the output of the above example:


Exception thrown in f()
Exception thrown in g()
Exception thrown in A().

18. Implement a String class. Each object of this class will represent a characters string.
Data members are the Length of the string and the actual characters String In addition to
constructors, destructor access function and a print function include a subscript function.
C++ provides following two types of string representations:

 The C-style character string.

 The string class type introduced with Standard C++.

The C-Style Character String:


The C-style character string originated within the C language and continues to be supported within C++.
This string is actually a one-dimensional array of characters which is terminated by a nullcharacter '\0'.
Thus a null-terminated string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than the
number of characters in the word "Hello."

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 40


Question Bank –CS2203 Object Oriented Programming

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as follows:

char greeting[] = "Hello";

Following is the memory presentation of above defined string in C/C++:

Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above
mentioned string:

#include <iostream>

using namespace std;

int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

return 0;
}

When the above code is compiled and executed, it produces result something as follows:

Greeting message: Hello

C++ supports a wide range of functions that manipulate null-terminated strings:

S.N. Function & Purpose

strcpy(s1, s2);
1
Copies string s2 into string s1.

strcat(s1, s2);
2
Concatenates string s2 onto the end of string s1.

strlen(s1);
3
Returns the length of string s1.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 41


Question Bank –CS2203 Object Oriented Programming

strcmp(s1, s2);
4
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

strchr(s1, ch);
5
Returns a pointer to the first occurrence of character ch in string s1.

strstr(s1, s2);
6
Returns a pointer to the first occurrence of string s2 in string s1.

Following example makes use of few of the above mentioned functions:

#include <iostream>
#include <cstring>

using namespace std;

int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;

return 0;
}

When the above code is compiled and executed, it produces result something as follows:

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

The String Class in C++:


The standard C++ library provides a string class type that supports all the operations mentioned above,
additionally much more functionality. We will study this class in C++ Standard Library but for now let us
check following example:
Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 42
Question Bank –CS2203 Object Oriented Programming

At this point you may not understand this example because so far we have not discussed Classes and
Objects. So can have a look and proceed until you have understanding on Object Oriented Concepts.

#include <iostream>
#include <string>

using namespace std;

int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total lenghth of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;

return 0;
}

When the above code is compiled and executed, it produces result something as follows:

str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10

19. Explain Method overriding in Java with an eg.

In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the superclass. When an
overridden method is called from within a subclass, it will always refer to the version of that method
defined by the subclass. The version of the method defined by the superclass will be hidden.

The benefit of overriding is: ability to define a behavior that's specific to the sub class type. Which means
a subclass can implement a parent class method based on its requirement.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 43


Question Bank –CS2203 Object Oriented Programming

In object oriented terms, overriding means to override the functionality of any existing method.

Example:

class Animal{

public void move(){


System.out.println("Animals can move");
}
}

class Dog extends Animal{

public void move(){


System.out.println("Dogs can walk and run");
}
}

public class TestDog{

public static void main(String args[]){


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class

b.move();//Runs the method in Dog class


}
}

This would produce following result:

Animals can move


Dogs can walk and run

In the above example you can see that the even though b is a type of Animal it runs the move method in
the Dog class. The reason for this is : In compile time the check is made on the reference type. However
in the runtime JVM figures out the object type and would run the method that belongs to that particular
object.

Therefore in the above example, the program will compile properly since Animal class has the method
move. Then at the runtime it runs the method specific for that object.

Consider the following example :

class Animal{

public void move(){


System.out.println("Animals can move");
}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 44


Question Bank –CS2203 Object Oriented Programming

class Dog extends Animal{

public void move(){


System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}
}

public class TestDog{

public static void main(String args[]){


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class


b.move();//Runs the method in Dog class
b.bark();
}
}

This would produce following result:

TestDog.java:30: cannot find symbol


symbol : method bark()
location: class Animal
b.bark();
^

This program will throw a compile time error since b's reference type Animal doesn't have a method by
the name of bark.

Rules for method overriding:

 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the original
overridden method in the super class.

 The access level cannot be more restrictive than the overridden method's access level. For
example: if the super class method is declared public then the overridding method in the sub class
cannot be either private or protected.

 Instance methods can be overridden only if they are inherited by the subclass.

 A method declared final cannot be overridden.

 A method declared static cannot be overridden but can be re-declared.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 45


Question Bank –CS2203 Object Oriented Programming

 If a method cannot be inherited then it cannot be overridden.

 A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.

 A subclass in a different package can only override the non-final methods declared public or
protected.

 An overriding method can throw any uncheck exceptions, regardless of whether the overridden
method throws exceptions or not. However the overriding method should not throw checked
exceptions that are new or broader than the ones declared by the overridden method. The
overriding method can throw narrower or fewer exceptions than the overridden method.

 Constructors cannot be overridden.

20. Construct the pictorial representation of Java Virtual Machine.

JVM has various sub components internally. You can see all of them from the above diagram.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 46


Question Bank –CS2203 Object Oriented Programming

1. Class loader sub system: JVM's class loader sub system performs 3 tasks
a. It loads .class file into memory.
b. It verifies byte code instructions.
c. It allots memory required for the program.

2. Run time data area: This is the memory resource used by JVM and it is divided into 5 parts
a. Method area: Method area stores class code and method code.
b. Heap: Objects are created on heap.
c. Java stacks: Java stacks are the places where the Java methods are executed. A Java stack contains
frames. On each frame, a separate method is executed.
d. Program counter registers: The program counter registers store memory address of the instruction
to be executed by the micro processor.
e. Native method stacks: The native method stacks are places where native methods (for example, C
language programs) are executed. Native method is a function, which is written in another language other
than Java.

3. Native method interface: Native method interface is a program that connects native methods libraries
(C header files) with JVM for executing native methods.

4. Native method library: holds the native libraries information.

5. Execution engine: Execution engine contains interpreter and JIT compiler, which covert byte code into
machine code. JVM uses optimization technique to decide which part to be interpreted and which part to
be used with JIT compiler. The HotSpot represent the block of code executed by JIT compiler.

21. Write a program in java using constructor concept.

A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax
does not include a return type, since constructors never return a value.

Constructors may include parameters of various types. When the constructor is invoked using the new
operator, the types must match those that are specified in the constructor definition.

Java provides a default constructor which takes no arguments and performs no special actions or
initializations, when no explicit constructors are provided.

The only action taken by the implicit default constructor is to call the superclass constructor using the
super() call. Constructor arguments provide you with a way to provide parameters for the initialization of
an object.

Below is an example of a cube class containing 2 constructors. (one default and one parameterized
constructor).

public class Cube1 {

int length;

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 47


Question Bank –CS2203 Object Oriented Programming

int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}

Note: If a class defines an explicit constructor, it no longer has a default constructor to set the
state of the objects.If such a class requires a default constructor, its implementation must be
provided. Any attempt to call the default constructor will be a compile time error if an explicit
default constructor is not provided in such a case.

22. What are the different statements and its use in java?

A Java method body is a series of zero or more statements. In the Java programming language, statements
are the fundamental unit of execution. All statements except blocks are terminated by a semicolon. Blocks
are denoted by open and close curly braces. Statements are executed for their effects; they do not have
values. There are many different kinds of statements in Java:

 blocks
 local variable declaration statements

 the empty statement

 expression statements

 the if and if-else statements

 the while statement

 the do-while statement

 the for statement


Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 48
Question Bank –CS2203 Object Oriented Programming

 the break statement

 the continue statement

 the return statement

 the switch statement

 the throw statement

 the try statement

 the synchronized statement

Blocks

A block is a series of zero or more statements between a matching set of open and close curly braces. The
bodies of methods and switch statements are blocks. The bodies of if, for, while, and do-while statements
may also be blocks. Also, you can also simply create a new block inside another block by enclosing code
within curly braces. A block contained within another block is itself a statement of the outer block. Blocks
that contain no statements are called empty.

Local Variable Declaration Statements

Declaration statements establish a name, type, and possibly an initial value for a new local variable. Local
variables in Java can be declared anywhere in a method. A local variable need not be initialized where it
is declared, but it must be initialized before it is used. If it isn't, the source file won't compile. For
example, the following snippet of code won't compile:

class Example2a {
public static void main(String[] args) {
int i;
if (i < 100) {
//...
}
}
}
This code won't compile because i is used before it is initialized. To fix this problem, you could initialize i
when you declare it:

class Example2b {
public static void main(String[] args) {
// This compiles fine.
int i = 5;
if (i < 100) {
//...
}
}
}
Alternatively, you could assign a value to i after you declare it, but before you use it:

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 49


Question Bank –CS2203 Object Oriented Programming

class Example2c {
public static void main(String[] args) {
// This compiles fine.
int i;
i = 5;
if (i < 100) {

}
}
}

The "i" in "int i" and the "i = 5" in "int i = 5" are called declarators. As in C++, you can place multiple
local variable declarators, separated by commas, into the same local variable declaration statement, as in:

int i, j = 5, k;

The scope of a local variable extends from the point where the local variable is declared to the end of the
block in which it is declared. No other local variable of the same name can be declared within a local
variable's scope. For example, the following won't compile, because a second local variable i is declared
within the scope of a first local variable i:

// In Source Packet in file expr/ex2/Example2d.java


class Example2d {
public static void main(String[] args) {
// THIS WON'T COMPILE.
int i = 4;
if (i < 10) {
int i = 3; // Can't use name i again.
//...
}
}
}

The Empty Statement


;

The above semicolon is intended to be the entire text of this section. If I were to explain the semicolon in
a sentence, it would be:"The empty statement, represented by a semicolon and nothing else, does
nothing." The alone semicolon above is an empty (English) statement about the empty (Java) statement.

Expression Statements

Expression statements are valid Java expressions that are terminated by a semicolon. Unlike C and C++,
not all kinds of valid expressions can be expression statements. In Java, there are four kinds of expression
statements:

 assignment expressions, such as a += 5, b *= 7, or c = 3


 prefix and postfix increment and decrement, such as ++a, --b, c++, d--

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 50


Question Bank –CS2203 Object Oriented Programming

 method invocations, whether or not they return a value

 object creation expressions, such as new CoffeeCup

All expressions except invocations of methods that don't return a value (methods declared as void) yield a
value upon evaluation. When an expression is used as an expression statement, the end value of the
expression is discarded. Such expressions are evaluated simply for their side effects, as in:
++i;

The if and if-else Statements

The simplest control flow construct in Java is the if statement, which can have an optional else clause.
Here is the format without the else clause:

if (boolean-expression)
statement
The statement can be a simple statement terminated by a semicolon or a block enclosed in curly braces.
Alternatively, you can add an else:

if (boolean-expression)
statement1
else
statement2

As in C++, an else in Java matches the closest if.

Note that Java's if statement differs from that of C++ in that the expression contained in the parentheses
must be boolean. In Java, if i is an int, then if (i) won't compile. You must say if (i != 0). This is also true
of the expressions in the while, do, and for loops. This feature of Java enables the compiler to catch
accidental use of = instead of == inside an expression. For example, if you accidentally type i = 3 instead
of i == 3 in an if expression, it won't compile:

// In Source Packet in file expr/ex2/Example2e.java


class Example2e {
public static void main(String[] args) {
int i = 4;
// In Java, THIS WON'T COMPILE, because the resulting
// value of the expression isn't boolean.
if (i = 3) {
//...
}
}
}

The while and do-while Statements

The while statement looks like this:

while (boolean-expression)

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 51


Question Bank –CS2203 Object Oriented Programming

statement
Java's while loop behaves like C++'s while loop (the difference between the two is that Java's expression
must be boolean.) The boolean- expression is evaluated first. If the expression is true, statement is
executed. This process is repeated until the expression evaluates to false (or a break, continue, or return is
executed, or an exception is thrown).

The do-while statement differs from the while in that the statement is always executed at least once. In a
while loop, if the boolean-expression evaluates to false the first time, statement is never executed. Here is
what a do-while looks like:

do
statement
while (boolean-expression);

The for Statement

The for loop is used to iterate through a sequence of values. It takes the same form as in C++:

for (init-expr; boolean-expr; incr-expr)


statement

The init-expr is an initialization expression, such as i = 0. You can optionally initialize multiple variables
in init- expr by separating each initialization expression by a comma, as in i = 0, j = 0. You can even
declare a new variable in the init- expr:

for (int i = 0; i < 10; ++i) {


//...
}

The scope of this variable i is only within the statement portion of the for itself (in this example, a block).
This contrasts with C++, which also allows you to declare a variable in the init-expr portion of a for loop,
but that variable has a scope as if it were declared just above the for loop. In Java, the variable has a scope
as if it were declared inside the statement of the for loop.

The incr-expr is usually an increment expression such as ++i. Like the init-expr, it can contain multiple
statements separated by commas, as in: ++i, ++j.

The for loop executes by first executing init- expr, then evaluating boolean-expr. If boolean-expr
evaluates to true, statement is executed. After statement is executed, incr-expr is executed and boolean-
expr is checked again. The process of boolean-expr check, statement execution, incr-expr execution
repeats until boolean-expr evaluates to false (or a break, continue, or return is executed, or an exception is
thrown).

Each of the three components in a for loop's parentheses are optional. If you leave out the boolean-expr, it
is assumed to be true. Thus, the customary way to write an infinite loop is:

// a "forever" loop
for (;;) {
//...
Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 52
Question Bank –CS2203 Object Oriented Programming

The switch Statement

The switch statement gives an alternative to a cascade of if- else constructs:

class Example3a {
public static void main(String[] args) {
int i = (int) (Math.random() * 5.0);
if (i == 0) {
System.out.println("Zero");
}
else if (i == 1) {
System.out.println("One");
}
else if (i == 2 || i == 3) {
System.out.println("Two or Three");
}
else {
System.out.println("Other");
}
}
}
The equivalent switch statement is:

// In Source Packet in file expr/ex3/Example3b.java


class Example3b {
public static void main(String[] args) {
int i = (int) (Math.random() * 5.0);
switch (i) {

case 0:
System.out.println("Zero");
break;

case 1:
System.out.println("One");
break;

case 2:
case 3:
System.out.println("Two or Three");
break;

default:
System.out.println("Other");
break;
}
}
}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 53


Question Bank –CS2203 Object Oriented Programming

A switch's expression (i in this example) must be an int. The case labels must be compile-time constants.
They can either be literals, as shown here, or static final fields of some class. A break statement is used in
a switch to indicate the processing for that case is done. You need not have a break for every case. You
can "fall through" to the code for the next case label, as was done by case 2 in this example.

The break and continue Statements

You can use break to exit while, do- while, for, and switch statements. When a break is executed, the
execution continues just after the end of the current simple statement or block. break hops to the end of
the current while, do-while, or switch block.

You can use continue inside a while, do- while, and for loop. When a continue is executed, the rest of the
loop's body is skipped and the boolean-expression is again evaluated.

You can optionally use a label to indicate which loop or switch you want a break to operate on, or which
loop you want a or continue to operate on. This enables you to easily break out of nested loops or switch
statements, or to continue nested loops. To do so you must label the beginning of the loop or switch
statement:

label: statement
Here's an example:

// In Source Packet in file expr/ex4/Example4.java


class Example4 {
public static void main(String[] args) {

dance: for (int i = 0; i < 10; ++i) {


System.out.println(i + ": Swing your partner...");
for (int j = 0; j < 10; ++j) {
System.out.println(j + ": Round and round...");
if (i == 5 && j == 5) {
break dance;
}
}
}
// Execution continues here after break dance is encountered.
System.out.println("Now, twirl on your back.");
}
}

When the break dance statement is executed, the for loop labeled dance (the outer loop) is exited.

The return Statement

The return statement returns from a method, potentially returning a value. If the method is declared as
void, you must use a simple return statement: return;

Otherwise, you must indicate a return value with a type that matches the return type of the method. For
example, a method declared with a boolean return type could have the following statement:
Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 54
Question Bank –CS2203 Object Oriented Programming

return true;

23. Illustrate Inheritance in Java with suitable program.

The derivation of one class from another class is called Inheritance.

Type of inheritance :

A class that is inherited is called a superclass.

The class that does the inheriting is called as subclass.

A subclass inherits all instance variables and methods from its superclass and also has its own variables
and methods.

One can inherit the class using keyword “extends”.

Syntax :

Class subclass-name extends superclass-name

// body of class.

In java, a class has only one super class.

Java does not support Multiple Inheritance.

One can create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass.

However, no class can be a superclass of itself.

EX :

class A //superclass
{
int num1; //member of superclass
int num2; //member of superclass
void setVal(int no1, int no2) //method of superclass
{
num1 = no1;
num2 = no2;
}
}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 55


Question Bank –CS2203 Object Oriented Programming

class B extends A //subclass B


{
int multi; //member of subclass
void mul() //method of subclass
{
multi = num1*num2; //accessing member of superclass from subclass
}
}

class inhe2
{
public static void main(String args[])
{
B subob = new B();
subob.setVal(5,6); //calling superclass method throgh subclass object
subob.mul();
System.out.println("Multiplication is " + subob.multi);
}
}

Output :

Multiplication is 30

Note : Private members of superclass is not accessible in subclass,


superclass is also called parentclass or baseclass,
subclass is also called childclass or derivedclass.

24. Give a explanatory answer to define the difference between Java and C++,
Characteristics of Java and the concepts in java

C++
Java

Java is a true and complete object oriented C++ is an extension of C with object oriented
language. behavior. C++ is not a complete object oriented
language as that of Java.

Java does not provide template classes. C++ offers Template classes.

Java supports multiple inheritance using interface.C++ achieves multiple inheritance by permitting
classes to inherit from multiple classes.

Java does not provide global variables. Global variables can be declared in C++.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 56


Question Bank –CS2203 Object Oriented Programming

Java does not support pointers. C++ supports pointers.

In Java, destruction of objects is performed in In C++, destruction of objects is performed by


finalize method. destructor function.

Java doesn’t provide header files. C++ has header files.

java doesn't contain any data types such as C++ contain data types such as
enum, struct,union. enum, struct,union.

java is platform independent c++ is plotform dependent.

java doesnot contain goto keyword C++ contain goto keyword

Java does not support predessor. C++ support predessor.

These concepts are:

Variables

Computer programs, regardless of programming language, typically read data from somewhere (file,
keyboard, mouse, network etc.), process the data, and write the data somewhere again (to screen, file,
network etc.).

In Java, data is kept in variables. Your Java program first declares variables, then read data into them,
execute operations on the variables, and then write the variables somewhere again. Variables are
explained in more detail in the text on Java variables.

Each variable has a certain data type. The data type determines what kind of data the variable can contain,
and what operations you can execute on it. For instance, a variable could be a number. Numbers can be
added, subtracted, multiplied, divided etc. Or, a variable could be a string (text). String's can be divided
into substrings, searched for characters, concatenated with other strings etc. Java has a set of built-in data
types. These data types are described in more detail in the text on Java data types.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 57


Question Bank –CS2203 Object Oriented Programming

Operations

Operations in Java are the instructions you can use to process the data in the variables. Some operations
work directly on the variables, while other control the program flow. The most important operations are:

 Variable operations
o Variable assignment of values.

o Variable reading of values.

o Variable arithmetic.

o Object instantiation.

 Program flow

o for loops.

o while loops.

o if statements (branches).

o switch statements.

o Method calls.

All of these operations are explained in their own texts.

Classes + Objects

Classes group variables and operations together in coherent modules. A class can have fields, constructors
and methods (plus more, but that is not important now). I will shortly describe fields, constructors and
methods here, but they are explained in more details in their own texts too. Here is a diagram illustrating
classes, fields, constructors and methods:

Objects are instances of classes. When you create an object, that object is of a certain class. The class is
like a template (or blueprint) telling how objects of that class should look. When you create an object, you
say "give me an object of this class".

If you think of a factory producing lots and lots of the same items, then the class would be the blueprint /
manual of how the finished product should look, and the objects would be each of the finished products.
If the factory produced cars, then the blueprint / design manual of the cars to produce corresponds to a
Java class, and the physical cars produced corresponds to Java objects.

Here is a simple diagram illustrating the principle of objects being of a certain class. The class
determines what fields and methods the objects of that class have.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 58


Question Bank –CS2203 Object Oriented Programming

A Java class can contain fields, constructors and methods.

Fields

A field is a variable that belongs to a class or object. It is a piece of data, in other words. For instance, a
Car class could define the field brand which all Car objects would have. Then each Car object can have a
different value for the brand field.

Fields are covered in more detail in the text on Java fields.

Constructors

Constructors are a special kind of method that is executed when an object is created of the given class.
Constructors typically initialize the objects internal fields - if necessary.

Constructors are covered in more detail in the text on Java constructors.

Methods

Methods are groups of operations that carry out a certain function together. For instance, a method may
add to numbers, and divide it by a third number. Or, a method could read and write data in a database etc.

Methods are typically used when you need to group operations together, that you need to be able execute
from several different places. Or, if you just want your code to be easier to read.

25. Explain the Life cycle of Thread with an eg

In the simplest form, a thread's life cycle consists of five states:

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 59


Question Bank –CS2203 Object Oriented Programming

1. New state: this is when the threadable / Thread object is first created by calling the
constructor of the Thread class. For example, our thread is in new state after this
statement Thread newThread = new (runnableObj, threadName);
2. Runnable / Read-to-run state: after calling the start() method on the thread, it enters
the runnable state. That means it is ready to run or to go to some other states. As of the current
version of Java, a thread must enter the runnable state before going to any other state.
3. Running state: a thread is in this state while its run() method is executing. During this
state, the thread can go to blocked state if it gets blocked or has to wait for other threads. When
the run() method finishes, this state ends.
4. Blocked/waiting state: while running a thread can be put to sleep, interrupted or blocked
by other threads. There are many reasons why this may happen. We'll go deeper in the next
section.
5. Terminated / dead state: when a thread reaches this state, its life ends. It can never be
revived again. Normally, a thread enters this state because its run() method has ended. However, a
thread can also be terminated even before it is in the runnable state or during the waiting state by
calling stop() or suspense() on the thread.

Blocked / Waiting state

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 60


Question Bank –CS2203 Object Oriented Programming

As we have seen, a thread can only enter this state while it is running. So why does a thread enter this
state? There are many causes. The main three are:

1. Yielding for another thread: current thread yields for another thread to run first.
Sometimes, we have a particular thread that needs to run immediately, so we call the yield()
method on any running thread to reclaim CPU and resources for the important thread. As the
result, any running thread enters the blocked state until the important thread finishes and releases
the CPU / resources.
2. Waiting for another thread: somewhat similar to yielding, there are times when a thread
needs to wait for another thread to finish first before it can continue. For instance, if two threads
share the same resource, and one of the two is holding that resource, then the other thread needs
to wait for that resource to be released.
3. Waiting for I/O: as you may know, the I/O speed is extremely slow compared to the
CPU speed. Thus, if a thread needs some resources / inputs from I/O, it may need to enter the
waiting state in order to let the CPU work on other threads. This practice is better for utilizing the
CPU because it should be working on other threads / processes instead of siting idle and waiting
for a particular thread.

The Java Thread API provides all functions needed to resolve all the situations above. For example,
the join() method allows one thread to wait for the completion of another thread. Moreover, you can
always cause a thread to enter the waiting state at anytime by calling the method interrupt() on that
thread.

Terminated / Dead State

Once a thread enters this state, it cannot come back to other states. There two distinct ways to terminate
the thread, letting the run() method return and calling stop(), suspense() or destroy() method on the
running thread. The former is recommended because it ensures thread safe. In fact, Java has already
deprecated stop(), suspense() and destroy() method in the new API.

26. Describe package concept to perform arithmetic operations. Explain how to use it?
Packages are used in Java in-order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 61


Question Bank –CS2203 Object Oriented Programming

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

Some of the existing packages in Java are::

 java.lang - bundles the fundamental classes


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

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

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

Creating a package:
When creating a package, you should choose a name for the package and put a package statement with
that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation
types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement
in each source file, and it applies to all types in the file.

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

Example:
Let us look at an example that creates a package called animals. It is common practice to use lowercased
names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:
/* File name : Animal.java */
package animals;

interface Animal {
public void eat();
public void travel();
}
Now put an implementation in the same package animals:
package animals;

/* File name : MammalInt.java */


public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 62


Question Bank –CS2203 Object Oriented Programming

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Now you compile these two files and put them in a sub-directory called animals and try to run as follows:
$ mkdir animals
$ cp Animal.class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels

27. Explain the different states in Life cycle of applet?


An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application, including the
following:

 An applet is a Java class that extends the java.applet.Applet class.

 A main() method is not invoked on an applet, and an applet class will not define main().

 Applets are designed to be embedded within an HTML page.

 When a user views an HTML page that contains an applet, the code for the applet is downloaded
to the user's machine.

 A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a
separate runtime environment.

 The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.

 Applets have strict security rules that are enforced by the Web browser. The security of an applet
is often referred to as sandbox security, comparing the applet to a child playing in a sandbox with
various rules that must be followed.

 Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 63


Question Bank –CS2203 Object Oriented Programming

Life Cycle of an Applet:

Four methods in the Applet class give you the framework on which you build any serious applet:

 init: This method is intended for whatever initialization is needed for your applet. It is called after
the param tags inside the applet tag have been processed.
 start: This method is automatically called after the browser calls the init method. It is also called
whenever the user returns to the page containing the applet after having gone off to other pages.
 stop: This method is automatically called when the user moves off the page on which the applet
sits. It can, therefore, be called repeatedly in the same applet.
 destroy: This method is only called when the browser shuts down normally. Because applets are
meant to live on an HTML page, you should not normally leave resources behind after a user
leaves the page that contains the applet.
 paint: Invoked immediately after the start() method, and also any time the applet needs to repaint
itself in the browser. The paint() method is actually inherited from the java.awt.
A "Hello, World" Applet:

The following is a simple applet named HelloWorldApplet.java:

import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet


{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}

These import statements bring the classes into the scope of our applet class:

 java.applet.Applet.

 java.awt.Graphics.

Without those import statements, the Java compiler would not recognize the classes Applet and Graphics,
which the applet class refers to.

The Applet CLASS:


Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that
a derived Applet class may call to obtain information and services from the browser context.

These include methods that do the following:

 Get applet parameters

 Get the network location of the HTML file that contains the applet

 Get the network location of the applet class directory


Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 64
Question Bank –CS2203 Object Oriented Programming

 Print a status message in the browser

 Fetch an image

 Fetch an audio clip

 Play an audio clip

 Resize the applet

Additionally, the Applet class provides an interface by which the viewer or browser obtains information
about the applet and controls the applet's execution. The viewer may:

 request information about the author, version and copyright of the applet

 request a description of the parameters the applet recognizes

 initialize the applet

 destroy the applet

 start the applet's execution

 stop the applet's execution

The Applet class provides default implementations of each of these methods. Those implementations may
be overridden as necessary.

The "Hello, World" applet is complete as it stands. The only method overridden is the paint method.

Invoking an Applet:

An applet may be invoked by embedding directives in an HTML file and viewing the file through an
applet viewer or Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that invokes
the "Hello, World" applet:

<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 65


Question Bank –CS2203 Object Oriented Programming

The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and height are
also required to specify the initial size of the panel in which an applet runs. The applet directive must be
closed with a </applet> tag.

If an applet takes parameters, values may be passed for the parameters by adding <param> tags between
<applet> and </applet>. The browser ignores text and other tags between the applet tags.

Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that appears
between the tags, not related to the applet, is visible in non-Java-enabled browsers.

The viewer or browser looks for the compiled Java code at the location of the document. To specify
otherwise, use the codebase attribute of the <applet> tag as shown:

<applet codebase="http://amrood.com/applets"
code="HelloWorldApplet.class" width="320" height="120">

If an applet resides in a package other than the default, the holding package must be specified in the code
attribute using the period character (.) to separate package/class components. For example:

<applet code="mypackage.subpackage.TestApplet.class"
width="320" height="120">

Getting Applet Parameters:

The following example demonstrates how to make an applet respond to setup parameters specified in the
document. This applet displays a checkerboard pattern of black and a second color.

The second color and the size of each square may be specified as parameters to the applet within the
document.

CheckerApplet gets its parameters in the init() method. It may also get its parameters in the paint()
method. However, getting the values and saving the settings once at the start of the applet, instead of at
every refresh, is convenient and efficient.

The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init() once,
immediately after loading the applet. (Applet.init() is implemented to do nothing.) Override the default
implementation to insert custom initialization code.

The Applet.getParameter() method fetches a parameter given the parameter's name (the value of a
parameter is always a string). If the value is numeric or other non-character data, the string must be
parsed.

The following is a skeleton of CheckerApplet.java:

import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
int squareSize = 50;// initialized to default size
public void init () {}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 66


Question Bank –CS2203 Object Oriented Programming

private void parseSquareSize (String param) {}


private Color parseColor (String param) {}
public void paint (Graphics g) {}
}

Here are CheckerApplet's init() and private parseSquareSize() methods:

public void init ()


{
String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);
String colorParam = getParameter ("color");
Color fg = parseColor (colorParam);
setBackground (Color.black);
setForeground (fg);
}
private void parseSquareSize (String param)
{
if (param == null) return;
try {
squareSize = Integer.parseInt (param);
}
catch (Exception e) {
// Let default value remain
}
}

The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the library
method Integer.parseInt(), which parses a string and returns an integer. Integer.parseInt() throws an
exception whenever its argument is invalid.

Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad input.

The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does a series of
string comparisons to match the parameter value to the name of a predefined color. You need to
implement these methods to make this applet works.

Specifying Applet Parameters:

The following is an example of an HTML file with a CheckerApplet embedded in it. The HTML file
specifies both parameters to the applet by means of the <param> tag.

<html>
<title>Checkerboard Applet</title>
<hr>
<applet code="CheckerApplet.class" width="480" height="320">
<param name="color" value="blue">
<param name="squaresize" value="30">
</applet>

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 67


Question Bank –CS2203 Object Oriented Programming

<hr>
</html>
Note: Parameter names are not case sensitive.
Application Conversion to Applets:

It is easy to convert a graphical Java application (that is, an application that uses the AWT and that you
can start with the java program launcher) into an applet that you can embed in a web page.

Here are the specific steps for converting an application to an applet.

 Make an HTML page with the appropriate tag to load the applet code.

 Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot be
loaded.

 Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.

 Move any initialization code from the frame window constructor to the init method of the applet.
You don't need to explicitly construct the applet object.the browser instantiates it for you and calls
the init method.

 Remove the call to setSize; for applets, sizing is done with the width and height parameters in the
HTML file.

 Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the
browser exits.

 If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars.
(You can, of course, title the web page itself, using the HTML title tag.)

 Don't call setVisible(true). The applet is displayed automatically.

Event Handling:

Applets inherit a group of event-handling methods from the Container class. The Container class defines
several methods, such as processKeyEvent and processMouseEvent, for handling particular types of
events, and then one catch-all method called processEvent.

Inorder to react an event, an applet must override the appropriate event-specific method.

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;

public class ExampleEventHandling extends Applet


implements MouseListener {

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 68


Question Bank –CS2203 Object Oriented Programming

StringBuffer strBuffer;

public void init() {


addMouseListener(this);
strBuffer = new StringBuffer();
addItem("initializing the apple ");
}

public void start() {


addItem("starting the applet ");
}

public void stop() {


addItem("stopping the applet ");
}

public void destroy() {


addItem("unloading the applet");
}

void addItem(String word) {


System.out.println(word);
strBuffer.append(word);
repaint();
}

public void paint(Graphics g) {


//Draw a Rectangle around the applet's display area.
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);

//display the string inside the rectangle.


g.drawString(strBuffer.toString(), 10, 20);
}

public void mouseEntered(MouseEvent event) {


}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}

public void mouseClicked(MouseEvent event) {


addItem("mouse clicked! ");
}
}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 69


Question Bank –CS2203 Object Oriented Programming

Now let us call this applet as follows:

<html>
<title>Event Handling</title>
<hr>
<applet code="ExampleEventHandling.class"
width="300" height="300">
</applet>
<hr>
</html>

Initially the applet will display "initializing the applet. Starting the applet." Then once you click inside the
rectangle "mouse clicked" will be displayed as well.

Based on the above examples, here is the live applet example: Applet Example.
Displaying Images:

An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the
applet, you use the drawImage() method found in the java.awt.Graphics class.

Following is the example showing all the steps to show images:

import java.applet.*;
import java.awt.*;
import java.net.*;
public class ImageDemo extends Applet
{
private Image image;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{
imageURL = "java.jpg";
}
try
{
URL url = new URL(this.getDocumentBase(), imageURL);
image = context.getImage(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
// Display in browser status bar
context.showStatus("Could not load image!");
}
}
public void paint(Graphics g)

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 70


Question Bank –CS2203 Object Oriented Programming

{
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.javalicense.com", 35, 100);
}
}

Now let us call this applet as follows:

<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="300" height="200">
<param name="image" value="java.jpg">
</applet>
<hr>
</html>
Based on the above examples, here is the live applet example: Applet Example.
Playing Audio:

An applet can play an audio file represented by the AudioClip interface in the java.applet package. The
AudioClip interface has three methods, including:

 public void play(): Plays the audio clip one time, from the beginning.
 public void loop(): Causes the audio clip to replay continually.
 public void stop(): Stops playing the audio clip.

To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class. The
getAudioClip() method returns immediately, whether or not the URL resolves to an actual audio file. The
audio file is not downloaded until an attempt is made to play the audio clip.

Following is the example showing all the steps to play an audio:

import java.applet.*;
import java.awt.*;
import java.net.*;
public class AudioDemo extends Applet
{
private AudioClip clip;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String audioURL = this.getParameter("audio");
if(audioURL == null)
{
audioURL = "default.au";
}
try

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 71


Question Bank –CS2203 Object Oriented Programming

{
URL url = new URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
context.showStatus("Could not load audio file!");
}
}
public void start()
{
if(clip != null)
{
clip.loop();
}
}
public void stop()
{
if(clip != null)
{
clip.stop();
}
}
}

Now let us call this applet as follows:

<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="0" height="0">
<param name="audio" value="test.wav">
</applet>
<hr>
</html>

28. Define Interfaces? Explain the extension of interfaces, implementation and accessing it.
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the
abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different
concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that
a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be
defined in the class.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 72


Question Bank –CS2203 Object Oriented Programming

An interface is similar to a class in the following ways:

 An interface can contain any number of methods.

 An interface is written in a file with a .java extension, with the name of the interface matching
the name of the file.
 The bytecode of an interface appears in a .class file.

 Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.

However, an interface is different from a class in several ways, including:

 You cannot instantiate an interface.

 An interface does not contain any constructors.

 All of the methods in an interface are abstract.

 An interface cannot contain instance fields. The only fields that can appear in an interface must
be declared both static and final.

 An interface is not extended by a class; it is implemented by a class.

 An interface can extend multiple interfaces.

Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:
Example:

Let us look at an example that depicts encapsulation:

/* File name : NameOfInterface.java */


import java.lang.*;
//Any number of import statements

public interface NameOfInterface


{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Interfaces have the following properties:

 An interface is implicitly abstract. You do not need to use the abstract keyword when declaring
an interface.

 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

 Methods in an interface are implicitly public.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 73


Question Bank –CS2203 Object Oriented Programming

Example:
/* File name : Animal.java */
interface Animal {

public void eat();


public void travel();
}

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing to
perform the specific behaviors of the interface. If a class does not perform all the behaviors of the
interface, the class must declare itself as abstract.

Aclass uses the implements keyword to implement an interface. The implements keyword appears in the
class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

This would produce following result:

Mammal eats
Mammal travels

When overriding methods defined in interfaces there are several rules to be followed:

 Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 74


Question Bank –CS2203 Object Oriented Programming

 The signature of the interface method and the same return type or subtype should be maintained
when overriding the methods.

 An implementation class itself can be abstract and if so interface methods need not be
implemented.

When implementation interfaces there are several rules:

 A class can implement more than one interface at a time.

 A class can extend only one class, but implement many interface.

 An interface can extend another interface, similarly to the way that a class can extend another
class.

Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods of the
parent interface.

The following Sports interface is extended by Hockey and Football interfaces.

//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}

//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements
Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define
the three methods from Football and the two methods from Sports.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 75


Question Bank –CS2203 Object Oriented Programming

Extending Multiple Interfaces:

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not
classes, however, and an interface can extend more than one parent interface.

The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

For example, if the Hockey interface extended both Sports and Event, it would be declared as:

public interface Hockey extends Sports, Event

Tagging Interfaces:

The most common use of extending interfaces occurs when the parent interface does not contain any
methods. For example, the MouseListener interface in the java.awt.event package extended
java.util.EventListener, which is defined as:

package java.util;
public interface EventListener
{}
An interface with no methods in it is referred to as a tagging interface. There are two basic design
purposes of tagging interfaces:

Creates a common parent: As with the EventListener interface, which is extended by dozens of other
interfaces in the Java API, you can use a tagging interface to create a common parent among a group of
interfaces. For example, when an interface extends EventListener, the JVM knows that this particular
interface is going to be used in an event delegation scenario.

Adds a data type to a class: This situation is where the term tagging comes from. A class that
implements a tagging interface does not need to define any methods (since the interface does not have
any), but the class becomes an interface type through polymorphism.

29. What are the Different Exceptions caught, Explain the types with eg program.
An exception is a problem that arises during the execution of a program. An exception can occur for many
different reasons, including the following:

 A user has entered invalid data.

 A file that needs to be opened cannot be found.

 A network connection has been lost in the middle of communications, or the JVM has run out of
memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 76


Question Bank –CS2203 Object Oriented Programming

To understand how exception handling works in Java, you need to understand the three categories of
exceptions:

 Checked exceptions: A checked exception is an exception that is typically a user error or a


problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the
file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time
of compilation.
 Runtime exceptions: A runtime exception is an exception that occurs that probably could have
been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are
ignored at the time of compliation.
 Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored
at the time of compilation.
Exception Hierarchy:

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is derived
from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions normally happen in case of
severe failures, which are not handled by the java programs. Errors are generated to indicate errors
generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot
recover from errors.

The Exception class has two main subclasses : IOException class and RuntimeException Class.

Java defines several exception classes inside the standard package java.lang.

The most general of these exceptions are subclasses of the standard type RuntimeException.
Since java.lang is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 77


Question Bank –CS2203 Object Oriented Programming

Java defines several other types of exceptions that relate to its various class libraries. Following is the list
of Java Unchecked RuntimeException.

Exception Description

ArithmeticException Arithmetic error, such as divide-by-zero.

ArrayIndexOutOfBoundsExc
Array index is out-of-bounds.
eption

Assignment to an array element of an incompatible


ArrayStoreException
type.

ClassCastException Invalid cast.

IllegalArgumentException Illegal argument used to invoke a method.

IllegalMonitorStateExceptio Illegal monitor operation, such as waiting on an


n unlocked thread.

IllegalStateException Environment or application is in incorrect state.

Requested operation not compatible with current


IllegalThreadStateException
thread state.

IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySizeException Array created with a negative size.

NullPointerException Invalid use of a null reference.

NumberFormatException Invalid conversion of a string to a numeric format.

SecurityException Attempt to violate security.

StringIndexOutOfBounds Attempt to index outside the bounds of a string.

UnsupportedOperationExce
An unsupported operation was encountered.
ption

Following is the list of Java Checked Exceptions Defined in java.lang.

Exception Description

ClassNotFoundExceptio
Class not found.
n

CloneNotSupportedExc Attempt to clone an object that does not implement the


eption Cloneable interface.

IllegalAccessException Access to a class is denied.

Attempt to create an object of an abstract class or


InstantiationException
interface.

InterruptedException One thread has been interrupted by another thread.

NoSuchFieldException A requested field does not exist.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 78


Question Bank –CS2203 Object Oriented Programming

NoSuchMethodExceptio
A requested method does not exist.
n

Exceptions Methods:

Following is the list of important medthods available in the Throwable class.

SN Methods with Description

public String getMessage()


1 Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.

public Throwable getCause()


2
Returns the cause of the exception as represented by a Throwable object.

public String toString()


3
Returns the name of the class concatenated with the result of getMessage()

public void printStackTrace()


4 Prints the result of toString() along with the stack trace to System.err, the error output
stream.

public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The element at index 0
5
represents the top of the call stack, and the last element in the array represents the method
at the bottom of the call stack.

public Throwable fillInStackTrace()


6 Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.

Common Exceptions:

In java it is possible to define two catergories of Exceptions and Errors.

 JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the
JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException,
ClassCastException,
 Programmatic exceptions . These exceptions are thrown explicitly by the application or the API
programmers Examples: IllegalArgumentException, IllegalStateException.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 79


Question Bank –CS2203 Object Oriented Programming

30. Explain try, catch and finally statements with eg.

A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs
in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.

Example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the
array which throws an exception.

// File Name : ExcepTest.java


import java.io.*;
public class ExcepTest{

public static void main(String args[]){


try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}

This would produce following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


Out of the block

Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following:

try

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 80


Question Bank –CS2203 Object Oriented Programming

{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of them after a
single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in
the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement. This continues until the exception either is caught
or falls through all catches, in which case the current method stops execution and the exception is thrown
down to the previous method on the call stack.

Example:

Here is code segment showing how to use multiple try/catch statements.

try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}

The throws/throw Keywords:


If a method does not handle a checked exception, the method must declare it using the throwskeyword.
The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using
the throw keyword. Try to understand the different in throws and throw keywords.

The following method declares that it throws a RemoteException:

import java.io.*;
public class className
{

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 81


Question Bank –CS2203 Object Oriented Programming

public void deposit(double amount) throws RemoteException


{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}

A method can declare that it throws more than one exception, in which case the exceptions are declared in
a list separated by commas. For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException:

import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}

The finally Keyword

The finally keyword is used to create a block of code that follows a try block. A finally block of code
always executes, whether or not an exception has occurred.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter
what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 82


Question Bank –CS2203 Object Oriented Programming

Example:
public class ExcepTest{

public static void main(String args[]){


int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}

This would produce following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


First element value: 6
The finally statement is executed

Note the following:

 A catch clause cannot exist without a try statement.

 It is not compulsory to have finally clauses whenever a try/catch block is present.

 The try block cannot be present without either catch clause or finally clause.

 Any code cannot be present in between the try, catch, finally blocks.

Dept. of CSE -A.C.T College of Engineering & Technology, Nelvoy Page 83

S-ar putea să vă placă și