You are on page 1of 32

CS6456 - OBJECT ORIENTED PROGRAMMING HAND MATERIAL

Staff Incharge: S.Ashok Kumar AP/CSE


Part-A -2 marks
1. Differentiate between class and object
Class
A class has a unique name

Object
Several objects with different names can be

Scope of the class is persistent throughout the

created for same class


Objects can be created and destroyed as per

program.

requirements.

2. Differentiate between Data encapsulation and Data abstraction


Data encapsulation
It is a binding of data and the functions

Data abstraction
Data abstraction helps in representing only the

together in a single entity called class.

essential features by hiding all the

Data encapsulation is achieved by inheritance

implementation details.
Data abstraction is represented by using
abstract class

3. What is an abstract class?


Abstract class is the class that does not specify the implementation details, but specifies what are the
operations to be done.
We cannot create object for an abstract class.
Example: Vehicle is an abstract class.
4. What is ADT?
ADT stands for Abstract Data Type. It does not specify the implementation details, but specifies what
are the operations to be done.
5. What is the use of ADT?
The user need not have to understand the implementation details.
Finding of bugs is easy.
6. What is Object Oriented Programming?
Object Oriented Programming is a collection of objects.
7. What are friend functions?
Friend function is not a member function of the class but it can access the private and protected
members of a class.

8. What is polymorphism?

Polymorphism means many forms.


Polymorphism is the ability of object to exhibit more than one forms
9. List the operators that cannot be overloaded?
Scope resolution operator ( :: )
Size of operator
Conditional operator( ?: )
Dot operator ( . )
10. What is a container?
Container is a collection of objects of different type.
These objects store the data.
11.What are called iterators?
It is also used to traverse the contents of container.
Iterators are basically objects and sometimes they can be pointers.
It is used to specify the position in the container.
12. What is STL?
STL is Standard Template Library.
STL is a collection of C++ classes and functions
13. Define exception. Give example.
Exception is an run time error or some abnormal situations which occurs in a program.
Exception can be handled by using exception handler.
Example: Division by zero
14. What are virtual functions? How are virtual functions declared in C++?
A virtual function is a member function that is declared within a base class and redefined in the derived
class.
Virtual functions are declared using the keyword virtual.
15. Define pure virtual function and mention its usage.
Pure virtual function does nothing
Syntax for declaring pure virtual function
virtual void functionname( ) =0;
Usage: It is used in the abstract class
16. What are virtual base class?
In order to overcome the ambiguity problem which occurs in multiple inheritance, the base class is made
virtual.

17. What is the difference between function template and template function?
Function template
In function template, single function template
is written and that can handle elements of
different data type.
Example
template<class T>
void add(T a, T b)
{
.
}

Template function
Template function is invoking the function
with different parameters
Example:
add(10,20);
add(10.5,12.7);

18. What is JVM?


JVM is Java Virtual Machine.
It is a set of software and program components.
Java is platform independent due to JVM.
19. What is a byte code? Mention its advantage.
The class file created while compiling java code is called byte code.
Byte code is used to make a java as a platform independent language.
20. Why is java language called as robust?
Java is robust because it can be used on multiple platforms.
Java provides a good mechanism for error checking.
21. How do we allocate an array dynamically in Java?
We allocate memory for the array dynamically using new operator.
Example:
int a[ ]=new int[10]; //Dynamically allocates a memory for an array a.
22. How is keyword super is used in Java?
Keyword super is used to call super class constructor and super class functions.
23. Java does not support multiple inheritance? Why?
Class A
Void display( )

Class B
Void display( )

Class C
Class As void display( )
Class Bs void display( )
When Class C is inherited from class A and class B, Class As void display( ) and Class Bs void display(
) will becomes members of class C.

