Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Oop Practice Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

OBJECT ORIENTED PROGRAMMING PRACTICE

QUESTIONS
C++
1. What is an Object? What is the difference between an array of objects and an array of pointers
to objects? Explain with an example.
2. Discuss memory requirements for the class, object, data members, member function, and static
class members.
3. What is the output of the following code snippet? Justify your answer.
#include <iostream>
using namespace std;
int x=40;
int& setx(){ return x; }
int main(){
setx() = 22;
cout<< "x=" << x<<endl;
return 0;
}
4. What are the characteristics of friend function? State the difference between friend class and
friend function. Write a syntax for how a function f () of class Y can be the friend of class X.
5. Write a C++ program to show the order of construction and destruction of a global object, static
object, nameless object, an object declared in the main function, an object declared in f() which
is invoked from main(), object declared in a block of code.
6. Write the difference between Abstraction and encapsulation.
7. Raising a number n to the power p is the same as multiplying n by itself p times. Write a function
called power() that takes a double value for n and an integer value for and returns the result as a
double value. Use a default argument of 2 for p, so that that argument, the number will be
squared. Write a main() function that gets values from the user to test the function.
8. Create a class called TIME that has separate data members for hours, minutes, and seconds. A
member function should display the time in the format hh: mm: ss. Another member function
should add two objects of type TIME passed as arguments. Write a program in C++ to do this.
Write a main() that creates the objects of TIME and it’s methods.
9. Create a class Stack to implement Stack data structure with constructors & destructors. Define
suitable member functions for insertion & deletion of elements to and from the Stack. Write a
program in C++ to do this by clearly specifying the overflow and overflow conditions.
10. Explain Deep copy and Shallow copy with the example of Stack.
11. Write a program as follows:
Create a class Employee with three instance variables employee_id, name, and salary. Write one
parameterized constructor (use initializer list) and one show method (display the details of the
employee). Create a class Manager with three instance variables manager_id, name, and salary.
Write one parameterized constructor (use initializer list) and one show method (display the
details of the manager). Write one method to promote, which will increase the salary of a
particular employee. Now create multiple Employee objects and one Manger objects. Call all the
relevant procedures from the objects.
12. What is the significance of a member method being declared static?
13. What is the significance of a data member being declared static?
14. What is a Copy constructor? Explain with code.
15. How many constructors and destructors will be called for the following code, explain.
#include<iostream>
using namespace std;
class A
{
int x;
public:
A(){cout<<”Object created”<<endl;}
A(int a){x=a; cout<<”Object created”<<endl}
~A(){ cout<<”Object destroyed”<<endl;

};

int main()
{
A * s = new A[5];

for(i=0;I<5;iI++)
s[i]= A(i);
delete []s;
return 0;
}
16. Write two different classes A and B. Each of them has private data member data1, and data2
respectively. Write a function addBoth(……,…) to add the values contained in data1 and data2.
addBoth function is an independent function, which is not a member of class A and class B
17. What is the difference between a pass-by value and a pass-by reference in C++ ?
Explain with examples.
18. Write a program to declare a void pointer, assign the address of an integer to it, and then print
the value
19. The methods in line number 2 and 3 are special functions. What are they called and what should
these methods be typically used for?
class Sample {
Sample();
~Sample();
};
20. C++ compilers already support shallow copy constructors. So why should a programmer write a
copy constructor code in a C++ program if it is required? Explain with code..
21. Create a class QUEUE to implement queue data structure with constructors and
destructors. Define suitable member functions for the insertion and deletion of elements to and
from the queue. Write a program in C++ to do this by clearly specifying the overflow and
underflow conditions.
22. Define a class to represent a bank account. Include the following members.
Data members
(i) Account number
(ii) Balance amount in the account.
Member functions.
(iii) To assign initial values
(iv) To display account number and balance.
(v) void moneyTransfer( ….) To transfer amount from one
account from one account to other .
Write a program to test the successful transfer of money from one account to other.
Use the concept of passing object reference and object by a pointer to solve the problem.
23. Differentiate Deep copy and shallow copy constructor with proper code and figure.
24. What are the features of Object-oriented programming?
25. Write a class (named Complex) consisting of two member variables to represent real part and
imaginary part of a complex number and it has three member functions: void getData(): to take
input at runtime for data members.
void showData(): to display the complex number.
Complex addComplex(Complex):
to add two complex numbers and return the result through the object.
26. Explain constructor overloading with meaningful code.
27. What will be the output of the following C++ code? Explain.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char s1[6] = "Hello";
char s2[6] = "World";
char s3[12] = s1 + " " + s2;
cout<<s3;
return 0;
}
28. Write three differences between pointers and references.
29. Write a C++ code to implement the following scenario.
Each of the two classes named “CSE_faculty” and “ECE_faculty”, has one public member “name”
and one private member “highest degree”. Write a function that compares the highest degree
of a “CSE_faculty” and an “ECE_faculty” and if they are the same, “CSE_faculty_name and
ECE_faculty_name have same qualification” would be printed, where “CSE_faculty_name” and
“ECE_faculty_name” are the name of the CSE_faculty and ECE_faculty, respectively. You can
give any name as you please. Please explain your code.
30. Write a code in C++ to show the use of this pointer. Please write the output as well.
31. A static integer named “a” belongs to the class named “test”. How and where will you initialize
it?
32. Write a C++ code to show how to declare and use a pointer to the object of a class.
33. Define friend class. Give one example code in C++ to implement a friend class.
34. Write three advantages of object-oriented programming over procedural-oriented
programming.
35. What will be the output of the following C++ code? Explain your output.
#include <iostream>
#include <string>
using namespace std;
class A{
int a;
public:
A(){
cout<<"Default constructor called\n";
}
A(const A& a){
cout<<"Copy Constructor called\n";
}
};
int main()
{
A obj;
A a1 = obj;
A a2(obj);
return 0;
}
36. Complete the following program such that it generates output: 5.
#include<iostream>
using namespace std;
int main()
{
Test t1(5);
t1->print();
return 0;
}
37. Why = operator cannot be overloaded with the friend function?
38. When constants and objects need to be two operands, the friend function must be used. Justify
the statement with a proper example in C++.
39. Write the main function of the following program to show an example of runtime
polymorphism.
#include <iostream>
#include <string>
using namespace std;
class A
{
float d;
public:
virtual void func(){
cout<<"Hello this is class A\n";
}
};
class B: public A
{
int a = 15;
public:
void func(){
cout<<"Hello this is class B\n";
}
};
40. Correct the statement: If a class is derived privately from a base class then no members of the
base class is inherited.
41. What will be the output of the following program? Explain your output.

