Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 79

1

What is the full form of OOPS?


Object Oriented Programming System.
What is a class?
Class is a blue print which reflects the entities attributes and actions. Technically defining a class is
designing an user defined data type.
What is an object?
An instance of the class is called as object.
List the types of inheritance supported in C++.
Single, Multilevel, Multiple, Hierarchical and Hybrid.
What is the role of protected access specifier?
If a class member is protected then it is accessible in the inherited class. However, outside the both
the private and protected members are not accessible.
What is encapsulation?
The process of binding the data and the functions acting on the data together in an entity (class)
called as encapsulation.
What is abstraction?
Abstraction refers to hiding the internal implementation and exhibiting only the necessary details.
What is inheritance?
Inheritance is the process of acquiring the properties of the exiting class into the new class. The
existing class is called as base/parent class and the inherited class is called as derived/child class.
Explain the purpose of the keyword volatile.
Declaring a variable volatile directs the compiler that the variable can be changed externally. Hence
avoiding compiler optimization on the variable reference.
What is an inline function?
A function prefixed with the keyword inline before the function definition is called as inline function.
The inline functions are faster in execution when compared to normal functions as the compiler treats
inline functions as macros.
What is a storage class?
Storage class specifies the life or scope of symbols such as variable or functions.

Mention the storage classes names in C++.


The following are storage classes supported in C++
auto, static, extern, register and mutable
What is the role of mutable storage class specifier?
1

2
A constant class objects member variable can be altered by declaring it using mutable storage class
specifier. Applicable only for non-static and non-constant member variable of the class.
Distinguish between shallow copy and deep copy.
Shallow copy does memory dumping bit-by-bit from one object to another. Deep copy is copy field
by field from object to another. Deep copy is achieved using copy constructor and or overloading
assignment operator.
What is a pure virtual function?
A virtual function with no function body and assigned with a value zero is called as pure virtual
function.
What is an abstract class in C++?
A class with at least one pure virtual function is called as abstract class. We cannot instantiate an
abstract class.
What is a reference variable in C++?
A reference variable is an alias name for the existing variable. Which mean both the variable name
and reference variable point to the same memory location. Therefore updation on the original variable
can be achieved using reference variable too.
What is role of static keyword on class member variable?
A static variable does exit though the objects for the respective class are not created. Static member
variable share a common memory across all the objects created for the respective class. A static
member variable can be referred using the class name itself.
Explain the static member function.
A static member function can be invoked using the class name as it exits before class objects comes
into existence. It can access only static members of the class.
Name the data type which can be used to store wide characters in C++.
wchar_t
What are/is the operator/operators used to access the class members?
Dot (.) and Arrow ( -> )
Can we initialize a class/structure member variable as soon as the same is defined?
No, Defining a class/structure is just a type definition and will not allocated memory for the same.
What is the data type to store the Boolean value?
bool, is the new primitive data type introduced in C++ language.
What is function overloading?
Defining several functions with the same name with unique list of parameters is called as function
overloading.
What is operator overloading?
Defining a new job for the existing operator w.r.t the class objects is called as operator overloading.
Do we have a String primitive data type in C++?
2

3
No, its a class from STL (Standard template library).
Name the default standard streams in C++.
cin, cout, cerr and clog.
Which access specifier/s can help to achive data hiding in C++?
Private & Protected.
When a class member is defined outside the class, which operator can be used to associate the
function definition to a particular class?
Scope resolution operator (::)
What is a destructor? Can it be overloaded?
A destructor is the member function of the class which is having the same name as the class name and
prefixed with tilde (~) symbol. It gets executed automatically w.r.t the object as soon as the object
loses its scope. It cannot be overloaded and the only form is without the parameters.
What is a constructor?
A constructor is the member function of the class which is having the same as the class name and gets
executed automatically as soon as the object for the respective class is created.
What is a default constructor? Can we provide one for our class?
Every class does have a constructor provided by the compiler if the programmer doesnt provides one
and known as default constructor. A programmer provided constructor with no parameters is called as
default constructor. In such case compiler doesnt provides the constructor.
Which operator can be used in C++ to allocate dynamic memory?
new is the operator can be used for the same.

What is the purpose of delete operator?


delete operator is used to release the dynamic memory which was created using new operator.
Can I use malloc() function of C language to allocate dynamic memory in C++?
Yes, as C is the subset of C++, we can all the functions of C in C++ too.
Can I use delete operator to release the memory which was allocated using malloc() function of
C language?
No, we need to use free() of C language for the same.
What is a friend function?
A function which is not a member of the class but still can access all the member of the class is called
so. To make it happen we need to declare within the required class following the keyword friend.
What is a copy constructor?
A copy constructor is the constructor which take same class object reference as the parameter. It gets
automatically invoked as soon as the object is initialized with another object of the same class at the
time of its creation.

4
Does C++ supports exception handling? If so what are the keywords involved in achieving the
same.
C++ does supports exception handling. try, catch & throw are keyword used for the same.
Explain the pointer this.
This, is the pointer variable of the compiler which always holds the current active objects address.
What is the difference between the keywords struct and class in C++?
By default the members of struct are public and by default the members of the class are private.
Can we implement all the concepts of OOPS using the keyword struct?
Yes.
What is the block scope variable in C++?
A variable whose scope is applicable only within a block is said so. Also a variable in C++ can be
declared anywhere within the block.
What is the role of the file opening mode ios::trunk?
If the file already exists, its content will be truncated before opening the file.

What is the scope resolution operator?


The scope resolution operator is used to

Resolve the scope of global variables.

To associate function definition to a class if the function is defined outside the class.

What is a namespace?
A namespace is the logical division of the code which can be used to resolve the name conflict of the
identifiers by placing them under different name space.
What are command line arguments?
The arguments/parameters which are sent to the main() function while executing from the command
line/console are called so. All the arguments sent are the strings only.
What is a class template?
A template class is a generic class. The keyword template can be used to define a class template.
How can we catch all kind of exceptions in a single catch block?
The catch block with ellipses as follows
catch()
{
}

5
What is keyword auto for?
By default every local variable of the function is automatic (auto). In the below function both the
variables i and j are automatic variables.
void f()
{
int i;

auto int j;
}
NOTE: A global variable cant be an automatic variable.

What is a static variable?


A static local variables retains its value between the function call and the default value is 0. The
following function will print 1 2 3 if called thrice.
void f()
{
static int i;

++i;
printf(%d ,i);
}
If a global variable is static then its visibility is limited to the same source code.
What is the purpose of extern storage specifier.
Used to resolve the scope of global symbol
#include <iostream>

using namespace std;


main()

6
{
extern int i;

cout<<i<<endl;
}
int i=20;
What is the meaning of base address of the array?
The starting address of the array is called as the base address of the array.
When should we use the register storage specifier?
If a variable is used most frequently then it should be declared using register storage specifier, then
possibly the compiler gives CPU register for its storage to speed up the look up of the variable.
Can a program be compiled without main() function?
Yes, it can be but cannot be executed, as the execution requires main() function definition.
Where an automatic variable is stored?
Every local variable by default being an auto variable is stored in stack memory
What is a container class?
A class containing at least one member variable of another class type in it is called so.
What is a token?
A C++ program consists of various tokens and a token is either a keyword, an identifier, a constant, a
string literal, or a symbol.
What is a preprocessor?
Preprocessor is a directive to the compiler to perform certain things before the actual compilation
process begins.
What are command line arguments?
The arguments which we pass to the main() function while executing the program are called as
command line arguments. The parameters are always strings held in the second argument (below in
args) of the function which is array of character pointers. First argument represents the count of
arguments (below in count) and updated automatically by operating system.
main( int count, char *args[]) {
}
What are the different ways of passing parameters to the functions? Which to use when?
Call by value: We send only values to the function as parameters. We choose this if we do not
want the actual parameters to be modified with formal parameters but just used.

Call by address: We send address of the actual parameters instead of values. We choose this
if we do want the actual parameters to be modified with formal parameters.
6

Call by reference: The actual parameters are received with the C++ new reference variables
as formal parameters. We choose this if we do want the actual parameters to be modified with
formal parameters.

What is reminder for 5.0 % 2?


Error, It is invalid that either of the operands for the modulus operator (%) is a real number.
Which compiler switch to be used for compiling the programs using math library with g++
compiler?
Opiton lm to be used as > g++ lm <file.cpp>
Can we resize the allocated memory which was allocated using new operator?
No, there is no such provision available.
Who designed C++ programming language?
Bjarne Stroustrup.
Which operator can be used to determine the size of a data type/class or variable/object?
sizeof
How can we refer to the global variable if the local and the global variable names are same?
We can apply scope resolution operator (::) to the for the scope of global variable.
What are valid operations on pointers?
The only two permitted operations on pointers are

Comparision ii) Addition/Substraction (excluding void pointers)

What is recursion?
Function calling itself is called as recursion.
What is the first string in the argument vector w.r.t command line arguments?
Program name.
What is the maximum length of an identifier?
Ideally it is 32 characters and also implementation dependent.
What is the default function call method?
By default the functions are called by value.
What are available mode of inheritance to inherit one class from another?
Public, private & protected
What is the difference between delete and delete[]?
Delete[] is used to release the array allocated memory which was allocated using new[] and delete is
used to release one chunk of memory which was allocated using new.
Does an abstract class in C++ need to hold all pure virtual functions?
Not necessarily, a class having at least one pure virtual function is abstract class too.

8
Is it legal to assign a base class object to a derived class pointer?
No, it will be error as the compiler fails to do conversion.
What happens if an exception is thrown outside a try block?
The program shall quit abruptly.
Are the exceptions and error same?
No, exceptions can be handled whereas program cannot resolve errors.
What is function overriding?
Defining the functions within the base and derived class with the same signature and name where the
base classs function is virtual.
Which function is used to move the stream pointer for the purpose of reading data from stream?
seekg()
Which function is used to move the stream pointer for the purpose of writing data from stream?
seekp()
Are class functions taken into consideration as part of the object size?
No, only the class member variables determines the size of the respective class object.
Can we create and empty class? If so what would be the size of such object.
We can create an empty class and the object size will be 1.
What is std?
Default namespace defined by C++.
What is the full form of STL?
Standard template library
What is cout?
cout is the object of ostream class. The stream cout is by default connected to console output device.
What is cin?
cin is the object of istream class. The stream cin is by default connected to console input device.
What is the use of the keyword using?
It is used to specify the namespace being used in.
If a pointer declared for a class, which operator can be used to access its class members?
Arrow (->) operator can be used for the same
What is difference between including the header file with-in angular braces < > and double
quotes
If a header file is included with in < > then the compiler searches for the particular header file only
with in the built in include path. If a header file is included with in , then the compiler searches for
the particular header file first in the current working directory, if not found then in the built in include
path

9
S++ or S=S+1, which can be recommended to increment the value by 1 and why?
S++, as it is single machine instruction (INC) internally.