When display( ) function is called, compiler doesnt know which display( ) to call and hence
AMBIGUITY problem arise.
24. What are packages?
Package is a mechanism in which variety of classes, functions and interfaces are grouped together.
25. What is API package?
API package is a collection of packages which includes the important classes and interfaces which are
used by the programmer while developing java applications.
Some of the Java API packages are java.io, java.util, java.lang etc.
26. Define interface. State its use.
Interface is similar to the class which contains data members and the functions. But the functions are not
defined in interface
Use: It is used to hide the implementation details from the rest of the code.
27. What is a thread? How does it differ from a process?
Thread is a light weight process which shares a same address space and same heavy weight process. (i.e)
Multiple threads executes in a process simultaneously.
Thread
Thread is a light weight process
Several threads share a same address space and

Process
Process is a heavy weight process
Processes requires separate address space

share the same heavy weight process


Switching from one thread is another thread is

Switching from one process to another is costly

of low cost
28. What are the two ways of creating java threads?
Java threads can be created by using Thread class and Runnable interface
29. What is multithreading?
Multiple threads executes in a process which performs multiple tasks simultaneously.
30. What is a stream?
Stream is a channel on which a data flow from sender to receiver.
31.What are the types of streams?
Byte Stream =>Read and write one byte at a time.
Character Stream=> Read and write one character at a time.

1. Explain in detail about the various object oriented concepts. (OR) Explain the features of Object
Oriented Programming. (OR) Explain the various important paradigm of Object Oriented

Programming with example


1.Class 2.Objects 3.Data encapsulation 4.Inheritance 5.Polymorphism 6.Dynamic binding 7.Data abstraction
1. class
A class is a collection of objects of same type.
Example:
class student
{
int rollno;
public:
void get( );
void display( );
};
2. objects
An Object is a instance of a class.
Example: student s; where student is the class name and s is the object.
3. Data encapsulation
It is a binding of data and the functions together in a single entity called class.

Data Encapsulation

4. Inheritance
New class is derived from the old class.
It provides REUSABILITY.
Types of Inheritance: Single level inheritance, multiple inheritance, multilevel inheritance, hierarchical
inheritance, hybrid inheritance.
5. Polymorphism
The ability to take more than one form is called polymorphism
Types:
1. Compile time polymorphism - Function overloading, Operator Overloading
Function overloading: Same function name is used with different arguments.
Operator overloading: Same operator is used to perform different function.
2. Run time polymorphism Virtual Function
6. Dynamic binding
Dynamic binding is the process of matching the function call with the correct definition at the run time.
7. Data abstraction
Data abstraction helps in representing only the essential features by hiding all the implementation
details.
Example: class

2.Explain constructor and destructor in detail with necessary examples.


Constructor

Destructor

Definition

Definition

Constructor is automatically called


when the object of the class is created.
Constructor name is same as the class
name.

The destructor is called when the object


is destroyed.
The destructor name is same as the
class name but preceded with tilde(~)
symbol.

Types of constructor:
Default Constructor=> It is called whenever the object of the class is created.
It set the initial value for the data members of class.
Parameterized constructor=> It is called whenever values are passed to the object.
It is used to set the new values to the data members of class.
Copy constructor=> It is called when a object is passed as argument to another object
It takes the reference to an object of same class as argument.
Overloaded Constructor => Constructor with different arguments
Dynamic constructor=> Dynamic constructor allocates memory for objects using the operator new.
Example program
#include<iostream.h>
#include<conio.h>
image( )
{
height=0;
width=0;
}

image(int x,int y)
{
height=x;
width=y;
}

image(image &obj)
{
height=obj.height;
width=obj.width;
}

Default Constructor

class image
{
private:
int height,width;
public:

Overloaded Constructor
Parameterized Constructor

Copy Constructor
void display( )

{
cout<<height;
cout<<width;
}
~image( )
{
}
};
void main( )
{
image obj1;
// Calling the default constructor
image obj2(3,5); //Calling the parameterized constructor
image obj3(obj2); //Calling the Copy Constructor
obj3.display( );
}
Output: 3 5
Dynamic constructor:
Program
#include<iostream.h>
#include<conio.h>
class image
{
private:
int *height,*width;
public:
image(int x, int y)
{
height=new int;

Dynamic constructor

width=new int;
*height=x;
*width=y;
}
cout<<*width;
}
~image( )
{

void display( )
{
cout<<*height;

Dynamic Destructor

delete height;
delete width;
}

};
void main( )