#include<iostream>
using namespace std;
class B1{
public:
B1() { cout<<”Constructor of B1”<<endl; }
~B1() { cout<<”Destructor of B1”<<endl; }
};
class B2{
public:
B2() { cout<<”Constructor of B2”<<endl; }
~B2() { cout<<”Destructor of B2”<<endl; }

};
class D:public B1, public B2{
public:
D():B2(), B1() { cout<<”Constructor of D”<<endl; }
~D() { cout<<”Destructor of D”<<endl; }

};
int main(){
D obj;
return 0;
}
42. Write two problems you faced that were solved by writing a function template. Why would you
use templates over macros?
43. Write a function template in C++ that will find an item in an array of a given size.
44. What will be the output of the following C++ code if we give input as 65 as age? Explain your
output.
#include<iostream>
#include<exception>
using namespace std;
class userdefined:public exception
{ public:
const char * what() const throw(){ return "out of range";}
};
int main(){
int age;
cin>>age;
try{
if(age>60)
throw userdefined();
}
catch(userdefined & obj)
{
cout<<obj.what();
}
return 0;
}
45. With an example, name and explain the macros of the stdarg library that are required when
writing functions in C++ that can handle variable number of arguments.
46. Consider the following program and answer the following two questions.
The program implements a typical type of inheritance that gives compilation error when not
implemented properly. Identify and explain why the piece of code will give compilation error. Fix the
error.
The expected output of the program:
In child 1
Value of i is: 10
After you fix the compilation error, what else do you have to modify in the program to get this
output? Explain your answer.
#include <iostream>
using namespace std;
class parent {
protected: int i=10;
public:void show(){cout<<"In parent "<<endl;}
};
class child1:public parent {
public:void show() {cout<<"In child 1 "<<endl;}
};
class child2:public parent {
public:void show() {cout<<"In child 2 "<<endl;}
};
class problemChild: public child1, public child2 {
public:void show() {cout<<"Value of i is: "<<i<<endl;}
};
int main() {
parent *p;
p=new child1();
p->show();
p=new problemChild();
p->show();
}

