Oops Lab Manual
Oops Lab Manual
LAB MANUAL
Class : II CSE
Sem : III
Syllabus
PREREQUISITES :
1.Basic Computer knowledge.
2.Programming in C Lab
COURSE
OBJECTIVES:
1. Justify the philosophy of object-oriented programming and the concepts of encapsulation,
abstraction, inheritance, and Polymorphism.
2. To make the student learn an object oriented way of solving problems using java.
3. To make the students to write programs using multi-threading concepts and handle
exceptions.
LIST OF EXPERIMENTS:
1. Write a C++ program using Static Data Members
2. Write a C++ program to implement the Multiple constructor in a class
3. Write a C++ program to implement Operator overloading for Unary and binary operator
4. Write a C++ program to implement Constructor in derived classes
5. Write a Java program to implement Control Statements
6. Write a Java program to implement Multi-threaded programming
7. Write a Java program to implement Multiple Inheritance
8. Write a Java program to implement Polymorphism
ADDITIONAL
EXPERIMENTS:
1. Program to overload unary and binary operator as Nonmember function.
2. Write a Java program to develop simple application(project) using OOP’s concept.
EX.NO :- 1 STATIC DATA MEMBERS
Aim:
Write a C++ program using Static data member to record the occurrences of the entire object.
Algorithm:
STEP 1: Start the program.
STEP 2: Declare the class name as Stat with data members and member functions.
STEP 3: The constructor Stat() which is used to increment the value of count as 1to
assign the variable code.
STEP 4: The function showcode() to display the code value.
STEP 5: The function showcount() to display the count value.
STEP 6: Stop the program.
Program
#include<iostream.h>
#include<conio.h>
class stat {
int code;
static int count;
public:
stat()
{
code = ++count;
}
void showcode()
{
cout<< "\n\tObject number is :" << code;
}
int stat::count;
void main()
{
clrscr();
stat obj1, obj2;
obj1.showcount();
obj1.showcode();
obj2.showcount();
obj2.showcode();
getch();
}
OUTPUT:
Count Objects:2
RESULT:
Thus a C++ program using static data member to record the occurences of the entire
object is executed successfully.
EX.NO:-2(a) MULTIPLE CONSTRUCTOR-COPY CONSTRUCTOR
(Factorial of agivennumber)
AIM:
ALGORITHM:
STEP 2: Declare the class name as CopyConstructor with data members and member
functions.
STEP 3: The constructor CopyConstructor() with the argument to assign the value.
STEP 4: To call the function factorial_calculate() do the following steps (5 to 8).
STEP 5: For i=1 to var
STEP 6: Calculate fact*i to assign to fact.
STEP 7: Increment the value as 1.
STEP 8: Return the value fact.
STEP 9: Create objects for CopyConstructor class in the main Function
STEP 10: Pass arguments using Constructor and Copy Constructor
STEP 11: Print the result.
STEP 12: Stop the program.
PROGRAM:
#include<iostream>
#include<conio.h> using
namespace std;
class CopyConstructor
{
int var, fact;
public:
CopyConstructor(int temp)
{
var = temp;
}
int factorial_calculate()
{
fact = 1;
for (int i = 1; i<= var; i++)
{
fact = fact * i;
}
return fact;
}
};
int main()
{
int n;
cout<< "Simple Copy Constructor For Find Factorial Example Program InC++\
n";
cout<< "\nEnter the Number : ";
cin>>n;
CopyConstructor obj(n);
CopyConstructorcpy = obj;
cout<< "\n" << n << " Factorial is:" <<obj.factorial_calculate(); cout<< "\n" << n <<
" Factorial is:" <<cpy.factorial_calculate(); getch();
return 0;
}
OUTPUT:
5 Factorial is:120
RESULT:
Thus executed a C++ program using copy constructor to find the factorial of given
number is executed successfully.
EX.NO:-2(B) MULTIPLE CONSTRUCTOR - DEFAULT CONSTRUCTOR
(Printthestudent details)
AIM:
ALGORITHAM:
STEP 1: Start the process
PROGRAM:
#include<iostream.h>
#include<conio.h>
class stu
{
private: char name[20],add[20]; int
roll,zip;
public: stu();
~stu();
void read( );
}; void disp( );
stu :: stu( )
{
void main( )
{
stu s; clrscr(
);
s.read ();
s.disp ();
getch();
}
OUTPUT:
RESULT:
Thus a C++ program using default constructor and destructor to print the student
details is executed successfully.
EX. NO :- 3(A) OPERATOR OVERLOADING FOR UNARY OPERATOR
AIM:
To write a program to find the complex numbers using unary operator overloading.
ALGORITHM:
PROGRAM:
#include<iostream.h>
#include<conio.h>
class complex
{
int a, b, c;
public:
complex()
{
}
void getvalue()
{
cout<< "Enter the Two Numbers:";
cin>> a>>b;
}
void operator++()
{
a = ++a;
b = ++b;
}
void operator--()
{
a =--a;
b =--b;
}
void display()
{
cout<< a << "+\t" << b << "i" <<endl;
}
};
void main()
{
clrscr(); complex
obj;
obj.getvalue();
obj++;
cout<< "Increment Complex Number\n";
obj.display();
obj--;
cout<< "Decrement Complex Number\n";
obj.display();
getch();
}
OUTPUT:
Enter the two numbers: 3 6
Increment Complex Number
4+ 7i
Decrement Complex Number
3+ 6i
RESULT:
Thus a C++ program using unary operator overloading to find the complex numbers is
executed successfullysuccessfully.
EX. NO :- 3(B) OPERATOR OVERLOADING FOR BINARY OPERATOR
(Add two complexnumbers)
AIM:
To write a program to add two complex numbers using binary operator
overloading.
ALGORITHM:
PROGRAM:
#include<iostream.h>
#include<conio.h>
class complex
{
int a, b;
public:
void getvalue()
{
cout<< "Enter the value of Complex Numbers a,b:"; cin>>
a>>b;
}
complex operator+(complex ob)
{
complex t;
t.a = a + ob.a;
t.b = b + ob.b;
return (t);
}
void display()
{
cout<< a << "+" << b << "i" << "\n";
}
};
void main()
{
clrscr();
complex obj1, obj2, result, result1;
obj1.getvalue();
obj2.getvalue();
cout<< "Result:";
result.display();
result1.display();
getch();
}
OUTPUT:
4 5
Enter the value of Complex Numbers a, b 2 2
Input Values 4
+5i
2 +2i
Result
6+ 7i
2+ 3i
RESUL:
Thus C++ program using binary operator overloading to add the two complex numbers is
executed successfully.
EX.NO:-4 CONSTRUCTOR IN DERIVED CLASSES
AIM:
ALGORITHM:
PROGRAM:
#include <iostream.h>
class alpha (
private:
int x;
public:
alpha(int i)
{
x = i;
cout<< "\n alpha initialized \n";
}
void show_x()
{
cout<< "\n x = "<<x;
}
);
class beta (
private:
float y;
public:
beta(float j)
{
y = j;
cout<< "\n beta initialized \n";
}
void show_y()
{
cout<< "\n y = "<<y;
}
);
class gamma : public beta, public alpha (
private:
int n,m;
public:
gamma(int a, float b, int c, int d):: alpha(a), beta(b)
{
m = c;
n = d;
cout<< "\n gamma initialized \n";
}
void show_mn()
{
cout<< "\n m = "<<m;
cout<< "\n n = "<<n;
}
);
void main()
{
gamma g(5, 7.65, 30, 100);
cout<< "\n";
g.show_x();
g.show_y();
g.show_mn();
}
OUTPUT:
beta initialized
alpha initialized
gamma initialized
x=5
y = 7.65
m = 30
n = 100
RESULT:
AIM:
To write a Java program to implement IF control statement.
ALGORITHM:
STEP 1: Start the program
STEP 2: Declare the variable and asign the value for the variable STEP 3: Check the condition
using if statement
STEP 4: If, the condition is true, print the result, else compiler exit the program.
STEP 5: Stop the program.
PROGRAM:
OUTPUT:
x is greater than y
RESULT:
AIM:
To write a Java program to implement IF-ELSE control statement.
ALGORITHM:
STEP 1: Start the program
STEP 2: Declare the variable and asign the value for the variable STEP 3: Check the condition
using if else statement
STEP 4: If, the condition is true, print the if result, else, printtheelse result.
STEP 5: Stop the program.
PROGRAM:
import java.io.*; public
class MyClass
{
public static void main(String[] args)
{
int time = 20; if
(time < 18)
{
System.out.println("Good day.");
}
else
{
System.out.println("Good evening.");
}
}
}
OUTPUT:
Good evening.
RESULT:
ALGORITHM:
STEP 1: Start the program
STEP 2: Declare the variable and asign the value for the variable STEP 3: Check the condition
using if else ladder statement
STEP 4: If, the condition is true, print the condition result, else print the default result.
PROGRAM:
import java.io.*; public
class MyClass
{
public static void main(String[] args)
{
int time = 22; if
(time < 10)
{
System.out.println("Good morning.");
}
else if (time < 20)
{
System.out.println("Good day.");
}
else
{
System.out.println("Good evening.");
}
}
}
OUTPUT:
Good evening.
RESULT:
AIM:
To write a Java program to implement nested if statement.
ALGORITHM:
STEP 1: Start the program
STEP 2: Declare the variable and asign the value for the variable STEP 3: Check the condition
using nested if statement
STEP 4: If, the condition is true, print the result, else compiler exit theprogram.
PROGRAM:
import java.io.*;
public class Test
{
if( x == 30 )
{
if( y == 10 )
{
System.out.print("X = 30 and Y = 10");
}
}
}
}
OUTPUT:
X = 30 and Y = 10
RESULT:
ALGORITHM:
STEP 1: Start the program
STEP 2: Create the class file with extend thread. STEP 3: Initialize the
start() method.
STEP 4: Create the run() function and include thread sleep time. STEP 5: If any error occured
include the catch exception.
STEP 6: Start the alive() method with while loop statement STEP 7: Print the results
frequently.
STEP 8: If any error occured, print the catch() results.
PROGRAM:
import java.io.*;
class Count extends Thread
{
Count()
{
super("my extending thread"); System.out.println("my
thread created" + this); start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("My thread run is over" );
}
}
class ExtendingExample
{
public static void main(String args[])
{
Count cnt = new Count(); try
{
while(cnt.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread's run is over" );
}
}
OUTPUT:
my thread createdThread[my runnable thread,5,main] Main thread
will be alive till the child thread is live Printing the count0
Printing the count1
Main thread will be alive till the child thread is live Printing the
count2
Main thread will be alive till the child thread is live Printing the
count3
Printing the count4
Main thread will be alive till the child thread is live Printing the
count5
Main thread will be alive till the child thread is live Printing the
count6
Printing the count7
Main thread will be alive till the child thread is live Printing the
count8
Main thread will be alive till the child thread is live Printing the
count9
mythread run is over Main
thread run is over
RESULT:
PROGRAM:
import java.io.*;
class Count implements Runnable
{
Thread mythread ;
Count()
{
mythread = new Thread(this, "my runnable thread");
System.out.println("my thread created" + mythread);
mythread.start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("mythread run is over" );
}
}
class RunnableExample
{
public static void main(String args[])
{
Count cnt = new Count(); try
{
while(cnt.mythread.isAlive())
{
System.out.println("Main thread will be alive till the child
thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread run is over" );
}
}
OUTPUT:
my thread createdThread[my runnable thread,5,main] Main thread
will be alive till the child thread is live Printing the count0
Printing the count1
Main thread will be alive till the child thread is live Printing the
count2
Main thread will be alive till the child thread is live Printing the
count3
Printing the count4
Main thread will be alive till the child thread is live Printing the
count5
Main thread will be alive till the child thread is live Printing the
count6
Printing the count7
Main thread will be alive till the child thread is live Printing the
count8
Main thread will be alive till the child thread is live Printing the
count9
mythread run isover
Main thread run is over
RESULT:
AIM:
To write a Java program to implement multiple inheritance.
ALGORITHM:
STEP 1: Start the program
STEP 2: Write the algorithm based on the process. STEP 3: Perform the
operation.
STEP 4: Display the results.
STEP 5: Stop theprogram.
PROGRAM :
import java.io.*;
interface one
{
public void add();
}
interface two
{
public void fun();
}
welcome
CSEstudents
RESULT:
AIM:
To write a Java program to implement Runtime polymorphism.
ALGORITHM:
STEP 1: Start the program
STEP 2: Write the algorithm based on the process.
STEP 3: Perform the operation.
STEP 4: Display the results.
STEP 5: Stop theprogram.
PROGRAM :
import java.io.*;
class A
{
void display()
{
System.out.println("Inside A class");
}
}
class B extends A
{
void display()
{
System.out.println("Inside B class");
}
}
class C extends A
{
void display()
{
System.out.println("Inside C class");
}
}
class test
{
public static void main(String args[])
{
A a1=new A();
B b1=new B(); C
c1=new C(); A ref;
ref=c1; ref.display();
ref=b1; ref.display();
ref=a1; ref.display();
}
}
Output:
Inside C class
Inside B class
Inside A class
RESULT:
AIM:
To write a java program to implement on arithmetic exception
ALGORITHM:
STEP 1: Start the program
STEP 2: Write the algorithm based on the process.
STEP 3: Perform the operation.
STEP 4: Display the results.
STEP 5: Stop theprogram.
PROGRAM :
import java.io.*;
class ArithmeticException_Demo
{
publicstaticvoidmain(String args[])
{
trY
{
inta = 30, b = 0;
intc = a/b;
System.out.println ("Result = "+ c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0
RESULT:
AIM:
To write a java program to implement on string methods.
ALGORITHM:
STEP 1: Start the program
STEP 2: Write the algorithm based on the process.
STEP 3: Perform the Stringoperations.
STEP 4: Display the results.
STEP 5: Stop theprogram.
PROGRAM :
class Main {
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
// compare first and second strings
boolean result1 = first.equals(second);
}
}
Output:
Java
Python
JavaScript
Length: 4
RESULT:
1.Write a Java program to create a new array list, add some elements (string) and print out
the collection.
importjava.util.*;
publicclassExercise1{
publicstaticvoidmain(String[]args){
List<String>list_Strings=newArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
System.out.println(list_Strings);
}
}
Output:
[Red, Green, Orange, White, Black]
2. Write a Java program to retrieve an element (at a specified index) from a given array
list.
import java.util.*;
public class Exercise4 {
public static void main(String[] args) {
// Creae a list and add some colors to the list
List<String>list_Strings = new ArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
// Print the list
System.out.println(list_Strings);
// Retrive the first and third element
String element = list_Strings.get(0);
System.out.println("First element: "+element);
element = list_Strings.get(2);
System.out.println("Third element: "+element);
}
}
Output:
[Red, Green, Orange, White, Black]
First element: Red
Third element: Orange
3. Write a Java program to append the specified element to the end of a linked list.
import java.util.LinkedList;
public class Exercise1 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String>l_list = new LinkedList<String>();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
l_list.add("White");
l_list.add("Pink");
l_list.add("Yellow");
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
publicclassExercise8{
publicstaticvoidmain(String[]args)throwsIOException
{
BufferedReaderR=newBufferedReader(newInputStreamReader(System.in));
System.out.print("Input your name: ");
String name =R.readLine();
System.out.println("Your name is: "+ name);
}
}
Sample Output:
Input your name: Krishna
Your name is: Krishna
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.FileReader;
public class Exercise12 {
Sample Output:
Welcome to w3resource.com.
Append this text.Append this text.Append this text.
Append this text.
Append this text.
Append this text.
Append this text.
null
6. Write a C++ program to overload binary operator using non-member function.
Program
#include<iostream.h>
class Complex
{
private:
float real;
float imag;
public:
Complex(){}
Complex(float r, float i)
{
real = r;
imag = i;
}
void display()
{
cout<<real<<"+i"<<imag;
}
friend Complex operator +(Complex &, Complex &);
};
Complex operator +(Complex &c1, Complex &c2)
{
Complex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return temp;
}
int main()
{
Complex c1(3, 4);
Complex c2(4, 6);
Complex c3 = c1+c2;
c3.display();
return 0;
}
Output:
7+i10
7. Simple Payroll Processing Application in Java
import java.util.Scanner;
class payroll {
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Viva Questions
Java Questions:
1. Why is Java a platform independent language?
Java language was developed in such a way that it does not depend on any hardware or software
due to the fact that the compiler compiles the code and then converts it to platform-independent
byte code which can be run on multiple systems.
• The only condition to run that byte code is for the machine to have a runtime environment
(JRE) installed in it.
Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code
simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause
potential errors. Moreover, security is also compromised if pointers are used because the users
can directly access memory with the help of pointers.
Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the
usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java
makes use of references as these cannot be manipulated, unlike pointers.
4. What do you understand by an instance variable and a local variable?
Instance variables are those variables that are accessible by all the methods in the class. They
are declared outside the methods and inside the class. These variables describe the properties of
an object and remain bound to it at any cost.
All the objects of the class will have their copy of the variables for utilization. If any
modification is done on these variables, then only that instance will be impacted by it, and all
other class instances continue to remain unaffected.
Example:
classAthlete {
public String athleteName;
publicdoubleathleteSpeed;
publicintathleteAge;
}
Local variables are those variables present within a block, function, or constructor and can be
accessed only inside them. The utilization of the variable is restricted to the block scope.
Whenever a local variable is declared inside a method, the other class methods don’t have any
knowledge about the local variable.
Example:
publicvoidathlete() {
String athleteName;
doubleathleteSpeed;
intathleteAge;
}
• It is used for the security of the private properties of an object and hence serves the
purpose of data hiding.
6. Tell us something about JIT compiler.
• JIT stands for Just-In-Time and it is used for improving the performance during run time.
It does the task of compiling parts of byte code having similar functionality at the same
time thereby reducing the amount of compilation time for the code to run.
• The compiler is nothing but a translator of source code to machine-executable code. But
what is special about the JIT compiler? Let us see how it works:
o First, the Java source code (.java) conversion to byte code (.class) occurs with the
help of the javac compiler.
o Then, the .class files are loaded at run time by JVM and with the help of an
interpreter, these are converted to machine understandable code.
o JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes
the method calls in the .class files and compiles them to get more efficient and
native code. It also ensures that the prioritized method calls are optimized.
o Once the above step is done, the JVM executes the optimized code directly instead
of interpreting the code again. This increases the performance and speed of the
execution.
7. Can you tell the difference between equals() method and equality operator (==) in Java?
equals() ==
This method is used for checking the This operator is used for comparing addresses (or
equality of contents between two objects references), i.e checks if both the objects are
as per the specified business logic. pointing to the same memory location.
Note:
• In the cases where the equals method is not overridden in a class, then the class uses the
default implementation of the equals method that is closest to the parent class.
• Object class is considered as the parent class of all the java classes. The implementation of
the equals method in the Object class uses the == operator to compare two objects. This
default implementation can be overridden as per the business logic.
8. How is an infinite loop declared in Java?
Infinite loops are those loops that run infinitely without any breaking conditions. Some examples
of consciously declaring infinite loop is:
In Java, method overloading is made possible by introducing different methods in the same
class consisting of the same name. Still, all the functions differ in the number or type of
parameters. It takes place inside a class and enhances program readability.
The only difference in the return type of the method does not promote method overloading. The
following example will furnish you with a clear picture of it.
classOverloadingHelp {
publicintfindarea (int l, int b) {
int var1;
var1 = l * b;
return var1;
}
publicintfindarea (int l, int b, int h) {
int var2;
var2 = l * b * h;
return var2;
}
}
Both the functions have the same name but differ in the number of arguments. The first method
calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.
Method overriding is the concept in which two methods having the same method signature are
present in two different classes in which an inheritance relationship is present. A particular
method implementation (already present in the base class) is possible for the derived class by
using method overriding.
Let’s give a look at this example:
classHumanBeing {
publicintwalk (int distance, int time) {
int speed = distance / time;
return speed;
}
}
classAthleteextendsHumanBeing {
publicintwalk(int distance, int time) {
int speed = distance / time;
speed = speed * 2;
return speed;
}
}
Both class methods have the name walk and the same parameters, distance, and time. If the
derived class method is called, then the base class method walk gets overridden by that of the
derived class.
11. A single try block and multiple catch blocks can co-exist in a Java Program. Explain.
Yes, multiple catch blocks can exist but specific approaches should come prior to the general
approach because only the first catch block satisfying the catch condition is executed. The given
code illustrates the same:
publicclassMultipleCatch {
publicstaticvoidmain(String args[]) {
try {
int n = 1000, x = 0;
intarr[] = newint[n];
for (inti = 0; i<= n; i++) {
arr[i] = i / x;
}
}
catch (ArrayIndexOutOfBoundsException exception) {
System.out.println("1st block = ArrayIndexOutOfBoundsException");
}
catch (ArithmeticException exception) {
System.out.println("2nd block = ArithmeticException");
}
In Java, the final keyword is used as defining something as constant /final and represents the non-
access modifier.
• final variable:
o When a variable is declared as final in Java, the value can’t be modified once it has
been assigned.
o If any value has not been assigned to that variable, then it can be assigned only by
the constructor of the class.
• final method:
o A method declared as final cannot be overridden by its children's classes.
o A constructor cannot be marked as final because whenever a class is inherited, the
constructors are not inherited. Hence, marking it final doesn't make sense. Java
throws compilation error saying - modifier final not allowed here
• final class:
o No classes can be inherited from the class declared as final. But that final class can
extend other classes for its usage.
13. Do final, finally and finalize keywords have the same function?
All three keywords have their own utility while programming.
Final: If any restriction is required for classes, variables, or methods, the final keyword comes in
handy. Inheritance of a final class and overriding of a final method is restricted by the use of the
final keyword. The variable value becomes fixed after incorporating the final keyword. Example:
finalint a=100;
a = 0; // error
The second statement will throw an error.
Finally: It is the block present in a program where all the codes written inside it get executed
irrespective of handling of exceptions. Example:
try {
int variable = 5;
}
catch (Exception exception) {
System.out.println("Exception occurred");
}
finally {
System.out.println("Execution of finally block");
}
Finalize: Prior to the garbage collection of an object, the finalize method is called so that the
clean-up activity is implemented. Example:
publicstaticvoidmain(String[] args) {
String example = new String("InterviewBit");
example = null;
System.gc(); // Garbage collector called
}
publicvoidfinalize() {
// Finalize called
}
14. When can you use super keyword?
• The super keyword is used to access hidden fields and overridden methods or attributes of
the parent class.
• The following example demonstrates all 3 cases when a super keyword is used.
publicclassParent{
protectedintnum = 1;
Parent(){
System.out.println("Parent class default constructor.");
}
Parent(String x){
System.out.println("Parent class parameterised constructor.");
}
publicvoidfoo(){
System.out.println("Parent class foo!");
}
}
publicclassChildextendsParent{
privateintnum = 2;
child(){
System.out.println("Child class default Constructor");
super(); // to call default parent constructor
super("Call Parent"); // to call parameterised constructor.
}
voidprintNum(){
System.out.println(num);
System.out.println(super.num); //prints the value of num of parent class
}
@Override
publicvoidfoo(){
System.out.println("Parent class foo!");
super.foo(); //Calls foo method of Parent class inside the Overriden foo method of Child class.
}
}
15. Can the static methods be overloaded?
Yes! There can be two or more static methods in a class with the same name but differing input
parameters.
16. Can the static methods be overridden?
• No! Declaration of static methods having the same signature can be done in the subclass
but run time polymorphism can not take place in such cases.
• Overriding or dynamic polymorphism occurs during the runtime, but the static methods are
loaded and looked up at the compile time statically. Hence, these methods cant be
overridden.
17. What is the main objective of garbage collection?
The main objective of this process is to free up the memory space occupied by the unnecessary
and unreachable objects during the Java program execution by deleting those unreachable
objects.
• This ensures that the memory resource is used efficiently, but it provides no guarantee that
there would be sufficient memory for the program execution.
18. What part of memory - Stack or Heap - is cleaned in garbage collection process?
Heap.
19. Apart from the security aspect, what are the reasons behind making strings immutable
in Java?
• Storage area: In string, the String pool serves as the storage area. For StringBuilder and
StringBuffer, heap memory is the storage area.
• Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are
mutable.
• Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in
performing operations. The speed of a StringBuffer is more than a String and less than a
StringBuilder. (For example appending a character is fastest in StringBuilder and very
slow in String because a new memory is required for the new String with appended
character.)
21. Using relevant properties highlight the differences between interfaces and abstract
classes.
• Availability of methods: Only abstract methods are available in interfaces, whereas non-
abstract methods can be present along with abstract methods in abstract classes.
• Variable types: Static and final variables can only be declared in the case of interfaces,
whereas abstract classes can also have non-static and non-final variables.
• Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do
not promote multiple inheritances.
• Data member accessibility: By default, the class data members of interfaces are of the
public- type. Conversely, the class members for an abstract class can be protected or
private also.
Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java.
However, when the object is passed in any method, the address of the value is passed due to the
nature of object handling in Java. When an object is passed, a copy of the reference is created by
Java and that is passed to the method. The objects point to the same memory location. 2 cases
might happen inside the method:
• Case 1: When the object is pointed to another location: In this case, the changes made to
that object do not get reflected the original object before it was passed to the method as the
reference points to another location.
For example:
classInterviewBitTest{
intnum;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
classDriver {
publicstaticvoidmain(String[] args)
{
//create a reference
InterviewBitTestibTestObj = newInterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in the object.
System.out.println(ibTestObj.num);
}
publicstaticvoidupdateObject(InterviewBitTestibObj)
{
// Point the object to new reference
ibObj = newInterviewBitTest();
// Update the value
ibObj.num = 50;
}
}
Output:
20
• Case 2: When object references are not modified: In this case, since we have the copy of
reference the main object pointing to the same memory location, any changes in the
content of the object get reflected in the original object.
For example:
classInterviewBitTest{
intnum;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
classDriver{
publicstaticvoidmain(String[] args)
{
//create a reference
InterviewBitTestibTestObj = newInterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in the object.
System.out.println(ibTestObj.num);
}
publicstaticvoidupdateObject(InterviewBitTestibObj)
{
// no changes are made to point the ibObj to new location
// Update the value of num
ibObj.num = 50;
}
}
Output:
50
31. Which among String or String Buffer should be preferred when there are lot of updates
required to be done in the data?
StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation /
modification of String creates a new String thereby overloading the string pool with unnecessary
objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will
reduce the overhead of the creation of multiple String objects in the string pool.
32. How to not allow serialization of attributes of a class in Java?
• In order to achieve this, the attribute can be declared along with the usage
of transient keyword as shown below:
public class InterviewBitExample {
There wouldn't be any compilation error. But then the program is run, since the JVM cant map
the main method signature, the code throws “NoSuchMethodError” error at the runtime.
C++ Questions:-
1. What are the different data types present in C++?
The 4 data types in C++ are given below:
• Primitive Datatype(basic datatype). Example- char, short, int, float, long, double, bool, etc.
• Derived datatype. Example- array, pointer, etc.
• Enumeration. Example- enum
• User-defined data types. Example- structure, class, etc.
The main difference between C and C++ are provided in the table below:
C C++
C is a procedure-oriented programming C++ is an object-oriented programming
language. language.
Data is hidden by encapsulation to ensure
C does not support data hiding. that data structures and operators are used
as intended.
C is a subset of C++ C++ is a superset of C.
Function and operator overloading are not Function and operator overloading is
supported in C supported in C++
Namespace is used by C++, which avoids
Namespace features are not present in C
name collisions.
Functions can not be defined inside structures. Functions can be defined inside structures.
calloc() and malloc() functions are used for new operator is used for memory
memory allocation and free() function is used for allocation and deletes operator is used for
memory deallocation. memory deallocation.
A class is a user-defined data type that has data members and member functions. Data members
are the data variables and member functions are the functions that are used to perform operations
on these variables.
An object is an instance of a class. Since a class is a user-defined data type so an object can also
be called a variable of that data type.
A class is defined as-
classA{
private:
int data;
public:
voidfun(){
}
};
Class and Object in C++
For example, the following is a class car that can have properties like name, color, etc. and they
can have methods like speed().
In C++ a structure is the same as a class except for a few differences like security. The difference
between struct and class are given below:
Structure Class
Members of the class are private by
Members of the structure are public by default.
default.
When deriving a struct from a class/struct, default access When deriving a class, default
specifiers for base class/struct are public. access specifiers are private.
The following code is for adding two complex number using operator overloading-
classcomplex{
private:
float r, i;
public:
complex(float r, floati){
this->r=r;
this->i=i;
}
complex(){}
voiddisplaydata(){
cout<<”real part = “<<r<<endl;
cout<<”imaginary part = “<<i<<endl;
}
complex operator+(complex c){
returncomplex(r+c.r, i+c.i);
}
};
intmain(){
complex a(2,3);
complex b(3,4);
complex c=a+b;
c.displaydata();
return 0;
}
6. What is polymorphism in C++?
Polymorphism in simple means having many forms. Its behavior is different in different
situations. And this occurs when we have multiple classes that are related to each other by
inheritance.
For example, think of a base class called a car that has a method called car brand(). Derived
classes of cars could be Mercedes, BMW, Audi - And they also have their own implementation
of a cars
The two types of polymorphism in c++ are:
• Compile Time Polymorphism
• Runtime Polymorphism
Polymorphism in C++
7. Explain constructor in C++
return 0;
}
8. Tell me about virtual function
Virtual function is a member function in the base class that you redefine in a derived class. A
virtual function is declared using the virtual keyword. When the function is made virtual, C++
determines which function is to be invoked at the runtime based on the type of the object pointed
by the base class pointer.
10. What do you know about friend class and friend function?
A friend class can access private, protected, and public members of other classes in which it is
declared as friends.
Like friend class, friend function can also access private, protected, and public members. But,
Friend functions are not member functions.
For example -
classA{
private:
intdata_a;
public:
A(int x){
data_a=x;
}
friendintfun(A, B);
}
classB{
private:
intdata_b;
public:
A(int x){
data_b=x;
}
friendintfun(A, B);
}
intfun(A a, B b){
returna.data_a+b.data_b;
}
intmain(){
A a(10);
B b(20);
cout<<fun(a,b)<<endl;
return 0;
}
Here we can access the private data of class A and class B.
11. What are the C++ access specifiers?
In C++ there are the following access specifiers:
Public: All data members and member functions are accessible outside the class.
Protected: All data members and member functions are accessible inside the class and to the
derived class.
Private: All data members and member functions are not accessible outside the class.
12. Define inline function
If a function is inline, the compiler places a copy of the code of that function at each point where
the function is called at compile time. One of the important advantages of using an inline
function is that it eliminates the function calling overhead of a traditional function.
13. What is a reference in C++?
A reference is like a pointer. It is another name of an already existing variable. Once a reference
name is initialized with a variable, that variable can be accessed by the variable name or
reference name both.
For example-
int x=10;
int&ref=x; //reference variable
If we change the value of ref it will be reflected in x. Once a reference variable is initialized it
cannot refer to any other variable. We can declare an array of pointers but an array of references
is not possible.
14. What do you mean by abstraction in C++?
Abstraction is the process of showing the essential details to the user and hiding the details which
we don’t want to show to the user or hiding the details which are irrelevant to a particular user.
15. Is deconstructor overloading possible? If yes then explain and if no then why?
No destructor overloading is not possible. Destructors take no arguments, so there’s only one
way to destroy an object. That’s the reason destructor overloading is not possible.
16. What do you mean by call by value and call by reference?
In call by value method, we pass a copy of the parameter is passed to the functions. For these
copied values a new memory is assigned and changes made to these values do not reflect the
variable in the main function.
In call by reference method, we pass the address of the variable and the address is used to access
the actual argument used in the function call. So changes made in the parameter alter the passing
argument.
17. What is an abstract class and when do you use it?
A class is called an abstract class whose objects can never be created. Such a class exists as a
parent for the derived classes. We can make a class abstract by placing a pure virtual function in
the class.
18. What are destructors in C++?
A constructor is automatically called when an object is first created. Similarly when an object is
destroyed a function called destructor automatically gets called. A destructor has the same name
as the constructor (which is the same as the class name) but is preceded by a tilde.
Example:
classA{
private:
intval;
public:
A(int x){
val=x;
}
A(){
}
~A(){ //destructor
}
}
intmain(){
A a(3);
return 0;
}
19. What are the static members and static member functions?
When a variable in a class is declared static, space for it is allocated for the lifetime of the
program. No matter how many objects of that class have been created, there is only one copy of
the static member. So same static member can be accessed by all the objects of that class.
A static member function can be called even if no objects of the class exist and the static function
are accessed using only the class name and the scope resolution operator ::
20. Explain inheritance
Inheritance is the process of creating new classes, called derived classes, from existing classes.
These existing classes are called base classes. The derived classes inherit all the capabilities of
the base class but can add new features and refinements of their own.
Example-
Inheritance in C++
Class Bus, Class Car, and Class Truck inherit the properties of Class Vehicle.
The most important thing about inheritance is that it permits code reusability.
};
intmain(){
A a1(2,3);
A a2=a1; //default copy constructor is called
return 0;
}
We can define our copy constructor. If we don’t define a copy constructor then the default copy
constructor is called.
22. What is the difference between shallow copy and deep copy?
The difference between shallow copy and a deep copy is given below:
Shallow Copy Deep Copy
Shallow copy stores the references of Deep copy makes a new and separate copy of an
objects to the original memory address. entire object with its unique memory address.
Shallow copy is faster. Deep copy is comparatively slower.
Shallow copy reflects changes made to the Deep copy doesn’t reflect changes made to the
new/copied object in the original object. new/copied object in the original object
23. What is the difference between virtual functions and pure virtual functions?
A virtual function is a member function in the base class that you redefine in a derived class. It is
declared using the virtual keyword.
Example-
classbase{
public:
virtualvoidfun();
}
};
A pure virtual function is a function that has no implementation and is declared by assigning 0. It
has no body.
Example-
classbase{
public:
virtualvoidfun()=0;
};
Here, = sign has got nothing to do with the assignment, and value 0 is not assigned to anything. It
is used to simply tell the compiler that a function will be pure and it will not have anybody.
24. If class D is derived from a base class B. When creating an object of type D in what
order would the constructors of these classes get called?
The derived class has two parts, a base part, and a derived part. When C++ constructs derived
objects, it does so in phases. First, the most-base class(at the top of the inheritance tree) is
constructed. Then each child class is constructed in order until the most-child class is constructed
last.
So the first Constructor of class B will be called and then the constructor of class D will be
called.
During the destruction exactly reverse order is followed. That is destructor starts at the most-
derived class and works its way down to base class.
So the first destructor of class D will be called and then the destructor of class B will be called.
25. Can we call a virtual function from a constructor?
Yes, we can call a virtual function from a constructor. But the behavior is a little different in this
case. When a virtual function is called, the virtual call is resolved at runtime. It is always the
member function of the current class that gets called. That is the virtual machine doesn’t work
within the constructor.
For example-
classbase{
private:
int value;
public:
base(int x){
value=x;
}
virtualvoidfun(){
}
}
classderived{
private:
int a;
public:
derived(int x, int y):base(x){
base *b;
b=this;
b->fun(); //calls derived::fun()
}
voidfun(){
cout<<”fun inside derived class”<<endl;
}
}
26. What are void pointers?
A void pointer is a pointer which is having no datatype associated with it. It can hold addresses
of any type.
For example-
void *ptr;
char *str;
p=str; // no error
str=p; // error because of type mismatch
We can assign a pointer of any type to a void pointer but the reverse is not true unless you
typecast it as
str=(char*) ptr;
27. What is this pointer in C++?
The member functions of every object have a pointer named this, which points to the object
itself. The value of this is set to the address of the object for which it is called. It can be used to
access the data in the object it points to.
Example
classA{
private:
int value;
public:
voidsetvalue(int x){
this->value=x;
}
};
intmain(){
A a;
a.setvalue(5);
return 0;
}
28. How do you allocate and deallocate memory in C++?
The new operator is used for memory allocation and deletes operator is used for memory
deallocation in C++.
For example-
int value=newint; //allocates memory for storing 1 integer
deletevalue; // deallocates memory taken by value