{
image obj(3,5);
obj.display( );
}
3. Explain friend function with an example

A friend function is not a member function of the class but it can access the private members of the
class
It cannot be invoked by the object of particular class but the object is passed as a argument to friend
function.
friend function is declared by using keyword friend
Example Program to add two values using friend function
#include<iostream.h>
#include<conio.h>
class A
{
private:
int a,b;
friend void add(A obj);
public:
void get( )
{
a=10;
b=20;
}};
void add(A obj)
{
cout<<obj.a+obj.b;
}
void main( )
{
A obj;
obj.get( );
add(obj); // Here object is passed as an argument to the friend function add
}
4. Write the list of rules for overloading operator with example. (OR)Explain operator overloading with
example. (OR)Define polymorphism. Explain types of polymorphism in detail.
Operator Overloading: Same operator is used to perform different function.
Rules for operator overloading:

Only existing operators can be overloaded


The basic meaning of operator cannot be changed
Unary operator takes no argument and no return value
Binary operator takes one argument and must return a value

General Syntax for operator overloading


returntype operator operatorname(arguments)
{
statements;
}
Example Program1(Unary Operator Overloading)
#include<iostream.h>

#include<conio.h>
class unary
{
int x,y;
public:
void get( int a, int b)
{
x=a;
y=b;
}
void operator - ( )
{
x= -x;
y= -y;
}
void display( )
{
cout<<x<<y;
}};
void main( )
{
unary obj;
obj.getdata(10,-20);
-obj;
obj.display( );
getch( );
}
Output: -10 20
Example program 2(Binary Operator Overloading)
#include<iostream.h>
#include<conio.h>
class vector
{
public:
int x;
vector(int a)
{
x=a;
}
int operator +(vector b)
{
return x+b.x;
}
int operator -(vector b)
{
return x-b.x;
}
int operator *(vector b)
{
return x*b.x;
}

void main( )
{
vector a(10);
vector b(20);
vector c=a+b;
cout<<c.x;
c=a-b;
cout<<c.x;
c=a*b;
cout<<c.x;
}
5. Describe templates and its types.
Templates is used as a tool for generic programming
By using template, we write a single function that can handle elements of different data type. (i.e) It is
used in re-usability of code
Types of templates
Function template
Class template
Function template
Class template
Function template is a function which can
In class template, data members and functions
handle elements of different data types.
of the class uses template parameter as its type.
Template function is invoking the function
Here t is a template parameter
with different parameters
#include<iostream.h>
#include<iostream.h>
#include<conio.h>
#include<conio.h>
template<class t>
template<class t>
class maximum
t max(t x,t y)
Function template
{
{
t x,y;
if(x>y)
public:
return x;
t max(t x,t y)
else
{
return y;
if(x>y)
}
return x;
}
void main( )
else
{
return y;
}};
cout<<max(10,20);
Template function void main()
cout<<max(10.5,5.5);
{
cout<<max(c,e);
maximum <int> obj1;
}
maximum <float> obj2;
maximum <char> obj3;
cout<<obj1.max(10,20);
cout<<obj2.max(10.5,5.5);
cout<<obj3.max('c','e');
}
6. Explain the types of inheritance in C++ with examples.
Types of Inheritance:
1.Single inheritance

2.Multiple inheritance

3.Multilevel inheritance

4.Hierarchical inheritance

5.Hybrid inheritance

1. Single inheritance
In single inheritance, the derived class is derived from a single base class
Base Class