47. Some of the most commonly used binary operators in C++ are the arithmetic operators e.g. plus
(+), minus (-), multiplication (*), and division (/). There are different ways to overload these
operators: putting as member, declaring as friend or the non-member way. Which approach is
more appropriate? Justify your answer with code excerpts.
With an example explain how the throw keyword can be used to specify a list of exceptions that can
be thrown by a method. In this context also explain the syntax and usage of empty throw.

48.
#include <iostream>
using namespace std;
namespace sample1
{
int rel = 300;
}
namespace sample2
{
int rel=400;
}
int main() {}
What are the different ways you can specify which namespace to use when printing the value of
the variable "rel" in main method
49. Please add proper function in the following incomplete code snippet such that it runs and give
the following output:
#include<iostream>
using namespace std;
class test{
int i;
};

int main(){
test obj;
cout<<"Enter input"<<endl;
cin>>obj;
cout<<obj;
return 0;
}
Expected Output:
Enter input
5
5
50. How to define an abstract class in C++? What is the use of an abstract class? Why cannot you
instantiate an abstract class?
51. How to implement multiple inheritance in C++?
52. Create an user defined exception “test” with a character pointer as member variable,
parameterized constructor and the what method.
53. Read the following code snippet and complete it such that:
If the input is “123”, the exception “test” will be thrown with the input “123”,caught and the error
message “Entered Number” will be shown via calling “what()” function of the test class.
int main(){
char * input = new char[100];
cout<<"Enter input"<<endl;
cin>>input;
}

