Documente Academic
Documente Profesional
Documente Cultură
QUESTION BANK
YEAR : II
REGULATION : 2008
Prepared By
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.
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.
* 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. .
* The function can be invoked without the use of an object. The friend function has its argument as
objects, seen in example below.
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.
#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
};
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 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:
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.
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.
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
};
main()
{
exforsys e;
e.test();
cout<<"The result is:"<
//Calling of Friend Function with object as argument.
}
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.
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.
Note: the friend class member function average is passed the object of Numbers class as parameter.
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.
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.
#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);
};
int main()
{
Numbers ob(23, 67);
Average avg;
cout<<”The average of the numbers is: ”<<avg.average(ob);
return 0;
}
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.
#include <iostream>
using namespace std;
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
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.
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.
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:
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.
#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
2. We can do programming through STRUCTURE, but NOT with the help of the CLASS.
5. C is a collection of FUNCTIONS.
7. In C, DATA can be MOVE openly around in the system from function to function.
8. C cannot support all the feature of the C++.while c++ supports all the features of C.
C++ DOES NOT REQUIRED FORMAT SPECIFIER for printing and scanning variable.
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
();
} }
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);
}
}
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
Input: 10
Output: Ten
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..
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;
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++
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];
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.
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.
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
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.
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
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.
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;
}
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 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);
}
};
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:
PROGRAM
#include<iostream.h>
#include<conio.h>
class stu
{
private: char name[20],add[20];
int roll,zip;
public: stu ( );//Constructor
~stu( );//Destructor
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:
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.
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.
cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs).
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:
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:
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:
will be shown on the screen one following the other without any line break between them:
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):
First sentence.
Second sentence.
Third sentence.
Additionally, to add a new-line, you may also use the endl manipulator. For example:
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.
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
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:
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.
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:
int main ()
{
string mystr;
cout << "What's your name? ";
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:
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;
}
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).
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
};
}
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
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.
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:
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:
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();
Output:
Enter the Number: 5
Factorial is: 120
Factorial is: 120
b.parameterized constructor
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
}
Example:
#include<iostream>
#include<conio.h>
class Example {
// Variable Declaration
int a,b;
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();
Sample Output:
Im Constructor
Values :10 20
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:
// constructor
X(int, int , int = 0);
// copy constructor
X(const X&);
class Y {
public:
// 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.
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 :
void show( )
{
cout <<"\n"<<num <<" raise to "<<power <<" is " <<ans;
}
};
main( )
{
clrscr( );
class power p1,p2(5);
p1.show( );
p2.show( );
return 0;
}
d.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);
}
};
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();
}
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.
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;
}
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 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).
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 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;
}
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.
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”;
}
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.
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.
#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;
}
};
int main() {
f();
// A try block
try {
g();
}
catch (Excep& e) {
cout << e.error << endl;
}
try {
Test x;
}
catch(...) { }
}
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 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."
If you follow the rule of array initialization then you can write the above statement as follows:
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>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
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.
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.
#include <iostream>
#include <cstring>
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
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>
int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
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.
In object oriented terms, overriding means to override the functionality of any existing method.
Example:
class Animal{
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.
class Animal{
This program will throw a compile time error since b's reference type Animal doesn't have a method by
the name of bark.
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 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.
JVM has various sub components internally. You can see all of them from the above diagram.
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.
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.
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).
int length;
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
expression statements
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.
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:
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:
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:
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 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
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:
while (boolean-expression)
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 loop is used to iterate through a sequence of values. It takes the same form as in C++:
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:
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
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:
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;
}
}
}
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.
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:
When the break dance statement is executed, the for loop labeled dance (the outer loop) is exited.
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;
Type of inheritance :
A subclass inherits all instance variables and methods from its superclass and also has its own variables
and methods.
Syntax :
// body of class.
One can create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass.
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;
}
}
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
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++.
java doesn't contain any data types such as C++ contain data types such as
enum, struct,union. enum, struct,union.
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.
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 arithmetic.
o Object instantiation.
Program flow
o for loops.
o while loops.
o if statements (branches).
o switch statements.
o Method calls.
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.
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.
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.
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.
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.
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.
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.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations
) providing access protection and name space management.
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;
There are some important differences between an applet and a standalone Java application, including the
following:
A main() method is not invoked on an applet, and an applet class will not define main().
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.
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:
import java.applet.*;
import java.awt.*;
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.
Get the network location of the HTML file that contains the applet
Fetch an image
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
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>
.
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">
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.
import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
int squareSize = 50;// initialized to default size
public void init () {}
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.
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>
<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.
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.)
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;
StringBuffer strBuffer;
<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.
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)
{
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.javalicense.com", 35, 100);
}
}
<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.
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
{
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();
}
}
}
<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.
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.
An interface cannot contain instance fields. The only fields that can appear in an interface must
be declared both static and final.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:
Example:
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.
Example:
/* File name : Animal.java */
interface Animal {
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{
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.
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.
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.
//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.
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:
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 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.
To understand how exception handling works in Java, you need to understand the three categories of
exceptions:
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.
Java defines several other types of exceptions that relate to its various class libraries. Following is the list
of Java Unchecked RuntimeException.
Exception Description
ArrayIndexOutOfBoundsExc
Array index is out-of-bounds.
eption
UnsupportedOperationExce
An unsupported operation was encountered.
ption
Exception Description
ClassNotFoundExceptio
Class not found.
n
NoSuchMethodExceptio
A requested method does not exist.
n
Exceptions Methods:
Common Exceptions:
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.
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.
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following:
try
{
//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:
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;
}
import java.io.*;
public class className
{
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 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.
}
Example:
public class ExcepTest{
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.