Derived Class
Example Program:
#include<iostream.h>
#include<conio.h>
class base
{
public:
int a;
};
class derived:public base
{
public:
void display( )
{
cout<<a;
}
};
void main( )
{
derived d;
cin>>d.a;
d.display( );
}
2.Multiple Inheritance
In multiple inheritance, the derived class is derived from multiple base class.
Base Class1

Base Class2

Derived Class
Example Program:
#include<iostream.h>
#include<conio.h>
class base1
{
public:
int a;
};
class base2

{
public:
int b;
};
class derived : public base1 , public base2
{
public:
void display( )
{
cout<<a<<b;
}
};
void main( )
{
derived d;
cin>>d.a;
cin>>d.b;
d.display( );
}
3.Multilevel Inheritance
In multilevel inheritance, the derived class is derived from the derived class itself.
Base Class
Derived Class1
Derived Class2
Example Program
#include<iostream.h>
#include<conio.h>
class base
{
public:
int a;
};
class derived1:public base
{
public:
int b;
};
class derived2:public derived1
{
public:
void display( )
{
cout<<a<<b;
}};
void main( )

{
derived2 d2;
cin>>d2.a;
cin>>d2.b;
d2.display( );
}
4.Hierarchical Inheritance
Many derived classes are derived from the single base class.
Base Class

Derived Class1
Example Program
#include<iostream.h>
#include<conio.h>
class base
{
public:
int a;
int b;
};
class derived1:public base
{
public:
void display( )
{
cout<<a+b;
}};
class derived2:public base
{
public:
void display( )
{
cout<<a-b;
}};
void main( )
{
derived1 d1;
derived2 d2;
cin>>d1.a;
cin>>d1.b;
d1.display( );
cin>>d2.a;
cin>>d2.b;
d2.display( );
}
5.Hybrid Inheritance

Derived Class2

It is a combination of two or more inheritance.


Base Class 1

Derived Class1

Base Class 2

Derived Class2
7. What is virtual function? State the rules for virtual function. Write a C++ program to declare virtual
function and pure virtual function.
(OR)
Explain run time polymorphism in C++ with an example.
Virtual Function:
A virtual function is a member function that is declared within a base class and redefined in the
derived class.
Virtual functions are declared using the keyword virtual.
Rules for virtual function:

Virtual function must be declared in a public section of a class.


Virtual function can be a friend function to another class.
Virtual function cannot be declared as static.
The class cannot have virtual constructor but can contain virtual destructor.

Virtual function
1. A virtual function is a member function that

Pure Virtual function


1. Pure virtual function does nothing. The class

is declared within a base class and redefined in

which contains pure virtual function is called

the derived class.


2. Object for the class can be created for the

abstract class.
2. Object for the class cannot be created for the

class containing virtual function


#include<iostream.h>
#include<conio.h>
class base
{
public:
int a;

class containing pure virtual function.


#include<iostream.h>
#include<conio.h>
class base
{
public:
int a;

virtual void function( )


{
cout<<"Inside base class";
cout<<a;
}
};
class derived:public base

virtual void function( )=0;


};
class derived:public base
{
public:
void function( )
{
cout<<"inside derived class";

{
public:
void function( )
{
cout<<"inside derived class";
cout<<a*a;
}};
void main( )
{
base *b;
derived d1;
b=&d1;
cout<<Enter a value;
cin>>d1.a;
b->function( );
}

cout<<a*a;
}};
void main( )
{
base *b;
derived d1;
b=&d1;
cout<<Enter a value;
cin>>d1.a;
b->function( );
}

Output:
Enter a value: 4
Inside derived class 16

Output:
Enter a value: 4
Inside derived class 16

8. Explain Exception handling mechanism in detail with example.


Exception Handling=> Process of catching and handling the exception is called Exception Handling
When a run time errors occur in a program, those exceptions are handled by using exception handler.
The exceptions are handled by using try, catch and throw statements.
try=> try block is a block where the exceptional condition may occur.
throw => When exception occurs, it is thrown using throw statement.
catch => The exception thrown is handled in catch block.
General syntax for exception handling
try {
// block of code where error may occur
if(error occurs)
throw exception;
else
Statements;
}
catch (ExceptionType exobj)
{
//block of code which handles exception
}
int a,b;
cout<< enter two values;
cin>>a>>b;
try