What is the difference between actual and formal parameters?


The parameters sent to the function at calling end are called as actual parameters while at the
receiving of the function definition called as formal parameters.
What is the difference between variable declaration and variable definition?
Declaration associates type to the variable whereas definition gives the value to the variable.
Which key word is used to perform unconditional branching?
goto.
Is 068 a valid octal number?
No, it contains invalid octal digits.
What is the purpose of #undef preprocessor?
It will be used to undefine an existing macro definition.
Can we nest multi line comments in a C++ code?
No, we cannot.
What is a virtual destructor?
A virtual destructor ensures that the objects resources are released in the reverse order of the object
being constructed w.r.t inherited object.
What is the order of objects destroyed in the memory?
The objects are destroyed in the reverse order of their creation.
What is a friend class?
A class members can gain accessibility over other class member by placing the class declaration
prefixed with the keyword friend in the destination class.
What is polymorphism?
Polymorphism is the idea that a base class can be inherited by several classes. A
base class pointer can point to its child class and a base class array can store
different child class objects.
How do you find out if a linked-list has an end? (i.e. the list is not a
cycle)
You can find out by using 2 pointers. One of them goes 2 nodes each time. The
second one goes at 1 nodes each time. If there is a cycle, the one that goes 2
nodes each time will eventually meet the one that goes slower. If that is the
case, then you will know the linked-list is a cycle.

10

How do you write a function that can reverse a linked-list? (Cisco


System)
void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur->next = head;
for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;

Explain virtual inheritance. Draw the diagram explaining the


initialization of the base class when virtual inheritance is used.
Note: Typical mistake for applicant is to draw an inheritance diagram, where a
single base class is inherited with virtual methods. Explain to the candidate that
this is not virtual inheritance. Ask them for the classic definition of virtual
inheritance. Such question might be too complex for a beginning or even
intermediate developer, but any applicant with advanced C++ experience should
be somewhat familiar with the concept, even though hell probably say hed avoid
10

11
using it in a real project. Moreover, even the experienced developers, who know
about virtual inheritance, cannot coherently explain the initialization process. If
you find a candidate that knows both the concept and the initialization process
well, hes hired.
What are the differences between references and pointers?
Both references and pointers can be used to change local variables of one function inside
another function. Both of them can also be used to save copying of big objects when passed
as arguments to functions or returned from functions, to get efficiency gain.
Despite above similarities, there are following differences between references and pointers.
References are less powerful than pointers
1) Once a reference is created, it cannot be later made to reference another object; it cannot
be reseated. This is often done with pointers.
2) References cannot be NULL. Pointers are often made NULL to indicate that they are not
pointing to any valid thing.
3) A reference must be initialized when declared. There is no such restriction with pointers
Due to the above limitations, references in C++ cannot be used for implementing data
structures like Linked List, Tree, etc. In Java, references dont have above restrictions, and
can be used to implement all data structures. References being more powerful in Java, is the
main reason Java doesnt need pointers.
References are safer and easier to use:
1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to
exist. It is still possible to have references that dont refer to a valid location (See questions 5
and 6 in the below exercise )
2) Easier to use: References dont need dereferencing operator to access the value. They
can be used like normal variables. & operator is needed only at the time of declaration. Also,
members of an object reference can be accessed with dot operator (.), unlike pointers where
arrow operator (->) is needed to access members.
What are virtual functions Write an example?
Virtual functions are used with inheritance, they are called according to the type of object
pointed or referred, not according to the type of pointer or reference. In other words, virtual
functions are resolved late, at runtime. Virtual keyword is used to make a function virtual.
Following things are necessary to write a C++ program with runtime polymorphism (use of
virtual functions)
1) A base class and a derived class.
2) A function with same name in base class and derived class.
3) A pointer or reference of base class type pointing or referring to an object of derived class.
For example, in the following program bp is a pointer of type Base, but a call to bp->show()
calls show() function of Derived class, because bp points to an object of Derived class.
11

12
#include<iostream>
using namespace std;
class Base {
public:
virtual void show() { cout<<" In Base \n"; }
};
class Derived: public Base {
public:
void show() { cout<<"In Derived \n"; }
};
int main(void) {
Base *bp = new Derived;
bp->show(); // RUN-TIME POLYMORPHISM
return 0;
}
Run on IDE
Output:
In Derived
What is this pointer?
The this pointer is passed as a hidden argument to all nonstatic member function calls and
is available as a local variable within the body of all nonstatic functions. this pointer is a
constant pointer that holds the memory address of the current object. this pointer is not
available in static member functions as static member functions can be called without any
object (with class name).
Can we do delete this?
See http://www.geeksforgeeks.org/delete-this-in-c/
What are VTABLE and VPTR?
vtable is a table of function pointers. It is maintained per class.
vptr is a pointer to vtable. It is maintained per object (See this for an example).
Compiler adds additional code at two places to maintain and use vtable and vptr.
1) Code in every constructor. This code sets vptr of the object being created. This code sets
vptr to point to vtable of the class.
2) Code with polymorphic function call (e.g. bp->show() in above code). Wherever a
polymorphic call is made, compiler inserts code to first look for vptr using base class pointer
or reference (In the above example, since pointed or referred object is of derived type, vptr of
derived class is accessed). Once vptr is fetched, vtable of derived class can be accessed.
Using vtable, address of derived derived class function show() is accessed and called.

12

13

One advantage with fresher interviews is that there are only limited number of concepts and
questions and the same has been repeatedly being asked over years. If you want to pursue
your career in system level programming like driver development, needless to say, you should
show your mastery in C/C++ interviews. Here we have identified and collected a set of
frequently asked C++ interview questions and answers for experienced and freshers as well.
It's a continuously updated list, go through them, understand the concepts and excel in the
interviews.
1. What is difference between C and C++ ?
[This is a usual C or C++ interview question, mostly the first one you will face if you are
fresher or appearing for campus interview. When answering this question please make sure
you don't give the text book type explanations, instead give examples from real software
scenario. Answer for this interview question can include below points, though its not complete
list. This question itself can be a 1day interview !!!]
1. C++ is Multi-Paradigm ( not pure OOP, supports both procedural and object
oriented) while C follows procedural style programming.
2. In C data security is less, but in C++ you can use modifiers for your class members to
make it inaccessible from outside.
3. C follows top-down approach ( solution is created in step by step manner, like each
step is processed into details as we proceed ) but C++ follows a bottom-up approach (
where base elements are established first and are linked to make complex solutions ).
4. C++ supports function overloading while C does not support it.
5. C++ allows use of functions in structures, but C does not permit that.
6. C++ supports reference variables ( two variables can point to same memory
location ). C does not support this.
7. C does not have a built in exception handling framework, though we can emulate it
with other mechanism. C++ directly supports exception handling, which makes life
of developer easy.
2. What is a class?

13

14
[Probably this would be the first question for a Java/c++ technical interview for freshers and
sometimes for experienced as well. Try to give examples when you answer this question.]
Class defines a datatype, it's type definition of category of thing(s). But a class actually does
not define the data, it just specifies the structure of data. To use them you need to create
objects out of the class. Class can be considered as a blueprint of a building, you can not
stay inside blueprint of building, you need to construct building(s) out of that plan. You can
create any number of buildings from the blueprint, similarly you can create any number of
objects from a class.
1. class Vehicle
2. {
3.

public:

4.

int numberOfTyres;

5.

double engineCapacity;

6.

void drive(){

7.
8.

// code to drive the car


}

9. };
3. What is an Object/Instance?
Object is the instance of a class, which is concrete. From the above example, we can create
instance of class Vehicle as given below
1. Vehicle vehicleObject;
We can have different objects of the class Vehicle, for example we can have Vehicle objects
with 2 tyres, 4tyres etc. Similarly different engine capacities as well.
4. What do you mean by C++ access specifiers ?
[Questions regarding access specifiers are common not just in c++ interview but for other
object oriented language interviews as well.]
14

15
Access specifiers are used to define how the members (functions and variables) can be
accessed outside the class. There are three access specifiers defined which are public,
private, and protected
private:

Members declared as private are accessible only with in the same class and they cannot be
accessed outside the class they are declared.
public:

Members declared as public are accessible from any where.


protected:

Members declared as protected can not be accessed from outside the class except a child
class. This access specifier has significance in the context of inheritance.
5. What are the basics concepts of OOP?
[ A must OOP / c++ interview question for freshers (some times asked in interviews for 1-2
years experienced also), which everybody answers as well. But the point is, it's not about the
answer, but how you apply these OOPs concepts in real life. You should be able to give real
life examples for each of these concepts, so prepare yourself with few examples before
appearing for the interview. It has seen that even the experienced people get confused when
it comes to the difference between basic OOP concepts, especially abstraction and
encapsulation.]
Classes and Objects

Refer Questions 2 and 3 for the concepts about classes and objects
Encapsulation

Encapsulation is the mechanism by which data and associated operations/methods are