54. Write a function template for adding two inputs. Specialize the template such that for string
input, it appends the given string inputs.
55.
class student {…};
class study:public student{…};
class sport:public student{…};
class result:public study,public sport{…};
In the above pseudo-code, the sequence of inheritance causes a certain type of compilation
issue. Identify the issue and correct the pseudo-code mentioning the solution.
56. What are the different types of inheritance? Draw a diagram for each type and explain.
57.
#include<iostream>
class father {
public: void showAge() {
cout << "Father's age 55"<<endl;
} };
class son:public father {
public: void showAge() {
cout << "Son's age 20"<<endl;
} };
int main() {
father *fptr; fptr = new father();
fptr->showAge();
fptr=new son(); fptr->showAge();
delete fptr; }
What will be the output of the above program? Taking this program as example, explain what a
virtual function is and how virtual function can be used to change the behaviour of the above
program.
58. What is the difference between class and function template? Write a single function to add two
numbers of user’s specified type and return the result using template.
59. Illustrate the different uses of the keyword “throw”, using code excerpts, w.r.t exception
handling in C++. (Please note: Writing relevant lines of code, instead of the whole program, will
suffice as long as the correct meaning is conveyed without any ambiguity.)
60. What is class template? Explain with example, how to define a method outside class using class
template?
61. How can you implement runtime polymorphism in C++, Explain with example?
62. Write operator overloading function to distinguish between prefix and postfix increment
operation on object of a class.
63. Write a program in C++ to read three integers x, y and z and evaluate r given by r = z / (x − y)
Use exception handling to throw an exception in case division by zero is attempted.
64. Write three characteristics of a virtual function in C++.
65. What is the use of a namespace?
66. What will be the output of the following codes? Explain your answer. Please note that there
might be compiler or runtime errors.
#include <iostream>
using namespace std;
int main()
{
try
{
throw 10;
}
catch (...)
{
cout << "default exceptionn";
}
catch (int param)
{
cout << "int exceptionn";
}

return 0;
}
(ii)#include <iostream>
using namespace std;
template <typename T>
T maxn(T x, T y)
{
return (x > y)? x : y;
}
int main()
{
cout << maxn(3, 7) << std::endl;
cout << maxn(3.0, 7.0) << std::endl;
cout << maxn(3, 7.0) << std::endl;
return 0;
}
67. Write a code in C++ to implement post-increment operator and << operator. Using your code,
what will be the output of the following input? Suppose the class name is Test.
Test t(10);
Test t2=t++;
cout<<”t=”<<t<<endl<<”t2=”<<t2<<endl;
68. Write a class template in C++ to implement stack and in main function, show how your code is
working with different data types.
69. class Mydiv has data members num1 and num2 of type int and two member functions, read()
and divide(). Member function read() prompts user to enter two numbers. Member function
divide() throws an exception if b equals zero. Else it returns the division result. Write the
program with suitable throw, try and catch constructs.
70. What is catch(…)? Explain with an example.
Java
1. Explain the working of the Java Virtual Machine (JVM) and how it contributes to the portability
of Java applications.
2. Describe the distinction between an abstract class and an interface in Java, providing examples
for clarity.
3. Explain the concept of Garbage Collection and its importance in memory management Java.
4. In Java, what are the key differences between public, protected, and default (no specifier)
access specifiers?
5. In Java, encapsulation is achieved by bundling data and methods to operate as a single unit
called class - Explain with example.
6. Is the Java compiler platform-independent? Justify your answer.
7. Compare Java’s primitive data types with reference data types.
8. What are the key differences between function overloading and function overriding in Java?
9. Discuss how command-line arguments are handled in Java.
10. Provide an example program that takes a list of numbers as command-line arguments and
calculates their sum.
11. Describe the process of object creation in Java using the new keyword.
12. What happens behind the scenes when an object is created in Java?
13. Discuss how inheritance enhances code reusability in Java. Illustrate this with an example where
inheritance is utilized in a Java program to reuse existing code.
14. Explain the purpose of a constructor in Java. Is it possible for a constructor to be private in Java?
Support your explanation with an example.
15. What are the differences between final, finally, and finalize in Java?
Provide examples demonstrating the use of final, finally, and finalize keywords in Java...
16. Explain the use of packages in Java. Provide an example demonstrating how to create and use a
package in a Java program.
17. What is the purpose of the super keyword in Java? Provide an example to demonstrate the use
of super keyword.
18. Explain why Java is both portable and secure.
19. Say a Java program named Test.java is compiled and there is only one public class named Test
containing public static void main, is there. What will it generate? How to run the program with
command line arguments? Where are the command line arguments stored?
Say in the above program Test.java, you need to keep a variable that will be accessed and
modified by each object and the modifications are visible to each object. How do you declare
the variable and access it?
20. Is there any concept of destructor in Java? If yes, write the syntax to declare it. If not, how do
you think memory is deallocated in Java?
21. Write True or False: For a class in Java to be abstract, the class must contain an abstract method.
Write an example Java code showing the use of an abstract class. Also, write the output of the
program.
Can we instantiate an abstract class? If yes, write the syntax to do it. If no, explain your answer.
22. Which object-oriented paradigm concept is/are satisfied using an abstract class?
23. Why interface is used? Give an example Java code showing the use of an interface. Write the
output of your program.
24. Describe how Java handles multithreading. Provide a code example of creating and running
threads.
25. In a class named Semester_answer, there will be name, roll, and no_of_ questions_attempted
as instance variables and calculate_marks method as an instance method. In your semester
exam, if a student answers more than four questions, a user-defined exception will be thrown
“Marks of one question not to be added” inside the calculate_marks method. Write a Java code
to implement this scenario.
26. What is the difference of use of default and protected access specifier?
27. Write a Java program to do the following:
Create three threads named one, two, and three in the main thread. Each thread will print
multiples of 3, 4, and 5, respectively. The main thread waits for the child threads to join it
28. Write a Java program to implement a JApplet to do the following:
There is an input textfield taking any string as input from the user. Your program will convert
lowercase letters to uppercase and vice versa and show that in the output textfield. For
example, if AbCd is given as input, aBcD will be shown as the output
29. ls it possible in Java to implement multiple inheritance? Explain with an example how a derived
class can inherit from more than one base classes.
30. Write down the differences between interfaces and abstract classes.
31. What is an abstract method? How is it implemented in Java?
32. Write a program in java swing/applet to draw a polygon filled with green colour using the rgb
format.
33. What is the difference between Java applets and Java application programs?
34. Explain the difference between creating a thread by extending the "Thread" class and creating a
thread by implementing the "Runnable" interface, with suitable programs.
35. How do we define "try" and "catch" block in Java?
36. Write a sample Java code to demonstrate ArrayIndexOutOfBoundsException,
ArithmeticException, NullPointerException exceptions.
37. Create a package shape containing classes Circle, Triangle and Rectangle. Every class of this
package should contain two methods, viz., area and perimeter. Write a sample Java code that
can import shape package and use the methods to calculate area and perimeter of the
respective shape.
38. With examples explain the scenario where the method in an interface can have a method body.
39. What is thread synchronization and why is it needed?.
40. What is package ? How do we add a class or an interface to a package ? What do you mean by
CLASSPATH ?
41. In a triangle, the sum of two sides is greater than the third. If we are given three values a, b ,c
then a+b>c, b+c>a, c+a>b
Write a sample code in java for class Triangle which throw an exception of type
TriangleException(user defined exception) if any one of the above conditions are not satisfied
else evaluate the area of a triangle and display the output.
42. Write a sample code in java to create a package mycomplex containing a class Complex. This
class contains a constructor to initialize a complex number and three methods, viz., add, sub and
mul to return sum, difference and product of two complex numbers respectively. Import the
package to your sample code and show the use of the existing methods.
43. What is partial implementation of an interface?
44. What are exceptions ? Explain the user defined exceptions and system defined exceptions with
suitable examples.
45. How do we define try and catch block ? Is it essential to catch all types of exceptions ? Explain.
Briefly explain the use of "this" and "super" keywords ?
46. What is multithreading programming ? Explain thread life cycle.
47. Differentiate between checked and unchecked exceptions in java.
48. What is the difference between throw and throws? Explain with example.
49. Write an example Java program to implement thread communication using wait() and notify()
method.
50. Write a program in java to Print the name, priority, and Thread group of the thread.Change the
name of the current thread to “MyThread”.Display the details of current thread.
51. Create two user defined exceptions viz. TooHot and TooCold. Write a Java program and throw
TooHot if the temperature exceeds 40 degrees and throw TooCold if the temperature be less
than 20 degrees.
52. What are the similarities and differences between synchronized method and synchronized block
in java thread, explain with examples.
53. Write a Java swing program which will accept two value in text boxes and display addition result
in third text box.
54. With example explain any two methods of JFrame, JLabel and JPanel in Java swing.
55. What is package? What is the use of it? Why do we need import statement?
56. Write the uses of finally block in Java.
57. Explain how an event delegation model works. Write a Java swing program to explain the said
concept.
58. What is the default type of variables in an interface?
59. Consider the following Java program:
import java.util.*;
interface Department{
String depName="CSE";
void display();
}
class TestDepartment implements Department{
public void display(){
depName="CSE(AIML)";
System.out.println("Department name is " + depName); }
public static void main(String args []){
Department ref = new TestDepartment ();

ref.display();
}
}
Is there any error in the code? If yes fix the error.

You might also like