Example program for division by zero exception Single try


block single catch block
#include<iostream.h>
#include<conio.h>
void main( )
{

{
if(b==0)
{
throw b;
}
else
{
cout<<a/b;
}
}
catch(int b)
{
cout<<cant divide by zero;
}
}
Output:
Enter the values of a and b 4 0
Cant divide by zero
Example program for division by zero exception Single try block multiple catch block
#include<iostream.h>
#include<conio.h>
void main( )
{
int a,b;
cout<< enter two values;
cin>>a>>b;
try
{
if(b==0)
{
throw cant divide by zero;
}
else
{
throw a/b;
}
}
catch(char *str)
{
cout<<str;
}
catch(float a/b)
{
cout<<a/b;
}}
Example program for division by zero exception :User defined exception
class userdefined
{
public:

char str[20];
userdefined(char *s)
{
str = s;
}
};
void main( )
{
int a,b;
cin>>a>>b;
try
{
if(b= =0)
{
throw userdefined( cant divide by zero );
}
else
{
cout<<a/b;
}
}
catch(userdefined obj)
{
cout<<obj.str;
}
}
9. Explain array and its types in detail with suitable examples.
Array is a collection of elements of same data type that are stored under a common name
1. One-dimensional array
An array with only one subscript is called one dimensional array
Syntax for declaring one-dimensional array:
datatype arrayname[ ]=new datatype[size];
Example:
int a[ ]=new int[10];
where a is a single dimensional array that can store a maximum of 10 elements.

Program:
import java.util.Scanner;
import java.io.*;
class single
{
public static void main(String args[ ])
{
int n,i;

int a[ ]=new int[10];


System.out.println("Enter the n value");
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
System.out.println("Enter the elements of array");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt( );
}
System.out.println(The elements of the array is);
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}}
Output
Enter the n value 4
Enter the elements of array 5 2 9 3
The elements of the array array is 5 2 9 3
2.Two-dimensional array
An array with two subscript is called two dimensional array.
Elements in two dimensional array is represented in rows and columns.
Syntax for declaring two-dimensional array:
datatype arrayname[ ][ ]=new datatype[size][size];
Example:
int a[ ][ ]=new int[3][3];
where a is a two dimensional array of 3 rows and 3 columns that can store a maximum of 9 elements.
Program to perform matrix addition:
import java.util.Scanner;
class matrix
{
public static void main(String args[ ])
{
int n,i,j,k,choice;
int a[ ][ ]=new int[3][3],b[ ][ ]=new int[3][3],c[ ][ ]=new int[3][3];
Scanner sc = new Scanner(System.in);
System.out.println("enter the elements of Matrix A");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a[i][j]=sc.nextInt( );
}}
System.out.println("The elements of Matrix A");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{

System.out.print(" "+a[i][j]);
}
System.out.println( );
}

}}
Output: Enter the elements of matrix A 1 2 3 4 5 6 7 8 9
Elements of matrix A is
1

3. Multi-dimensional array
An array with more than two subscript is called multi dimensional array.
Syntax for declaring multi-dimensional array:
datatype arrayname[ ][ ][ ][ ]=new datatype[size][size][size][size];
Example:
int a[ ][ ][ ]=new int[3][3][3];
where a is a three dimensional array that can store a maximum of 27 elements.
int a[ ][ ][ ][ ]=new int[3][3][3][3];
where a is a four dimensional array that can store a maximum of 81 elements.
10. Explain in detail about the inheritance mechanism in java with example programs.
1. Single inheritance
In single inheritance, the derived class is derived from a single base class
Base Class