bound together and thus hide the data from outside world. It's also called data hiding. In c++,
encapsulation achieved using the access specifiers (private, public and protected). Data
members will be declared as private (thus protecting from direct access from outside) and
public methods will be provided to access these data. Consider the below class
1. class Person
2. {
3.

private:

15

16

4.

int age;

5.

public:

6.

int getAge(){

7.

return age;

8.

9.

int setAge(int value){

10.

if(value > 0){

11.

age = value;

12.

13.

14. };
In the class Person, access to the data field age is protected by declaring it asprivate and
providing public access methods. What would have happened if there was no access
methods and the field age was public? Anybody who has a Personobject can set an invalid
value (negative or very large value) for the age field. So by encapsulation we can preventing
direct access from outside, and thus have complete control, protection and integrity of the
data.
Data abstraction

Data abstraction refers to hiding the internal implementations and show only the necessary
details to the outside world. In C++ data abstraction is implemented using interfaces and
abstract classes.
1. class Stack
2. {
3.

public:

4.

virtual void push(int)=0;

5.

virtual int pop()=0;

16

17

6. };
7.
8. class MyStack : public Stack
9. {
10.

private:

11.

int arrayToHoldData[]; //Holds the data from stack

12.
13.

public:

14.

void push(int) {

15.

// implement push operation using array

16.

17.

int pop(){

18.

// implement pop operation using array

19.

20. };
In the above example, the outside world only need to know about the Stack class and
its push, pop operations. Internally stack can be implemented using arrays or linked lists or
queues or anything that you can think of. This means, as long as the push and pop method
performs the operations work as expected, you have the freedom to change the internal
implementation with out affecting other applications that use your Stack class.

Inheritance
Inheritance allows one class to inherit properties of another class. In other words, inheritance
allows one class to be defined in terms of another class.
1. class SymmetricShape
2. {

17

18

3.

public:

4.

int getSize()

5.

6.

return size;

7.

8.

void setSize(int w)

9.

10.
11.

size = w;
}

12.

protected:

13.

int size;

14. };
15.
16. // Derived class
17. class Square: public SymmetricShape
18. {
19.

public:

20.

int getArea()

21.

22.
23.

return (size * size);


}

24. };
In the above example, class Square inherits the properties and methods of
classSymmetricShape. Inheritance is the one of the very important concepts in C++/OOP. It

18

19
helps to modularise the code, improve reusability and reduces tight coupling between
components of the system.
6. What is the use of volatile keyword in c++? Give an example.
Most of the times compilers will do optimization to the code to speed up the program. For
example in the below code,
1. int a = 10;
2. while( a == 10){
3.

// Do something

4. }
compiler may think that value of 'a' is not getting changed from the program and replace it
with 'while(true)', which will result in an infinite loop. In actual scenario the value of 'a' may be
getting updated from outside of the program.
Volatile keyword is used to tell compiler that the variable declared using volatile may be used
from outside the current scope so that compiler wont apply any optimization. This matters
only in case of multi-threaded applications.
In the above example if variable 'a' was declared using volatile, compiler will not optimize it.
In shot, value of the volatile variables will be read from the memory location directly.
In how many ways we can initialize an int variable in C++?
In c++, variables can be initialized in two ways, the traditional C++ initialization using "="
operator and second using the constructor notation.

Traditional C++ initilization


1. int i = 10;
variable i will get initialized to 10.

Using C++ constructor notation


1. int i(10);

19

20
8. What is implicit conversion/coercion in c++?
Implicit conversions are performed when a type (say T) is used in a context where a
compatible type (Say F) is expected so that the type T will be promoted to type F.
short a = 2000 + 20;
In the above example, variable a will get automatically promoted from short to int. This is
called implicit conversion/coercion in c++.
9. What are C++ inline functions?
C++ inline functions are special functions, for which the compiler replaces the function call
with body/definition of function. Inline functions makes the program execute faster than the
normal functions, since the overhead involved in saving current state to stack on the function
call is avoided. By giving developer the control of making a function as inline, he can further
optimize the code based on application logic. But actually, it's the compiler that decides
whether to make a function inline or not regardless of it's declaration. Compiler may choose
to make a non inline function inline and vice versa. Declaring a function as inline is in effect a
request to the compiler to make it inline, which compiler may ignore. So, please note this
point for the interview that, it is upto the compiler to make a function inline or not.
1. inline int min(int a, int b)
2. {
3.

return (a < b)? a : b;

4. }
5.
6. int main( )
7. {
8.

cout << "min (20,10): " << min(20,10) << endl;

9.

cout << "min (0,200): " << min(0,200) << endl;

10.

cout << "min (100,1010): " << min(100,1010) << endl;

11.

return 0;

20

21

12. }
If the complier decides to make the function min as inline, then the above code will internally
look as if it was written like
1. int main( )
2. {
3.

cout << "min (20,10): " << ((20 < 10)? 20 : 10) << endl;

4.

cout << "min (0,200): " << ((0 < 200)? 0 : 200) << endl;

5.

cout << "min (100,1010): " << ((100 < 1010)? 100 : 1010) << endl;

6.

return 0;

7. }
10. What do you mean by translation unit in c++?
We organize our C++ programs into different source files (.cpp, .cxx etc). When you consider
a source file, at the preprocessing stage, some extra content may get added to the source
code ( for example, the contents of header files included) and some content may get
removed ( for example, the part of the code in the #ifdef of #ifndef block which resolve to
false/0 based on the symbols defined). This effective content is called a translation unit. In
other words, a translation unit consists of

Contents of source file

Plus contents of files included directly or indirectly

Minus source code lines ignored by any conditional pre processing directives ( the
lines ignored by #ifdef,#ifndef etc)
11. What do you mean by internal linking and external linking in c++?
[This interview question is related to questions on "translation unit" and "storage classes"]
A symbol is said to be linked internally when it can be accessed only from with-in the scope
of a single translation unit. By external linking a symbol can be accessed from other
translation units as well. This linkage can be controlled by using static and extern keywords.
21

22
12. What do you mean by storage classes?
Storage class are used to specify the visibility/scope and life time of symbols(functions and
variables). That means, storage classes specify where all a variable or function can be
accessed and till what time those variables will be available during the execution of program.
How many storage classes are available in C++?
Storage class are used to specify the visibility/scope and life time of symbols(functions and
variables). That means, storage classes specify where all a variable or function can be
accessed and till what time those variables will be available during the execution of program.
Following storage classes are available in C++
auto

It's the default storage class for local variables. They can be accessed only from with in the
declaration scope. auto variables are allocated at the beginning of enclosing block and
deallocated at the end of enclosing block.
1. void changeValue(void)
2. {
3.

auto int i = 1 ;

4.

i++;

5.

printf ( "%d ", i ) ;

6.
7. }
8. int main()
9. {
10.

changeValue();

11.

changeValue();

12.

changeValue();

13.

changeValue();

22

23

14.

return 0;

15. }
16.
17. Output:18. 2 2 2 2
In the above example, every time the method changeValue is invoked, memory is allocated
for i and de allocated at the end of the method. So it's output will be same.
register

It's similar to auto variables. Difference is that register variables might be stored on the
processor register instead of RAM, that means the maximum size of register variable should
be the size of CPU register ( like 16bit, 32bit or 64bit). This is normally used for frequently
accessed variables like counters, to improve performance. But note that, declaring a variable
as register does not mean that they will be stored in the register. It depends on the hardware
and implementation.
1. int main()
2. {
3.

register int i;

4.

int array[10] = {0,1,2,3,4,5,6,7,8,9};

5.
6.

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

7.

8.

printf("%d ", array[i]);

9.

10.

return 0;

11. }
12.
23

24

13. Output:14. 0 1 2 3 4 5 6 7 8 9
The variable i might be stored on the CPU register and due to which the access of i in the
loop will be faster.
static

A static variable will be kept in existence till the end of the program unlike creating and
destroying each time they move into and out of the scope. This helps to maintain their value
even if control goes out of the scope. When static is used with global variables, they will have
internal linkage, that means it cannot be accessed by other source files. When static is used
in case of a class member, it will be shared by all the objects of a class instead of creating
separate copies for each object.
1. void changeValue(void)
2. {
3.

static int i = 1 ;

4.

i++;

5.

printf ( "%d ", i ) ;

6.
7. }
8.
9. int main()
10. {
11.

changeValue();

12.

changeValue();

13.

changeValue();

14.

changeValue();

15.

return 0;
24

25

16. }
17.
18. Output:19. 2 3 4 5
Since static variable will be kept in existence till the end of program, variable i will retain it's
value across the method invocations.
extern

extern is used to tell compiler that the symbol is defined in another translation unit (or in a
way, source files) and not in the current one. Which means the symbol is linked externally.
extern symbols have static storage duration, that is accessible through out the life of
program. Since no storage is allocated for extern variable as part of declaration, they cannot
be initialized while declaring.
1. int x = 10;
2. int main( )
3. {
4.

extern int y ;

5.

printf("x: %d ", x );

6.

printf("y: %d", y);

7.

return 0;

8. }
9. int y = 70 ;
10.
11. Output:12. x: 10 y: 70

25

26
extern variable is like global variable, it's scope is through out the program. It can be defined
anywhere in the c++ program.
mutable

mutable storage class can be used only on non static non const data a member of a class.
Mutable data member of a class can be modified even is it's part of an object which is
declared as const.
1. class Test
2. {
3.

public:

4.

Test(): x(1), y(1) {};

5.

mutable int x;

6.

int y;

7. };
8.
9. int main()
10. {
11.

const Test object;

12.

object.x = 123;

13.

//object.y = 123;

14.

/*

15.

* The above line if uncommented, will create compilation error.

16.

*/

17.

cout<< "X:"<< object.x << ", Y:" << object.y;

18.

return 0;

19. }

26

27

20.
21. Output:22. X:123, Y:1
In the above example, we are able to change the value of member variable x though it's part
of an object which is declared as const. This is because the variable x is declared as
mutable. But if you try to modify the value of member variable y, compiler will throw error.
You can find the summary of c++ storage class specifiers below
C++ Storage
Specifier

Storage
Location

Scope Of
Variable

Life Time

auto

Memory
(RAM)

Local

With in function

static

Memory
(RAM)

Local

Life time is from when the flow reaches the


first declaration to the termination of
program.

register

CPU register

Local

With in function

extern

Memory
(RAM)

Global

Till the end of main program

14. What is 'Copy Constructor' and when it is called?


This is a frequent c++ interview question. Copy constructor is a special constructor of a class
which is used to create copy of an object. Compiler will give a default copy constructor if you
don't define one. This implicit constructor will copy all the members of source object to target
object.
Implicit copy constructors are not recommended, because if the source object contains
pointers they will be copied to target object, and it may cause heap corruption when both the
objects with pointers referring to the same location does an update to the memory location. In
this case its better to define a custom copy constructor and do a deep copy of the object.
1.

class SampleClass{
27

28

2.

public:

3.

int* ptr;

4.

SampleClass();

5.

// Copy constructor declaration

6.

SampleClass(SampleClass &obj);

7.

};

8.
9.

SampleClass::SampleClass(){

10.

ptr = new int();

11.

*ptr = 5;

12.

13.
14.

// Copy constructor definition

15.

SampleClass::SampleClass(SampleClass &obj){

16.

//create a new object for the pointer

17.

ptr = new int();

18.

// Now manually assign the value

19.

*ptr = *(obj.ptr);

20.

cout<<"Copy constructor...\n";

21.

15. What is realloc() and free()? What is difference between them?

void* realloc (void* ptr, size_t size)


This function is used to change the size of memory object pointed by address ptr to the size
given by size. If ptr is a null pointer, then realloc will behave like malloc(). If the ptr is an
invalid pointer, then defined behaviour may occur depending the implementation. Undefined
28

29
behaviour may occur if the ptr has previously been deallocated by free(), or dealloc() or ptr do
not match a pointer returned by an malloc(), calloc() or realloc().

void free (void* ptr)


This function is used to deallocate a block of memory that was allocated using malloc(),
calloc() or realloc(). If ptr is null, this function does not doe anything.
16. What is difference between shallow copy and deep copy? Which is default?
[This question can be expected in any interviews, not just c++ interviews. This is a usual
question in most of the java interviews.]
When you do a shallow copy, all the fields of the source object is copied to target object as it
is. That means, if there is a dynamically created field in the source object, shallow copy will
copy the same pointer to target object. So you will have two objects with fields that are
pointing to same memory location which is not what you usually want.
In case of deep copy, instead of copying the pointer, the object itself is copied to target. In this
case if you modify the target object, it will not affect the source. By default copy constructors
and assignment operators do shallow copy. To make it as deep copy, you need to create a
custom copy constructor and override assignment operator.
17. What do you mean by persistent and non persistent objects?
[This question may be asked in many ways during c++ interviews, like how to send an object
to a remote computer or how to save the your program state across application restarts. All
these are related to serialization.]
Persistent objects are the ones which we can be serialized and written to disk, or any other
stream. So before stopping your application, you can serialize the object and on restart you
can deserialize it. [ Drawing applications usually use serializations.]
Objects that can not be serialized are called non persistent objects. [ Usually database
objects are not serialized because connection and session will not be existing when you
restart the application. ]
18. Is it possible to get the source code back from binary file?
Technically it is possible to generate the source code from binary. It is called reverse
engineering. There are lot of reverse engineering tools available. But, in actual case most of
them will not re generate the exact source code back because many information will be lost
due to compiler optimization and other interpretations.
What are virtual functions and what is its use?
29

30
[This is a sure question in not just C++ interviews, but any other OOP language interviews.
Virtual functions are the important concepts in any object oriented language, not just from
interview perspective. Virtual functions are used to implement run time polymorphism in c++.]
Virtual functions are member functions of class which is declared using keyword 'virtual'.
When a base class type reference is initialized using object of sub class type and an
overridden method which is declared as virtual is invoked using the base reference, the
method in child class object will get invoked.
1. class Base
2. {
3.

int a;

4.

public:

5.

Base()

6.

7.

a = 1;

8.

9.

virtual void method()

10.

11.
12.

cout << a;
}

13. };
14.
15. class Child: public Base
16. {
17.

int b;

18.

public:

19.

Child()

30

31

20.

21.

b = 2;

22.

23.

virtual void method()

24.

25.
26.

cout << b;
}

27. };
28.
29. int main()
30. {
31.

Base *pBase;

32.

Child oChild;

33.

pBase = &oChild;

34.

pBase->method();

35.

return 0;

36. }
In the above example even though the method in invoked on Base class reference, method of
the child will get invoked since its declared as virtual.
20. What do you mean by pure virtual functions in C++? Give an example?
Pure virtual function is a function which doesn't have an implementation and the same needs
to be implemented by the the next immediate non-abstract class. (A class will become an
abstract class if there is at-least a single pure virtual function and thus pure virtual functions
are used to create interfaces in c++).
How to create a pure virtual function?
31

32
A function is made as pure virtual function by the using a specific signature, " = 0" appended
to the function declaration as given below,
1. class SymmetricShape {
2.

public:

3.

// draw() is a pure virtual function.

4.

virtual void draw() = 0;

5. };
21. Why pure virtual functions are used if they don't have implementation / When does
a pure virtual function become useful?
Pure virtual functions are used when it doesn't make sense to provide definition of a virtual
function in the base class or a proper definition does not exists in the context of base class.
Consider the above example, class SymmetricShape is used as base class for shapes with
symmetric structure(Circle, square, equilateral triangle etc). In this case, there exists no
proper definition for function draw() in the base class SymmetricShape instead the child
classes of SymmetricShape (Cirlce, Square etc) can implement this method and draw
proper shape.
22. What is virtual destructors? Why they are used?
[This c++ interview question is in a way related to polymorphism.]
Virtual destructors are used for the same purpose as virtual functions. When you remove an
object of subclass, which is referenced by a parent class pointer, only destructor of base
class will get executed. But if the destructor is defined using virtual keyword, both the
destructors [ of parent and sub class ] will get invoked.
23. What you mean by early binding and late binding? How it is related to dynamic
binding?
[This c++ interview question is related to question about virtual functions ]
Binding is the process of linking actual address of functions or identifiers to their reference.
This happens mainly two times.

During compilation : This is called early binding


32

33
For all the direct function references compiler will replace the reference with actual address of
the method.
At runtime : This is called late binding.

In case of virtual function calls using a Base reference, as in shown in the example of
question no: 2, compiler does not know which method will get called at run time. In this case
compiler will replace the reference with code to get the address of function at runtime.

Dynamic binding is another name for late binding.


24. What is meant by reference variable in C++?
In C++, reference variable allows you create an alias (second name) for an already existing
variable. A reference variable can be used to access (read/write) the original data. That
means, both the variable and reference variable are attached to same memory location. In
effect, if you change the value of a variable using reference variable, both will get changed
(because both are attached to same memory location).
How to create a reference variable in C++
Appending an ampersand (&) to the end of datatype makes a variable eligible to use as
reference variable.

1. int a = 20;
2. int& b = a;
3.
The first statement initializes a an integer variable a. Second statement creates an integer
reference initialized to variable a
Take a look at the below example to see how reference variables work.

1. int main ()
2. {
3.

int a;

4.

int& b = a;

5.
33

34

6.

a = 10;

7.

cout << "Value of a : " << a << endl;

8.

cout << "Value of a reference (b) : " << b << endl;

9.
10.

b = 20;

11.

cout << "Value of a : " << a << endl;

12.

cout << "Value of a reference (b) : " << b << endl;

13.
14.

return 0;

15. }
Above code creates following output.
Value of a : 10
Value of a reference (b) : 10
Value of a : 20
Value of a reference (b) : 20
25. What are the difference between reference variables and pointers in C++?
[This question is usually asked in a twisted way during c++ interviews. Sometimes the
interviewer might use examples and ask you to find the error.]
Pointers

Reference Variables

Pointers can be assigned to NULL

References cannot be assigned NULL. It should


always be associated with actual memory, not
NULL.

Pointers can be (re)pointed to any


object, at any time, any number of
times during the execution.

Reference variables should be initialized with an


object when they are created and they cannot be
reinitialized to refer to another object

34

35

Reference variables has location on stack, but


Pointer has own memory address and
shares the same memory location with the object it
location on stack
refer to.

JAVA

1. What is Java technology ?


Java is a programming language, application development and deployment environment.
Java programming language is similar to C++ syntax. Java development environment
provides tools - Compiler, Interpreter, Packaging Tool etc.
2. What are the objectives of Java Technology ?
Simple: The language syntax is based on the familiar programming language C++. Though
the syntax of C++ was adopted, some features which were troublesome were avoided
making the Java programming simple.
Object oriented: The object oriented features of Java are comparable to C++. One major
difference between Java and C++ lies in multiple inheritance. Object oriented design is a
technique that focuses design on data (i.e.objects) and on the interfaces to it.
Architectural Neutral: The Java compiler generates an intermediate byte code which does
not depend on any architecture of a computer i.e., whether it is an IBM PC, a Macintosh, or a
Solaris system. So the Java programs can be used on any machine irrespective of its
architecture and hence the Java program is Architectural Neutral.
Portable type: The size of data types are always same irrespective of the system
architecture. That is an int in Java is always 32 bit unlike in C/C++ where the size may be 16bit or 32-bit depending on the compiler and machine. Hence when ported on different
machines, there does not occur any change in the values the data types can hold. And also
Java has libraries that enables to port its application on any systems like UNIX, Windows and
the Macintosh systems.

35

36
Distributed: Javas networking capabilities are both strong and easy to use. Java
applications are capable of accessing objects across the net, via URLs as easy as a local file
system.
Secure: Since Java is mostly used in network environment, a lot of emphasis has been
placed on security to enable construction of virus free and tamper free systems.
Smaller code: The Java compiler generates an intermediate byte code to make it
architecture neutral. Though Java interpreter is needed to run the byte code, it is one copy
per machine and not per program.
Multithreaded: Multithreading is the ability for one program to do more than one task at
once. Compared to other languages it is easy to implement multithreading in Java.
Interpreted: The Java Interpreter can execute Java byte code, directly on any machine to
which the interpreter has been ported. Interpreted code is slower than compiled code.
High performance: The byte codes can be translated at run time into machine code for the
particular CPU on which the application is running.
Applet programming: is one of the important features which has attracted the users of the
Internet. Applets are Java programs that are typically loaded from the Internet by a browser.
3. What are the Major Features of Java Technology Architecture ?

Java Run Time Environment

Java Virtual Machine

Just in Time Compiler

Java Tools

Garbage Collector

Don't Miss - Tricky & Advanced Java Interview Questions


Core Java Interview Questions on JVM, JRE and JDK

36

37
4. What is Java Virtual Machine (JVM) ?
A self-contained operating environment that behaves as if it is a separate computer. For
example, Java applets run in a Java virtual machine (VM) that has no access to the host
operating system.
Java Compilers compile JAVA source code into byte code. Java Virtual Machine(JVM)
interpreters Java byte code and send necessary commands to underlying hardware or Just in
time compiled to native machine code and execute it directly on the underlying hardware .
Most JVM's use Just in time compilation which provides execution speeds near to C or C++
application. Most widely used JVM is Oracle Corporations HotSpot, which is written in the
C++ programming language.
5. What are the advantages of JVM?
This design has two advantages:

System Independence: A Java application will run the same in any Java VM,
regardless of the hardware and software underlying the system.

Security: Because the VM has no contact with the operating system, there is little
possibility of a Java program damaging other files or applications.
6. What are classpath variables?
Classpath is an environment variable that tells the Java Virtual Machine where to look for
user-defined classes and packages in Java programs. The Classpath is the connection
between the Java runtime and the filesystem. It defines where the compiler and interpreter
look for .class files to load. The basic idea is that the file system hierarchy mirrors the Java
package hierarchy, and the Classpath specifies which directories in the filesystem serve as
roots for the Java package hierarchy.
7. Explain the architecture of code execution process inside JRE ?

37

38

8. What is Java Run Time Environment ?


Java Virtual Machine (JVM) along with Java Class Libraries which implement the Java
application programming interface (API) form the Java Runtime Environment (JRE).
9. What are the steps involved in Java Application Execution ?

Compiling Java Source Files into *.class file. (Byte Code)

Loading class file into Java Run Time (JRE) using class loader

Use Bytecode verifier to check for byte code specification

Use Just In time Code Generator or Interpreter for byte code execution

10. What is Just in Time Compiler ?


Just in time Compiler (JIT) compiles JAVA byte code to native machine code and execute it
directly on the underlying hardware. Just in time compilation which provides application
execution speeds near to C or C++ application.
11. What is Java Development Kit (JDK) ?
Java Development Kit (JDK) is a super set of the JRE, which contains Java Run-time
Environment (JRE) , Compilers and debuggers required to develop applets and applications.

38

39
12. What is Garbage Collector ?
For executing programs, application are allocated memory at runtime. After execution of
programs, unused memory need to be allocated. Allocation and deallocation of memory is
done by programmers developing application using C, C++ programming language . Java
internally uses garbage collector to deallocate unused memory which make the life of
programmer easy.
13. What is class loader ?
Class loader is used to load all the classes required execute the application into Java Virtual
Machine (JVM). After the class is loaded memory required for the application is determined.
14. What is byte code verifier ?
Byte code verifier checks for illegal code like forges pointers, violated access rights on
objects etc. in complied byte code.
Must Read - Top Java Collections Interview Questions
15. What are the java verifications done by byte code verifier ?
1. Check whether classes follow JVM specification for classes
2. Check for stack overflows
3. Check for access restriction violations
4. Illegal data conversions
16. What is Java API?
An application programming interface (API) is a library of functions that Java provides for
programmers for common tasks like file transfer, networking, and data structures.
17. Give Some examples of Java API.

Java.applet - Applet class

Java.awt - Windows, buttons, mouse, etc.

Java.awt.image - image processing

Java.awt.peer - GUI toolkit


39

40

Java.io - System.out.print

Java.lang - length method for arrays; exceptions

Java.net - sockets

Java.util - System.getProperty
18. What is an applet?
An applet is a small Java program that runs within a web page on your browser. Unlike a
traditional desktop application, an applet is severely limited as to what it can perform on your
desktop.

Applet read and write files.

Applet integrates with desktop services (e.g., e-mail).

It is connected to other servers.

It is also built with security in mind.

If the user allows, an applet can be given more authority.


Core Java Interview Questions on OOPS
19. What is a class?
A class is a blueprint or prototype that defines the variables and the methods common to all
objects of a certain kind.
20. What is an object?
An object is a software construct that encapsulates data, along with the ability to use or
modify that data, into a software entity. An object is a self-contained entity which has its own
private collection of properties (ie. data) and methods (i.e. operations) that encapsulate
functionality into a reusable and dynamically loaded structure.
21. What an object contains?
An object has - State and Behavior
40

41
22. What is object oriented program?
An Object-Oriented Program consists of a group of cooperating objects, exchanging
messages, for the purpose of achieving a common objective.
23. What are the benefits of OOPS?

Real-world programming

Reusability of code

Modularity of code

Resilience to change

Information hiding
24. What are the features of OOPS?

Encapsulation

Abstraction

Inheritance

Polymorphism
25. What is encapsulation?
Encapsulation is the ability of an object to place a boundary around its properties (i.e. data)
and methods (i.e. operations). Grady Booch, defined the encapsulation feature as:
Encapsulation is the process of hiding all of the details of an object that do not contribute to
its essential characteristics.
26. What is abstraction?
An Abstraction denotes the essential characteristics of an object that distinguishes it from all
other kinds of objects and thus provides crisply defined conceptual boundaries, relative to the
perspective of the viewer.
27. What is the difference between encapsulation and abstraction?

41

42
Encapsulation hides the irrelevant details of an object and Abstraction makes only the
relevant details of an object visible.
28. What is inheritance?
Inheritance is the capability of a class to use the properties and methods of another class
while adding its own functionality. It enables you to add new features and functionality to an
existing class without modifying the existing class.
Must Read - Java Thread Interview Questions
29. What is superclass and subclass?

A superclass or parent class is the one from which another class inherits attributes
and behavior.

A subclass or child class is a class that inherits attributes and behavior from a
superclass.
30. What are the types of inheritance?

Single inheritance

Multiple inheritance
31. What is single inheritance?
Subclass is derived from only one superclass.

42

43

32. What is multiple inheritance?


A subclass is derived from more than one super class

33. What is polymorphism?


Derived from two Latin words - Poly, which means many, and morph, which means forms.

It is the capability of an action or method to do different things based on the object


that it is acting upon.

In object-oriented programming, polymorphism refers to a programming language's


ability to process objects differently depending on their data type or class.
43

44
34. Describe method overloading with example?
Java allows to define several methods with same name within a class. Methods are identified
with the parameters set based on:

the number of parameters

types of parameters and

order of parameters.
Compiler selects the proper method. This is called as Method overloading. Method
overloading is used perform same task with different available data. For Example:
int sum(int a,int b) { return a+b;}
int sum(int a,int b,int c) { return a+b+c;}
float sum(float a, float b, float c) { return a+b+c;}
35. How to identify starting method of a program ?
Method starting with following code
public static void main (String args[])
{
}
Java Interview Questions on Classes & Packages
36. How do we access data members of a class in java?
Dot Operator(.) is used to access the data members of a class outside the class by
specifying the data member name or the method name.
What is "this" reference in java?
this is a reference to the current object. "this" is used to refer to the current object when it
has to be passed as a parameter to a method.
otherobj1.anymethod(this);
refer to the current object when it has to be returned in a method. Refer the instance
variables if parameter names are same as instance variables to avoid ambiguity.

44

45
public void method1(String name){
this.name=name;
}
The this keyword included with parenthesis i.e. this() with or without parameters is used to
call another constructer. The default construct for the Car class can be redefined as below
public Car(){
this(NoBrand,NoColor,4,0);
}
The this() can be called only from a constructor and must be the first statement in the
constructor
38. What are the uses of Java packages?
"A package is a namespace that organizes the a set of related classes and interfaces. It also
defines the scope of a class. An application consists of thousands of classes and interfaces,
and therefore, it is very important to organize them logically into packages. By definition,
package is a grouping of related types providing access protection and name space
management." Packages enable you to organize the class files provided by Java.
39. What is the significance of import keyword?
The classes in the packages are to be included into the applications as required. The classes
of a package are included using import keyword. The import keyword followed by fully
qualified class name is to be placed before the application class definition.
import classname ;
// Class Definition.
Ex: import Java.util.Date;
import Java.io.*;
// Class Definition
above indicates to import all the classes in a package.
All the classes in Java.lang package are included implicitly.
40. What is user defined package in java?
When you write a Java program, you create many classes. You can organize these classes
by creating your own packages. The packages that you create are called user-defined
packages. A user-defined package contains one or more classes that can be imported in a
Java program.

45

46
package land.vehicle;
public class Car
{
String brand;
String color;
int wheels;
}
41. How to compile a Java Source file ?
From command prompt, Go to location in which Java file is located. Enter command javac
followed by Java source file name. For example, To compile person class, type command
javac Person.java . Class files will be generated in the same location
42. How to compile all the files in a Folder?
javac *.java
43. How to place compiled Java file in a different location ?
To compile Java classes and place all the file in a different location use command javac
-d ../Java/All/*.java
44. How to run a compiled Java file ?
Go to location in which Java file is located from command prompt. Enter command java
followed by class name . For example to execute Employee class, type command java
Employee
45. Why Information hiding is used and how Information hiding is implemented in Java
?
In order to avoid direct access of an attribute in a class, attributes are defined as private and
use getter and setter to restrict the access of attributes in a class. Example class is given
below
public class Person {
private String FirstName;

public String getFirstName()


{
return FirstName;
46

47
}
public void setFirstName(String FirstName)
{
this.FirstName = FirstName;
}
}
46. What is a Constructor ?
A constructor is a special method that initializes the instance variables. The method is called
automatically when an object of that class is created. A constructor method has the same
name as the that of the class.
A constructor always returns objects of the class type hence there is no return type specified
in its definition. A constructor is most often defined with the accessibility modifier public so
that every program can create an instance but is not mandatory. A constructor is provided to
initialize the instance variables in the class when it is called.
If no constructor is provided, a default constructor is used to create instances of the class. A
default Constructor initializes the instance variables with default values of the data types. If at
least one constructor is provided , default constructor is not provided by JVM. A class can
have multiple constructors.
class Car {
String brand;
String color;
int wheels;
int speed;
int gear;
public Car() {
brand=NoBrand;
color=NoColor;
wheels=4;
speed=80;
}
public Car(String b, String c, int w, int s, int g)
{
brand=b;
color=c;
wheels=w;
47

48
speed=s;
}
void accelerate(){}
void brake(){}
void changeGear(){}
}
What is access modifier and what are its types?
An attribute that determines whether or not a class member is accessible in an expression or
declaration. Different types of access modifiers are:

Public - Members are accessible to the class and to other classes.

Private - Members are accessible only to the class.

Protected - Members are accessible only to the class and its subclass(es).

Default - Members are accessible only to the class and other classes within that
package. This is the default access specifier.
48. What is final keyword?
A final data members cannot be modified. A final method cannot be overridden in the
subclass. A class declared as final cannot be inherited .
49. What is static keyword?
Static keyword is used to define data members and methods that belongs to a class and not
to any specific instance of a class. Static Methods and data members can be called without
instancing the class.A static member exists when no objects of that class exist.
50. What is abstract keyword?
Abstract keyword is used to declare class that provides common behavior across a set of
subclasses. Abstract class provides a common root for a group of classes. An abstract
keyword with a method does not have any definition.

48

49
51. What is synchronized keyword?
It controls the access to a block in a multithreaded environment.
52. What is native keyword?
Native keyword is used only with methods. It signals the compiler that the method has been
coded in a language other than Java. It indicates that method lies outside the Java Runtime
Environment.
53. What is a transient variable?
A transient variable is a variable that may not be serialized.i.e JVM understands that the
indicated variable is not part of the persistent state of the object. For example
class A implements Serializable {
transient int i; // will not persist
int j; // will persist
}
Here, if an object of type A is written to a persistent storage area, the contents of i would not
be saved, but the contents of j would.
54. What is sctrictfp keyword?
strictfp can be used to modify a class or a method, but never a variable. Marking a class as
strictfp means that any method code in the class will conform to the IEEE 754 standard rules
for floating points. Without that modifier floating points used in the methods might behave in a
platform-dependent way.
If not at class class level , strictfp behavior can be applied at method level, by declaring a
method as strictfp. Usage of strictfp is required when floating point values should be
consistent across multiple platforms.
55. Explain method overriding with an example?
Method overriding is defined as creating a non-static method in the subclass that has the
same return type and signature as a method defined in the superclass. Signature of a
method includes name of method and number, sequence, type of arguments.

49

50
public class Person {
private String name;
private String ssn;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name; }
public String getId() {
return ssn;}
getId method is overridden in subclass:
public class Employee extends Person
{
private String empId;
public void setId(String empId)
{
this.empId=empId;
}
public String getId() {
return empId;
}
}
56. What is the use of super keyword. Give an example?
It allows you to access methods and properties of the parent class.
public class Person {
private String name;
public Person(String name) {
this.name = name; }
public String getName() {
return name;
}}
public class Employee extends Person {
private String empID;

50

51
public Employee(String name) {
super(name); // Calls Person constructor
}
public void setID(String empID){
this.empID=empID;
}
public String getID(){
return empID;
}
}
57. What is an interface?
A programmers tool for specifying certain behaviors that an object must have in order to be
useful for some particular task.Interface is a conceptual entity. It can contain only constants
(final variables) and non-implemented methods (Non implemented methods are also known
as abstract methods).
For example, you might specify Driver interface as part of a Vehicle object hierarchy. A
human can be a Driver, but so can a Robot.
What is an abstract class?

An Abstract class is a conceptual class.

An Abstract class cannot be instantiated objects cannot be created.

Abstract classes provides a common root for a group of classes, nicely tied together
in a package.

When we define a class to be final, it cannot be extended. In certain situation, we


want properties of classes to be always extended and used. Such classes are called
Abstract Classes.
59. What are the properties of abstract class?

A class with one or more abstract methods is automatically abstract and it cannot be
instantiated.

A class declared abstract, even with no abstract methods can not be instantiated.

51

52

A subclass of an abstract class can be instantiated if it overrides all abstract methods


by implementation them.

A subclass that does not implement all of the superclass abstract methods is itself
abstract; and it cannot be instantiated.

We cannot declare abstract constructors or abstract static methods.


60. What is object class in java?
Every class that we create extends the class Object by default. That is the Object class is at
the highest of the hierarchy. This facilitates to pass an object of any class to be passed as an
argument to methods.
61. What are the methods of object class?
The methods in this class are:

equals(Object ref) - returns if both objects are equal

finalize( ) - method called when an objects memory is destroyed

getClass( ) - returns class to which the object belongs

hashCode( ) - returns the hashcode of the class

notify( ) - method to give message to a synchronized methods

notifyAll( ) - method to give message to all synchronized methods

toString() - return the string equivalent of the object name

wait() - suspends a thread for a while

wait(...) - suspends a thread for specified time in seconds


62. What does java.util package provides?
The java.util package provides various utility classes and interfaces that support date and
calendar operations, String manipulations and Collections manipulations.

52

53
63. How do we convert object to string?
Any Java reference type or primitive that appears where a String is expected will be
converted into a string.
System.out.println("1 + 2 = " + (1 + 2));
For an reference type (object) this is done by inserting code to call String toString() on the
reference.
All reference types inherit this method from java.lang.Object and override this method to
produce a string that represents the data in a form suitable for printing.
To provide this service for Java's primitive types, the compiler must wrap the type in a socalled wrapper class, and call the wrapper class's toString method.
String arg1 = new Integer(1 + 2).toString();
For user defined classes they will inherit the standard Object.toString() which produces
something like "ClassName@123456" (where the number is the hashcode representation of
the object). To have something meaningful the classes have to provide a method with the
signature public String toString().
public class Car() {
String toString()
{
return brand + : + color + : +wheels+ : + speed;
}
}
64. How can we convert string to object?
Many data type wrapper classes provide the valueOf(String s) method which converts the
given string into a numeric value. The syntax is straightforward. It requires using the static
Integer.valueOf(String s) and intValue() methods from the java.lang.Integer class.
To convert the String "22" into the int 22 you would write
int i = Integer.valueOf("22").intValue();
Doubles, floats and longs are converted similarly. To convert a String like "22" into the long
value 22 you would write
long l = Long.valueOf("22").longValue();

53

54
To convert "22.5" into a float or a double you would write:
double x = Double.valueOf("22.5").doubleValue(); float y = Float.valueOf("22.5").floatValue();
If the passed value is non-numeric like Four" it will throw a NumberFormatException.
65. What is Regular expression?
Regular expressions are a way to describe a set of strings based on common characteristics
shared by each string in the set. They can be used to search, edit, or manipulate text and
data.
The regular expression syntax supported by the java.util.regex API
What does rejex package consists of?
The java.util.regex package primarily consists of three classes: Pattern, Matcher, and
PatternSyntaxException. A Pattern object is a compiled representation of a regular
expression. The Pattern class provides no public constructors.
To create a pattern, you must first invoke one of its public static compile methods, which will
then return a Pattern object. These methods accept a regular expression as the first
argument; the first few lessons of this trail will teach you the required syntax.
A Matcher object is the engine that interprets the pattern and performs match operations
against an input string. Like the Pattern class, Matcher defines no public constructors. You
obtain a Matcher object by invoking the matcher method on a Pattern object. A
PatternSyntaxException object is an unchecked exception that indicates a syntax error in a
regular expression pattern.
67. What is StringBuffer class is used for?

It is used for creating and manipulating dynamic string data i.e., modifiable Strings.

It can store characters based on capacity. Capacity expands dynamically to handle


additional characters. It cannot use operators + and += for string concatenation.

It has fewer utility methods (e.g. substring, trim, ....)


68. What is the difference between StringBuffer and StringBuilder class?

54

55
StringBuffer class is not threadsafe whereas StringBuilder class is threadsafe. That means
the methods of StringBuilder class are synchronized.
69. What is matcher in regex package?
A matcher is created from a pattern by invoking the pattern's matcher method. Once created,
a matcher can be used to perform three different kinds of match operations:

The matches method attempts to match the entire input sequence against the
pattern.

The looking at method attempts to match the input sequence, starting at the
beginning, against the pattern.

The find method scans the input sequence looking for the next subsequence that
matches the pattern

70. How to add comments in Java File ?


Comments can be inserted in 3 ways as shown below

// Comment Type1

/* Multi Line Comments


* Comment Line 2 */

/* Documentation Comment
* Comment Line 2 */

This comment will be added in the automatic document generation


Core Java Interview Questions on Collections
71. What are the limitations of array?
Arrays do not grow while applications demand. It has inadequate support for inserting,
deleting, sorting, and searching operations.
55

56
72. What is collection framework?
Collections Framework provides a unified system for organizing and handling collections and
is based on four elements:

Interfaces that characterize common collection types

Abstract Classes which can be used as a starting point for custom collections and
which are extended by the JDK implementation classes.

Classes which provide implementations of the Interfaces.

Algorithms that provide behaviors commonly required when using collections i.e.
search, sort, iterate, etc.
Another item in collections framework is the Iterator interface. An iterator gives you a generalpurpose, standardized way of accessing the elements within a collection, one at a time.
73. What is set interface about?
Mathematically a set is a collection of non-duplicate elements.The Set interface is used to
represent a collection which does not contain duplicate elements. The Set interface extends
the Collection interface. It stipulates that an instance of Set contains no duplicate elements.
The classes that implement Set must ensure that no duplicate elements can be added to the
set. That is no two elements e1 and e2 can be in the set such that e1.equals(e2) is true.
74. What is HashSet, LinkedHashSet and TreeSet?
The Java platform contains three general-purpose Set implementations: HashSet, TreeSet,
and LinkedHashSet.

HashSet: This is an unsorted, unordered Set. This may be chosen when order of the
elements are not important .

LinkedHashSet: This is ordered. The elements are linked to one another (DoubleLinked). This will maintain the list in the order in which they were inserted.

TreeSet: This is a sorted set. The elements in this will be in ascending order in the
natural order. You can also define a custom order by means of a Comparator passed as a
parameter to the constructor.
56

57
75. Which one to choose and when among HashSet, LinkedHashSet and TreeSet?

HashSet is a good choice for representing sets if you don't care about element
ordering. But if ordering is important, then LinkedHashSet or TreeSet are better choices.
However, LinkedHashSet or TreeSet come with an additional speed and space cost.

Iteration over a LinkedHashSet is generally faster than iteration over a HashSet.

Tree-based data structures get slower as the number of elements get larger

HashSet and LinkedHashSet do not represent their elements in sorted order

Since TreeSet keeps its elements sorted, it can offer other features such as the first
and last methods,i.e the lowest and highest elements in a set, respectively.
What is Enumeration interface?
The Enumeration interface defines a way to traverse all the members of a collection of
objects. The hasMoreElements() method checks to see if there are more elements and
returns a boolean.
If there are more elements, nextElement() will return the next element as an Object. If there
are no more elements when nextElement() is called, the runtime NoSuchElementException
will be thrown.
77. Explain Iterator interface?
Iterator is a special object to provide a way to access the elements of a collection
sequentially. Iterator implements one of two interfaces: Iterator or ListIterator. An Iterator is
similar to the Enumeration interface, Iterators differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection during the
iteration with well-defined semantics.
Method names have been improved.
boolean hasNext() Returns true if the iteration has more elements. Object next() Returns the
next element in the iteration. void remove() Removes from the underlying collection the last
element returned by the iterator (optional operation).
78. What is SortedSet interface?

57

58
SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted.
TreeSet is a concrete class that implements the SortedSet interface. You can use an iterator
to traverse the elements in the sorted order.
79. How elements can be sorted in java collections?
The elements can be sorted in two ways. One way is to use the Comparable interface.
Objects can be compared using by the compareTo() method. This approach is referred to as
a natural order.
The other way is to specify a comparator for the elements in the set if the class for the
elements does not implement the Comparable interface, or you dont want to use the
compareTo() method in the class that implements the Comparable interface. This approach is
referred to as order by comparator
80. What is a list interface?

A list allows duplicate elements in a collection where duplicate elements are to be


stored in a collection, list can be used. A list also allows to specify where the element is to
be stored. The user can access the element by index.

The List interface allows to create a list of elements.The List interface extends the
Collection interface.
81. Compare ArrayList vs LinkedList?

ArrayList provides support random access through an index without inserting or


removing elements from any place other than an end.

LinkedList provides support for random access through an index with inserting and
deletion elements from any place .

If your application does not require insertion or deletion of elements, the Array is the
most efficient data structure.
82. What is a vector class?
The Vector class implements a growable array of objects. Like an array, it contains
components that can be accessed using an integer index. However, the size of a Vector can

58

59
grow or shrink as needed to accommodate adding and removing items after the Vector has
been created.
83. What is a Stack class?
The Stack class represents a last-in-first-out (LIFO) stack of objects. The elements are
accessed only from the top of the stack. You can retrieve, insert, or remove an element from
the top of the stack.
84. What is a Map interface?
A Map is a storage that maps keys to values. There cannot be duplicate keys in a Map and
each key maps to at most one value. The Map interface is not an extension of Collection
interface. Instead the interface starts of its own interface hierarchy. for maintaining key-value
associations. The interface describes a mapping from keys to values, without duplicate keys,
by definition. The Map interface maps keys to the elements. The keys are like indexes. In
List, the indexes are integer. In Map, the keys can be any objects.
85. Describe about HashMap and TreeMap?
The HashMap and TreeMap classes are two concrete implementations of the Map interface.
Both will require key &value. Keys must be unique. The HashMap class is efficient for
locating a value, inserting a mapping, and deleting a mapping. The TreeMap class,
implementing SortedMap, is efficient for traversing the keys in a sorted order.
HashMap allows null as both keys and values.TreeMap is slower than HashMap. TreeMap
allows us to specify an optional Comparator object during its creation. This comparator
decides the order by which the keys need to be sorted.
86. What is the purpose of Collections class in util package?
The Collections class contains various static methods for operating on collections and maps,
for creating synchronized collection classes, and for creating read-only collection classes.
87. How do we order/sort objects in collections?
To provide for ordering/sorting of the objects Java API provides two interfaces Comparable
and Comparator
59

60

Comparable interface is in java.lang

Comparator interface is in java.util


88. When to use Comparable and Comparator in code?
The Comparable interface is simpler and less work

Your class implements Comparable

You provide a public int compareTo(Object o) method

Use no argument in your TreeSet or TreeMap constructor

You will use the same comparison method every time


The Comparator interface is more flexible but slightly more work

Create as many different classes that implement Comparator as you like

You can sort the TreeSet or TreeMap differently with each

Construct TreeSet or TreeMap using the comparator you want

For example, sort Students by score or by name


Suppose you have students sorted by score, in a TreeSet you call studentsByScore. Now you
want to sort them again, this time by name
Comparator<Student> myStudentNameComparator = new MyStudentNameComparator();
TreeSet studentsByName = new TreeSet(myStudentNameComparator);
studentsByName.addAll(studentsByScore);
What are the new features added in Java 1.5?
Generic classes

New approach to loops Enhanced for loop

Static imports

Arrays, string builder, queues and overriding return type


Annotation

60

61

Output formatting format() and printf()

Autoboxing of primitive types

Enumerated types

Variable length of arguments

90. What is Generic classes?


Similar in usage to C++ templates, but do not generate code for each implementation. It
ensure stored/retrieved type of objects.Check done at compile-time avoid nasty casting
surprises during runtime. Generics are removed from compiled classes. Java 5 is upwardly
compatible with Java 1.4, so old programs must continue to work. It can be used in legacy
code to check for place where incorrect type is inserted
91. What is the big advantage of Generics?
Big advantage: collections are now type safe. For example, you can create a Stack that holds
only Strings as follows:
Stack<String> names = new Stack<String>();
You can write methods that require a type-safe collection as follows:
void printNames(Stack<String> names) {
String nextName = names.pop(); // no casting needed!
names.push("Hello"); // works just the same as before
names.push(Color.RED); // compile-time error!
92. What is StringBuilder class?
It is an improvement upon StringBuffer. It allows quicker concatenation of strings. It is not
safe for use by multiple threads at the same time since the methods are not synchronized.
Why use it?
Creating new Strings in a loop can be inefficient because of the number new objects that are
created and discarded.

61

62
StringBuilder.append(<type> <value>)
StringBuilder.insert(<type> <value>)
93. What is Queue interface?
It extends Collection interface. It is designed for holding elements prior to processing.

It is typically ordered in a FIFO manner.


Main Methods are - remove() and pull(). Both return the head of the queue. When

empty, the remove() method throws an exception while poll() returns null.
94. Describe covariant return types with an example?
It allows the user to have a method in inherited class with same signature as in parents class
but differing only in return types. It makes programs more readable and solves casting
problem.
class Shape
{
public Shape transform(int x, int y)
}
class Rectangle extends Shape
{
public Rectangle transform(int x, int y)
}
95. What is boxing and unboxing ?
Converting a primitive data type to its corresponding wrapper class object is called boxing or
autoboxing. Example of boxing,
int i = 0;
Integer O = new Integer(i);
Unboxing is the exact opposite of boxing where wrapper class object is converted into
primitive data type. Example of unboxing,
i = O.intValue();
96. How autoboxing was done before java 5 and in java 5 version?
Before 5.0
62

63
ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, new Integer(42)); int total =
(list.get(0)).intValue();
From 5.0 version:
ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, 42);int total = list.get(0);
97. How java distinguishes between primitive types and objects?
Java distinguishes between primitive types and Objects.

Primitive types, i.e., int, double, are compact, support arithmetic operators.

Object classes (Integer, Double) have more methods: Integer.toString()


You need a wrapper to use Object methods:
Integer ii = new Integer( i );
ii.hashCode()
Similarly, you need to unwrap an Object to use primitive operation
int j = ii.intValue() * 7;
Java 1.5 makes this automatic:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);
98. What is Enum?
An enumeration, or enum, is simply a set of constants to represent various values. Heres
the old way of doing it:
public final int SPRING = 0;
public final int SUMMER = 1;
public final int FALL = 2;
public final int WINTER = 3;
This is a nuisance, and is error prone as well. Heres the new way of doing it,
enum Season { winter, spring, summer, fall }
63

64
Enums are classes, extends java.lang.Enum.Enums are final, cant be subclassed. Only one
Constructor and is protected. It implement java.lang.Comparable: compareTo() and
implements Serializable.
Core Java Interview Questions on Exceptions
99. What is an exception?
An exception can be defined as an abnormal event that occurs during program execution and
disrupts the normal flow of instructions.
What are the uses of exceptions?

Consistent error reporting style.

Easy to pass errors up the stack.

Pinpoint errors better in stack trace.

As long as you fail fast and throw as soon as you find a problem.

Wrap useful information up in your exception classes, use that information later when
handling the exception.

Exceptions dont always have to be errors, maybe your program can cope with the
exception and keep going!

Separating error handling code from Regular code


101. What are the types of error?
There are two types of error:

Compile time error

Run time error


102. List some exception occurence reason?
Running out of memory, Resource allocation errors, Inability to find files, Problem in network
connectivity etc.
64

65
103. What are checked exceptions?
Checked exceptions are so called because both the Java compiler and the Java virtual
machine check to make sure this rule is obeyed. The checked exceptions that a method may
raise are part of the method's signature. Every method that throws a checked exception must
advertise it in the throws clause in its method definition.
Every method that calls a method that advertises a checked exception must either handle
that exception (with try and catch) or must in turn advertise that exception in its own throws
clause.
104. What are unchecked exceptions?
Raised implicitly by system because of illegal execution of program. Do not need to
announce the possibility of exception occurrence. When unchecked exception occurred, if
programmer does not deal with it, it would be processed by default exception handler.
105. How exception handling is implemented using try and catch statement?
Using try and catch statements. The try block encloses the statements that might raise an
exception within it and defines the scope of the exception handlers associated with it. The
catch block is used as an exception-handler. You enclose the code that you want to monitor
inside a try block to handle a run time error.
106. What is throwing an exception?
The throw statement causes termination of the normal flow of control of the Java code and
stops the execution of the subsequent statements if an exception is thrown when the throw
statement is executed.
The throw clause transfers the control to the nearest catch block handling the type of
exception object throws. The following syntax shows how to declare the throw statement:
public double divide(int dividend, int divisor) throws ArithmeticException {
if(divisor == 0) {
throw new ArithmeticException(Divide by 0 error);
}
return dividend / divisor;
}

65

66
107. What is using throws exceptions?
The throws statement is used by a method to specify the types of exceptions the method
throws. If a method is capable of raising an exception that it does not handle, the method
must specify that the exception has to be handled by the calling method. This is done using
the throws statement.
Example: void readData() throws IOException
108. How can we create our own exceptions?
Defining your own exceptions let you handle specific exceptions that are tailor-made for your
application. Steps to Create a User Defined Exception:
Create a class that extend from a right kind of class from the Exception Hierarchy. For
Example,
public class DivideByZeroException extends ArithmeticException
{
public DivideByZeroException()
{
super("Divide by 0 error");
}
}
109. What are the exception occurrence levels?
Hardware/operating system level :

Arithmetic exceptions; divide by 0, under/overflow.

Memory access violations; segment fault, stack over/underflow.


Language level :

Type conversion; illegal values, improper casts.

Bounds violations; illegal array indices.

Bad references; null pointers.


Program level :

66

67
User defined exceptions.

110. What are the categories of exceptions?


There are two categories of exceptions:
Built in Exceptions

Checked Exceptions

Unchecked Exceptions
User Defined Exceptions

111. What is the use of finally clause?


The finally block is used to process certain statements, no matter whether an exception is
raised or not. Generally we write code resource cleaning operations inside finally block.
What is an assertion?
An assertion is a statement in the JavaTM programming language that enables test the
assumptions about program. Each assertion contains a boolean expression that is assumed
to be true. When executed if the boolean expression is false, the system will throw an error.
Writing assertions while programming is one of the quickest and most effective ways to
detect and correct bugs. As an added benefit, assertions serve as internal documentation,
thus enhancing maintainability.
113. What are the forms of assertion statements?
The assertion statement has two forms.
assert Expression1 ;
Where Expression1 is a boolean expression. When the system runs the assertion, it
evaluates Expression1 and if it is false throws an AssertionError with no detail message.
assert Expression1 : Expression2 ;
Where Expression1 is a boolean expression and Expression2 is an expression that has a
value. (It cannot be an invocation of a method that is declared void). This form of asssert
statement provides a detail message for the AssertionError. The system passes the value of

67

68
Expression2 to the appropriate AssertionError constructor, which uses the string
representation of the value as the error's detail message.
114. How do we enable and disable assertions?
To enable assertions use -enableassertions, or -ea, option at runtime. To disable assertions
use -disableassertions, or -da. Specify the granularity with the arguments provided at
runtime.

no arguments - Enables or disables assertions in all classes except system classes.

packageName - Enables or disables assertions in the named package and any


subpackages.
"-" Enables or disables assertions in the unnamed package in the current working

directory.
className - Enables or disables assertions in the named class

Core Java Interview Questions on I/O


115. What are the basic functionalities provided by io package?
Many Java programs need to read or write data. This can be obtained by using the classes in
java.io package. Your program can get input from a data source by reading a sequence
characters from a InputStream attached to the source. Your program can produce output by
writing a sequence of characters to an OutputStream attached to a destination.
116. What is a Stream?
A stream is a flowing set of data. Streams support many different kinds of data, including
simple bytes, primitive data types. Some streams simply pass on data, others manipulate and
transform the data in useful ways. A program uses an input stream to read data from a
source, one item at a time and uses an output stream to write data to destination, one item at
a time.
117. What is an inputstream?
The InputStream class is an abstract superclass that provides a minimal programming
interface and a partial implementation of input streams. The InputStream class defines
methods for reading bytes or arrays of bytes.
68

69

118. What is a FileInputStream?


It reads data from file on the native file system. It is meant for reading streams of raw bytes
such as image data.
119. What is ByteArrayInputStream?
A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from
the stream. An internal counter keeps track of the next byte to be supplied by the read
method.
120. What is SequenceInputStream, StringBufferInputStream, PipedInputStream?

SequenceInputStream : It concatenate multiple input streams into one input stream.

StringBufferInputStream : It allow programs to read from a StringBuffer as if it were an


input stream.

PipedInputStream : In this data can be read from a thread by using PipedInputStream


121. What is FilterInputStream?
FilterInputStream is a subclass of InputStream.These classes define the interface for filtered
streams which process data as it's being read or written.
122. What is BufferedInputStream?
Buffered input streams read data from a memory area known as a buffer; the native input API
is called only when the buffer is empty.
123. What is an Enumeration interface and what are its methods?
The Enumeration interface defines a way to traverse all the members of a collection of
objects. The hasMoreElements() method checks to see if there are more elements and
returns a boolean. If there are more elements, nextElement() will return the next element as
an Object. If there are no more elements when nextElement() is called, the runtime
NoSuchElementException will be thrown.
124. What is a DataInputStream?

69

70
A data input stream lets an application read primitive Java data types from an underlying
input stream in a machine-independent way.
125. What is an OutputStream?
The OutputStream class is an abstract superclass that provides a minimal programming
interface and a partial implementation of output streams.
OutputStream defines methods for writing bytes or arrays of bytes.
126. What is a FileOutputStream?
A file output stream is an output stream for writing data to a File. Whether or not a file is
available or may be created depends upon the underlying platform.
What is a ByteArrayOutputStream and FilterOutputStream?
ByteArrayOutputStream class implements an output stream in which the data is written into a
byte array. FilterOutputStream class is the superclass of all classes that filter output streams.
These streams sit on top of an already existing output stream (the underlying output stream)
which it uses as its basic sink of data, but possibly transforming the data along the way or
providing additional functionality .
128. What is BufferedOutputStream and PrintStream?
A buffered lets you write to a stream without causing a write every time. The data is first
written into a buffer. Data is written to the actual stream only when the buffer is full, or when
the stream is flushed. A PrintStream adds functionality to another output stream, namely the
ability to print representations of various data values conveniently.
129. What is object serialization?
Serializing objects is the process of writing objects to a file. When an object is serialized, its
state and other attributes are converted into an ordered series of bytes. This byte series can
be written into streams.
130. Why should we use object serialization?
Writing the code for saving data, can become repetitive work. First, the programmer must
create a specification document for the proposed file structure. Next, the programmer must

70

71
implement save and restore functions that convert object data to & from primitive data types,
and test it with sample data.
If the application later requires new data to be stored, the file specification must be modified,
as well as the save and restore methods. The solution to the problems specified is Object
serialization. Object serialization takes an object's state, and converts it to a stream of data.
With object serialization, it's an easy task to take any object, and make it persistent, without
writing custom code to save object member variables.
131. How to prevent writing some member data value during object serialization?
You use the transient keyword to indicate to the Java virtual machine that the indicated
variable is not part of the persistent state of the object. Variables that are part of the
persistent state of an object must be saved when the object is archived .
132. What are Reader and Writer classes?
Input and output for characters streams are handled through subclasses of the Reader and
Writer classes. These classes are abstractions that Java provides for dealing with reading
and writing character data.
133. Give few examples of simple Reader and Writer classes?

FileReader and FileWriter : Read data from or write data to a file on the native file
system.

PipedReader and PipedWriter : Pipes are used to channel the output from one
program (or thread) into the input of another.

CharArrayReader and CharArrayWriter : Read data from or write data to a char array
in memory.
134. What are FilterReader/FilterWriter, BufferedReader/BufferedWriter and
PrintWriter?

FilterReader and FilterWriters are subclasses of Reader and Writer, respectively.


These classes define the interface for filtered streams which process data as it's being read
or written.

BufferedReader and BufferedWriter : Buffer data while reading or writing, thereby


reducing the number of accesses required on the original data source.
71

72

PrintWriter : An output stream with convenient print methods


135. What is a File class?
It represents a file on the native file system. You can create a File object for a file on the
native file system and then query the object for information about that file (such as its full
pathname).
136. What are the functionalaties we get using File class?
The File class in the java.io package provides various methods to access the properties of a
file or a directory, such as file permissions, date and time of creation, and path of a directory.
Core Java Interview Questions on Threads
137. What are the benefits of using threads in an application?

It improves performance .

It minimizes system resource usage.

We can access multiple applications simultaneously.

Threads simplifies the program structure.

We can send & receive data on network at the same time.

We can read & write files to disk simultaneously.


138. What are the differences between process and threads?
Process
It is executable program loaded in memory. It has its own address space variables & data
structures (in memory). Process communicates via operating system, files, network. A
process may contain multiple threads.
Threads
It is sequentially executed stream of instructions. Shares address space with other threads. It
has its own execution context. Multiple thread in process execute same program.

72

73
139. What are the types of thread?
There are two types of thread:

Single Threaded Process

Multi Threaded Process


140. What is single threaded and multi threaded process?

Single Threaded Process: A thread is defined as the execution of a program. A


process that is made of one thread is known as single-threaded process.

Multi Threaded Process: A process that creates two or more threads is called a
multithreaded process.
What is the basic concept of multitasking and its types?
Multitasking is the ability to execute more than one task at the same time. Multitasking can be
divided into two categories:

Process based multitasking

Thread based multitasking


142. Give example and describe process and thread based multitasking?
Process based multitasking refers to working with two programs concurrently. For example,
working with MS-Word, Listening to mp3 song using Windows Media Player.
Thread based multitasking refers to working with parts of one program. For example, MSWord program can check spelling, count line numbers, column number while writing in a
document.
143. What are the disadvantages of multitasking?

Race condition

Deadlock condition

Lock starvation
144. How to use threads in java?
73

74
By using Thread class, Java.lang.Thread class is used to construct and access individual
thread in a multi threaded application?
145. What are the stages of Thread Lifecycle?

New : It is created byinstantiating the Thread class. Thread th = new Thread(this);

Runnable: By calling the start method that in turn call run method. th.start();

Not Runnable: Calling wait or sleep method or caused due to io interrupts. wait();
th.sleep(1000);

Dead or terminate: After run() method completes execution.


146. What are the two ways of creating threads in java?
Two ways of creating Thread in Java:

Extending from java.lang.Thread class

Implementing the Runnable Interface


147. Which is the first thread to be executed in a multithreaded process?
The first thread to be executed in a multithreaded process is called the main thread. The
main thread is created automatically on the startup of java program execution.
148. What is thread scheduling and what does it determines?
The execution of multiple threads on a single CPU is called scheduling.

It determines which runnable threads to run

It can be based on thread priority

It is part of OS or Java Virtual Machine (JVM)


149. What thread scheduling does java runtime supports?
The Java runtime supports a very simple, deterministic scheduling algorithm known as fixed
priority scheduling.

74

75
150. Describe thread policy in java?

Thread priorities are the integers in the range of 1 to 10 that specify the priority of one
thread with respect to the priority of another thread.

Each Java thread is given a numeric priority between MIN_PRIORITY and


MAX_PRIORITY.

The Java Run-time system selects the runnable thread with the highest priority of
execution when a number of threads get ready to execute.

The Java Run-time Environment executes threads based on their priority.

A thread with higher priority runs before threads with low priority.

A given thread may, at any time, give up its right to execute by calling the yield
method. Threads can only yield the CPU to other threads of the same priority attempts to
yield to a lower priority thread are ignored.

You can set the thread priority after it is created using the setPriority() method
declared in the Thread class.
151. What is synchronization?
Synchronization of threads ensures that if two or more threads need to access a shared
resource then that resource is used by only one thread at a time. Synchronization is based
on the concept of monitor.
152. Why synchronization is required?

Problem: Race condition! Two or more threads access to same object and each call a
method that modifies the state of the object.

Result: Corrupted object. Solution to this is synchronization.


153. What is monitor?
A monitor is an object that can block threads and notify them when it is available.The monitor
controls the way in which synchronized methods access an object or class. To enter an
objects monitor, you need to call a synchronized method.

75

76
154. How to acheive synchronization in java?
Synchronization can be acheived in java using synchronized keyword.
What are the two levels of acheiving synchronization?

Method level

Block level
156. What is inter thread communication?
A thread may notify another thread that the task has been completed. This communication
between threads is known as interthread communication.
157. What are the various methods used in inter thread communication?
The various methods used in interthread communication are:

wait()

notify()

notifyAll()
158. What is garbage collection?
Garbage collection is the feature of Java that helps to automatically destroy the objects
created and release their memory for future reallocation.
159. What are the various activities involved in garbage collection?
The various activities involved in garbage collection are:

Monitoring the objects used by a program and determining when they are not in use.

Destroying objects that are no more in use and reclaiming their resources, such as
memory space.

76

77

The Java Virtual machine (JVM) acts as the garbage collector that keeps a track of
the memory allocated to various objects and the objects being referenced.
160. How JDBC architecture can be categorized?
JDBC architecture can be categorized into two layers:

JDBC Application layer

JDBC Driver layer


161. In which package jdbc apli classes and interfaces are available?
The JDBC API classes and interfaces are available in the java.sql and the javax.sql
packages.
162. What are the commonly used classes and interfaces in JDBC api?
The commonly used classes and interfaces in the JDBC API are:

DriverManager class: Loads the driver for a database.

Driver interface: Represents a database driver. All JDBC driver classes must
implement the Driver interface.

Connection interface: Enables you to establish a connection between a Java


application and a database.

Statement interface: Enables you to execute SQL statements.

ResultSet interface: Represents the information retrieved from a database.

SQLException class: Provides information about the exceptions that occur while
interacting with databases.
163. What are the steps to create JDBC application?

Load a driver

Connect to a database

Create and execute sql statements

77

78

Handle exceptions
163. How do we load a driver in jdbc?
Loading a Driver can be done in two ways:
Programmatically:

Using the forName() method

Using the registerDriver()method


Manually:

By setting system property


164. How do we load driver programmatically?
Using the forName() method

The forName() method is available in the java.lang.Class class.

The forName() method loads the JDBC driver and registers the driver with the driver
manager.

The method call to use the the forName() method is:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Using the registerDriver() method

You can create an instance of the Driver class to load a JDBC driver. This instance
provide the name of the driver class at run time. The statement to create an instance of the
Driver class is:
Driver d = new sun.jdbc.odbc.JdbcOdbcDriver();
You need to call the registerDriver() method to register the Driver object with the
DriverManager. The method call to register the JDBC-ODBC Bridge driver is:
DriverManager.registerDriver(d);
165. How we connect to a database in JDBC?

78

79
Connecting to a Database Using DriverManager.getConnection() method:
Connection getConnection (String <url>)
Connection getConnection (String <url>, String <username>, String <password>)
Connects to given JDBC URL.
throws java.sql.SQLException
Returns a connection object.
Example:
Connection con=DriverManager.getConnection(jdbc:odbc:MyDSN,scott,tiger);
166. What are the different types of statements in JDBC?

Statement Interface : A Statement object is used for executing a static SQL statement
and obtaining the results produced by it.

Statement createStatement() : returns a new Statement object.

Prepared Statement Interface: When you use a PreparedStatement object to execute


a SQL statement, the statement is parsed and compiled by the database, and then placed
in a statement cache. From then on, each time you execute the same PreparedStatement, it
is once again parsed, but no recompile occurs. Instead, the precompiled statement is found
in the cache and is reused.

PreparedStatement prepareStatement(String sql) : returns a new PreparedStatement


object.

CallableStatement Interface : The interface used to execute SQL stored procedures.


167. What is a ResultSet interface?
A ResultSet provides access to a table of data generated by executing a Statement. Only one
ResultSet per Statement can be open at once. The table rows are retrieved in sequence. A
ResultSet maintains a cursor pointing to its current row of data. The 'next' method moves the
cursor to the next row.

79

You might also like