Derived Class
Example Program
import java.io.*;
import java.util.Scanner;
class base
{
int a;
}
class derived extends base
{
void get( )
{
Scanner sc = new Scanner(System.in);
a=sc.nextInt( );
}
void display( )
{

System.out.println(a);
}}
class single
{
public static void main(String args[ ])
{
derived d=new derived( );
d.get( );
d.display( );
}}
2.Multilevel Inheritance
In multilevel inheritance, the derived class is derived from the derived class itself.
Base Class
Derived Class1
Derived Class2
Example program:
import java.io.*;
import java.util.Scanner;
class base
{
int a;
}
class derived1 extends base
{
int b;
}
class derived2 extends derived1
{
void get( )
{
Scanner sc = new Scanner(System.in);
a=sc.nextInt( );
b=sc.nextInt( );
}
void display( )
{
System.out.println(a);
System.out.println(b);
}}
class multilevel
{
public static void main(String args[])
{
derived2 d2=new derived2( );
d2.get( );
d2.display( );
}}

3.Hierarchical Inheritance
Many derived classes are derived from the single base class.
Base Class

Derived Class
Example Program
import java.io.*;
import java.util.Scanner;
class base
{
int a;
int b;
}
class derived1 extends base
{
void get( )
{
Scanner sc = new Scanner(System.in);
a=sc.nextInt( );
b=sc.nextInt( );
}
void display( )
{
System.out.println(a);
System.out.println(b);
}}
class derived2 extends base
{
void get( )
{
Scanner sc = new Scanner(System.in);
a=sc.nextInt( );
b=sc.nextInt( );
}
void display( )
{
System.out.println(a);
System.out.println(b);
}}
class hierarchical
{
public static void main(String args[ ])
{
derived1 d1=new derived1( );
derived2 d2=new derived2( );
d1.get( );
d2.get( );

Derived Class

Derived Class

d1.display( );
d2.display( );
}}
4.Hybrid Inheritance
It is a combination of two or more inheritance.
Base Class 1
Base Class 2

Derived Class1

Derived Class2
11. Write a java program to perform matrix addition.
import java.util.Scanner;
import java.io.*;
class matrixadd
{
public static void main(String args[ ])
{
int n,i,j,k,choice;
int a[ ][ ]=new int[3][3],b[ ][ ]=new int[3][3],c[ ][ ]=new int[3][3];
Scanner sc = new Scanner(System.in);

System.out.println("enter the elements of Matrix A");


for(i=0;i<3;i++)
Get the values for matrix A

{
for(j=0;j<3;j++)
{
a[i][j]=sc.nextInt( );
}}

System.out.println("enter the elements of Matrix B");


for(i=0;i<3;i++)

Get the values for matrix B

{
for(j=0;j<3;j++)

System.out.println(Addition of two matrices);

for(i=0;i<3;i++)

b[i][j]=sc.nextInt( );

}}

for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];

Addition of two matrices

System.out.print(" "+c[i][j]);
}
System.out.println( );
}

}
}

Output: Enter the elements of matrix A 1


Enter the elements of matrix B 1
Addition of two matrices 2
4
8
10
14
16

2
2

3
3

4
4

5
5

6
6

7
7

8
8

9
9

6
12
18

12. Write a java program to perform matrix multiplication.


import java.util.Scanner;
import java.io.*;
class matrixmultiply
{
public static void main(String args[ ])
{
int n,i,j,k,choice;
int a[ ][ ]=new int[3][3],b[ ][ ]=new int[3][3],c[ ][ ]=new int[3][3];
Scanner sc = new Scanner(System.in);

System.out.println("enter the elements of Matrix A");


for(i=0;i<3;i++)
Get the values for matrix A

{
for(j=0;j<3;j++)
{
a[i][j]=sc.nextInt( );
}}

System.out.println("enter the elements of Matrix B");


for(i=0;i<3;i++)

Get the values for matrix B

{
for(j=0;j<3;j++)

System.out.println(Multiplication of two matrices);

for(i=0;i<3;i++)

b[i][j]=sc.nextInt( );

}}

for(j=0;j<3;j++)
{
c[i][j]=0;

Multiplication of two matrices

for(k=0;k<3;k++)
{

for(i=0;i<3;i++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];

}}}

for(j=0;j<3;j++)
{
System.out.print("
Displaying the resultant matrix

"+c[i][j]);

}
System.out.println( );
}

}}
13. Write a Java program to perform all the string operations.
import java.util.Scanner;
class string
{
public static void main(String args[ ])
{
int ch;
String str1,str2;
do
{
System.out.println("1. String compare");
System.out.println("2. String concatenation");
System.out.println("3. String length");
System.out.println("4. String reverse");
System.out.println("5. Replacing a character from string");
System.out.println("6. String uppercase and lowercase");
System.out.println("7. Substring of a given string");
Scanner sc=new Scanner(System.in);
System.out.println("Enter your choice");
ch=sc.nextInt( );
switch(ch)
{
case 1: System.out.println("Enter string 1");
str1=sc.next();
System.out.println("Enter string 2");
str2=sc.next();
if(str1.equals(str2)==true)
System.out.println("Strings are equal");
else
System.out.println("Strings are not equal");
break;
case 2: System.out.println("Enter string 1");
str1=sc.next();
System.out.println("Enter string 2");
str2=sc.next();
System.out.println(str1+str2);
break;
case 3: System.out.println("Enter the string");
str1=sc.next();
System.out.println("Length of the string is");
System.out.println(str1.length( ));
break;
case 4: System.out.println("Enter the string");
str1=sc.next();
String rev=new StringBuffer(str1).reverse( ).toString();
System.out.println("\nString before reverse:"+str1);
System.out.println("String after reverse:"+rev);
break;

case 5: System.out.println("Enter the string");


str1=sc.next();
System.out.println("String after the character has been replaced");
String s=str1.replace('v','j');
System.out.println(s);
break;
case 6: System.out.println("Enter the string");
str1=sc.next();
System.out.println("String in uppercase is");
System.out.println(str1.toUpperCase());
System.out.println("String in Lowercase is");
System.out.println(str1.toLowerCase());
break;
case 7: System.out.println("Enter the string");
str1=sc.next();
System.out.println(str1.substring(2,7));
break;
}
}while(ch<=7);
}
}
14. What are packages? How do they created and used ?
Package is a process of grouping classes, methods and interfaces together.
Creation and using package:
Create a folder pack
Create a file a.java inside the folder pack

pack
a.java

a.java:
package pack;
public class a
{
public void display( )
{
System.out.println(class a is added to package);
}
}
Create a file packageclass.java
packageclass.java
import pack . a;
class packageclass
{
public static void main(String args[ ])
{
a obj=new a( );

pack
a.java

Packageclass.java

obj.display( );
}}
15. Explain interface in detail with suitable example.
Interface is denoted by a keyword interface.
The methods declared within interface have no body.
Interface can use only public access modifier.
Syntax:
access_modifier interface interface_name
{
datatype variable_name=value;
return_type function_name(parameters);
}
Example:
public interface I
{
int a=5;
void display( );
}
Extending Interface: => Members of interface I1 becomes members of interface I2
I1.java:
public interface I1
{
int a=5;
void display( );
}
I2.java:
public interface I2 extends I1
{
void show( );
}
Implementing interface:
Syntax
class classname implements interfacename
{
Statements;
}
Example:
class A implements I2
{
Void display( )
{
System.out.println(a);
}

Void show( )
{
System.out.println(a*a);
}
}
class interface
{
public static void main(String args[ ])
{
A obj=new A( );
obj.display( );
obj.show( );
}}
Example 2: Multiple inheritance in Java using interface
If a class implements two or more interface, then it is called multiple inheritance.
When a class implements the interface I1 and I2 , then the members of the interfaces will become the
members of the class.
I1.java
public interface I1
{
int a=5;
public void display( );
}
I2.java:
public interface I2
{
public void show( );
}
multiple.java:
class A implements I1 , I2
{
public void display( )
{
System.out.println(a);
}
public void show( )
{
System.out.println(a*a);
}
}
class multiple
{
public static void main(String args[ ])
{
A obj=new A( );
obj.display( );
obj.show( );
}}

Output:
Value of a is 5
Square of a is 25
Predefined Interface - Runnable:
class A implements Runnable
{
public void run( )
{
System.out.println("Inside run");
}
public void show( )
{
System.out.println("Predefined Interface-Runnable");
}
}
public class predefined
{
public static void main(String args[ ])
{
A obj=new A( );
obj.show( );
}}

16. Explain the life cycle of thread with example program. (OR) Explain multithreading with an example.
(OR) What is a thread? What is multithreading? Explain the states of thread with an example.
Thread:
Thread is a Light Weight Process(LWP)
Multithreading:
Multiple threads are executed in parallel when they are independent.
Execution of thread may be in any order.
States of thread:
New state, Runnable state, Waiting state, Timed waiting state, Blocked state, Terminated state.
New

Runnable

Terminated

Wait

Blocked
Timed
Waiting

New State:
In this state, Thread is created.
Runnable state:
In this state, Thread start its execution.
Waiting state:
In this state, Thread will be in waiting state while some other higher priority thread executes at that time.
Timed Waiting State:
In this state, Thread will be in waiting state for some specified time. After that, thread will enter into
runnable state.
Blocked State:
In this state, thread will be in blocked state when thread issues an Input/Output request. After that it will
go to runnable state.
Terminated State:
When the execution completes, the thread goes to terminated state.

Example Program
class A extends Thread
{
String str;
A(String str)
{
Thread t=new Thread(this); =>Thread is created
str=s;
t.start( ); =>Thread start its execution
}
public void run( )
{
try
{
Thread.sleep(100); =>Thread is in Timed waiting state
}
catch(Exception e)
{

System.out.println(exception caught);
}
System.out.println(str);
}
}
class multithread
{
public static void main(String a[ ])
{
A obj1=new A(1st thread);
A obj2=new A(2nd thread);
A obj3=new A(3rd thread);
}}
17. Explain Exception handling in Java with example programs.
Exception
Exception is a run time error that occur in a execution of program.
Exception Handling
The process of catching and handling exception is called exception handling.
General syntax for exception handling
try {
// block of code where error may occur
}
catch (ExceptionType exobj)
{
//block of code which handles exception
}
Example program for division by zero exception: Single catch
import java.util.Scanner;
class singlecatch
{
public static void main(String args[ ])
{
int a,b,c;
Scanner sc=new Scanner(System.in);
a=sc.nextInt( );
b=sc.nextInt( );
try
{
c=a/b;
System.out.println(c);
}
catch(Exception e)
{

System.out.println(cant divide by zero);


}
}}
Example program : Multiple catch
import java.util.Scanner;
class multiplecatch
{
public static void main(String args[ ])
{
int a,b,c,d[ ]=new int[2];
Scanner sc=new Scanner(System.in);
a=sc.nextInt( );
b=sc.nextInt( );
try
{
c=a/b;
System.out.println(c);
}
catch(Exception e)
{
System.out.println(cant divide by zero);
}
finally
{
try
{
for(int i=0;i<4;i++)
{
d[i] = sc.nextInt( );
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println( Array Out of bound);
}
}
}}
Userdefined Exception
It is the exception which is defined by the user
Example program for user defined exception when input negative numbers
class A extends Exception
{
A(String str)
{
super(str);

}
}
class userdefined
{
public static void main(String args[ ])
{
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt( );
try
{
if(n<0)
{
throw new A(number is negative);
}
}
catch(A e)
{
System.out.println(e.getMessage( ));
}
}}

********************************PRACTICE MAKES PERFECT*****************************


**************************************ALL THE BEST*************************************

You might also like