1 Day Before Interview
1 Day Before Interview
A list of 50 top frequently asked C programming interview questions and answers are given below.
1) What is C language?
C is known as a mother language because most of the compilers and JVMs are written in C language.
Most of the languages which are developed after C language has borrowed heavily from it like C++,
Python, Rust, javascript, etc. It introduces new core concepts like arrays, functions, file handling
which are used in these languages. More details.
o Simple: C is a simple language because it follows the structured approach, i.e., a program is
broken into parts
o Portable: C is highly portable means that once the program is written can be run on any
machine with little or no modifications.
o Mid Level: C is a mid-level programming language as it combines the low- level language with
the features of the high-level language.
o Fast Speed: C language is very fast as it uses a powerful set of data types and operators.
o Memory Management: C provides an inbuilt memory function that saves the memory and
improves the efficiency of our program.
More details.
printf(): The printf() function is used to print the integer, character, float and string values on to the
screen.
scanf(): The scanf() function is used to take input from the user.
More details.
8) What is the difference between the local variable and global variable in C?
Following are the differences between a local variable and global variable:
Life Life of a variable is created when the Life of a variable exists until the
function block is entered and destroyed program is executing.
on its exit.
Storage Variables are stored in a stack unless The compiler decides the storage
specified. location of a variable.
More details.
o A variable which is declared as static is known as a static variable. The static variable retains its
value between multiple function calls.
o Static variables are used because the scope of the static variable is available in the entire
program. So, we can access a static variable anywhere in the program.
o The static variable is initially initialized to zero. If we update the value of a variable, then the
updated value is assigned.
o The static variable is used as a common value which is shared by all the methods.
o The static variable is initialized only once in the memory heap to reduce the memory usage.
More details.
o C functions are used to avoid the rewriting the same code again and again in our program.
o C functions can be called any number of times from any place of our program.
o When a program is divided into functions, then any part of our program can easily be tracked.
o C functions provide the reusability concept, i.e., it breaks the big task into smaller tasks so that
it makes the C program more understandable.
More details.
11) What is the difference between call by value and call by reference in C?
Following are the differences between a call by value and call by reference are:
Call by value Call by reference
Description When a copy of the value is passed to When a copy of the value is passed to
the function, then the original value is the function, then the original value is
not modified. modified.
Memory Actual arguments and formal arguments Actual arguments and formal
location are created in separate memory arguments are created in the same
locations. memory location.
Safety In this case, actual arguments remain In this case, actual arguments are not
safe as they cannot be modified. reliable, as they are modified.
Arguments The copies of the actual arguments are The addresses of actual arguments are
passed to the formal arguments. passed to their respective formal
arguments.
1. #include <stdio.h>
2. void change(int,int);
3. int main()
4. {
5. int a=10,b=20;
6. change(a,b); //calling a function by passing the values of variables.
7. printf("Value of a is: %d",a);
8. printf("\n");
9. printf("Value of b is: %d",b);
10. return 0;
11. }
12. void change(int x,int y)
13. {
14. x=13;
15. y=17;
16. }
Output:
Value of a is: 10
Value of b is: 20
1. #include <stdio.h>
2. void change(int*,int*);
3. int main()
4. {
5. int a=10,b=20;
6. change(&a,&b); // calling a function by passing references of variables.
7. printf("Value of a is: %d",a);
8. printf("\n");
9. printf("Value of b is: %d",b);
10. return 0;
11. }
12. void change(int *x,int *y)
13. {
14. *x=13;
15. *y=17;
16. }
Output:
Value of a is: 13
Value of b is: 17
More details.
12) What is recursion in C?
When a function calls itself, and this process is known as recursion. The function that calls itself is
known as a recursive function.
1. Winding phase
2. Unwinding phase
Winding phase: When the recursive function calls itself, and this phase ends when the condition is
reached.
Unwinding phase: Unwinding phase starts when the condition is reached, and the control returns to
the original call.
Example of recursion
1. #include <stdio.h>
2. int calculate_fact(int);
3. int main()
4. {
5. int n=5,f;
6. f=calculate_fact(n); // calling a function
7. printf("factorial of a number is %d",f);
8. return 0;
9. }
10. int calculate_fact(int a)
11. {
12. if(a==1)
13. {
14. return 1;
15. }
16. else
17. return a*calculate_fact(a-1); //calling a function recursively.
18. }
Output:
More details.
o One-dimensional array: One-dimensional array is an array that stores the elements one after
the another.
Syntax:
1. data_type array_name[size];
o Multidimensional array: Multidimensional array is an array that contains more than one
array.
Syntax:
1. data_type array_name[size];
Example of an array:
1. #include <stdio.h>
2. int main()
3. {
4. int arr[5]={1,2,3,4,5}; //an array consists of five integer values.
5. for(int i=0;i<5;i++)
6. {
7. printf("%d ",arr[i]);
8. }
9. return 0;
10. }
Output:
12345
More details.
A pointer is a variable that refers to the address of a value. It makes the code optimized and makes
the performance fast. Whenever a variable is declared inside a program, then the system allocates
some memory to a variable. The memory contains some address number. The variables that hold
this address number is known as the pointer variable.
For example:
1. Data_type *p;
The above syntax tells that p is a pointer variable that holds the address number of a given data type
value.
Example of pointer
1. #include <stdio.h>
2. int main()
3. {
4. int *p; //pointer of type integer.
5. int a=5;
6. p=&a;
7. printf("Address value of 'a' variable is %u",p);
8. return 0;
9. }
Output:
More details.
o Dynamic memory allocation: Pointers are used in allocation and deallocation of memory
during the execution of a program.
o Call by Reference: The pointers are used to pass a reference of a variable to other function.
o Data Structures like a tree, graph, linked list, etc.: The pointers are used to construct
different data structures like tree, graph, linked list, etc.
A pointer that doesn't refer to any address of value but NULL is known as a NULL pointer. When we
assign a '0' value to a pointer of any type, then it becomes a Null pointer.
More details.
A pointer which can access all the 16 segments (whole residence memory) of RAM is known as far
pointer. A far pointer is a 32-bit pointer that obtains information outside the memory in a given
section.
18) What is dangling pointer in C?
o If a pointer is pointing any memory location, but meanwhile another pointer deletes the memory
occupied by the first pointer while the first pointer still points to that memory location, the first
pointer will be known as a dangling pointer. This problem is known as a dangling pointer
problem.
o Dangling pointer arises when an object is deleted without modifying the value of the pointer.
The pointer points to the deallocated memory.
1. #include<stdio.h>
2. void main()
3. {
4. int *ptr = malloc(constant value); //allocating a memory space.
5. free(ptr); //ptr becomes a dangling pointer.
6. }
In the above example, initially memory is allocated to the pointer variable ptr, and then the memory
is deallocated from the pointer variable. Now, pointer variable, i.e., ptr becomes a dangling pointer.
1. #include<stdio.h>
2. void main()
3. {
4. int *ptr = malloc(constant value); //allocating a memory space.
5. free(ptr); //ptr becomes a dangling pointer.
6. ptr=NULL; //Now, ptr is no longer a dangling pointer.
7. }
In the above example, after deallocating the memory from a pointer variable, ptr is assigned to a
NULL value. This means that ptr does not point to any memory location. Therefore, it is no longer a
dangling pointer.
In case of a pointer to pointer concept, one pointer refers to the address of another pointer. The
pointer to pointer is a chain of pointers. Generally, the pointer contains the address of a variable. The
pointer to pointer contains the address of a first pointer. Let's understand this concept through an
example:
1. #include <stdio.h>
2. int main()
3. {
4. int a=10;
5. int *ptr,**pptr; // *ptr is a pointer and **pptr is a double pointer.
6. ptr=&a;
7. pptr=&ptr;
8. printf("value of a is:%d",a);
9. printf("\n");
10. printf("value of *ptr is : %d",*ptr);
11. printf("\n");
12. printf("value of **pptr is : %d",**pptr);
13. return 0;
14. }
In the above example, pptr is a double pointer pointing to the address of the ptr variable and ptr
points to the address of 'a' variable.
More details.
o The pointer is required to access the variable present in the static memory.
1. For example:
2. int a[10];
The above example creates an array of integer type, and the size of an array is fixed, i.e., 10.
More details.
o In case of dynamic memory allocation, memory is allocated at runtime and memory can be
increased while executing the program. It is used in the linked list.
o The malloc() or calloc() function is required to allocate the memory at the runtime.
o An allocation or deallocation of memory is done at the execution time of a program.
1. For example
2. int *p= malloc(sizeof(int)*10);
More details.
22) What functions are used for dynamic memory allocation in C language?
1. malloc()
o The malloc() function is used to allocate the memory during the execution of the program.
o It does not initialize the memory but carries the garbage value.
o It returns a null pointer if it could not be able to allocate the requested space.
Syntax
o The calloc() is same as malloc() function, but the difference only is that it initializes the
memory with zero value.
Syntax
2. realloc()
o The realloc() function is used to reallocate the memory to the new size.
o If sufficient space is not available in the memory, then the new block is allocated to
accommodate the existing data.
Syntax
1. ptr = realloc(ptr, newsize); // updating the memory size using realloc() function.
2. free():The free() function releases the memory allocated by either calloc() or malloc() function.
Syntax
More details.
calloc() malloc()
Description The malloc() function allocates a The calloc() function allocates multiple
single block of requested memory. blocks of requested memory.
Initialization It initializes the content of the It does not initialize the content of
memory to zero. memory, so it carries the garbage
value.
Return value It returns a pointer pointing to the It returns a pointer pointing to the
allocated memory. allocated memory.
More details.
24) What is the structure?
o The structure is a user-defined data type that allows storing multiple types of data in a single
unit. It occupies the sum of the memory of all members.
o Structure variables accessing the same structure but the memory allocated for each variable will
be different.
Syntax of structure
1. struct structure_name
2. {
3. Member_variable1;
4. Member_variable2
5. .
6. .
7. }[structure variables];
1. #include <stdio.h>
2. struct student
3. {
4. char name[10]; // structure members declaration.
5. int age;
6. }s1; //structure variable
7. int main()
8. {
9. printf("Enter the name");
10. scanf("%s",s1.name);
11. printf("\n");
12. printf("Enter the age");
13. scanf("%d",&s1.age);
14. printf("\n");
15. printf("Name and age of a student: %s,%d",s1.name,s1.age);
16. return 0;
17. }
Output:
o The union is a user-defined data type that allows storing multiple types of data in a single unit.
However, it doesn't occupy the sum of the memory of all members. It holds the memory of the
largest member only.
o In union, we can access only one variable at a time as it allocates one common space for all the
members of a union.
Syntax of union
1. union union_name
2. {
3. Member_variable1;
4. Member_variable2;
5. .
6. .
7. Member_variable n;
8. }[union variables];
value of a is 1085485921
value of b is 5.600022
value of ch is a
In the above example, the value of a and b gets corrupted, and only variable ch shows the actual
output. This is because all the members of a union share the common memory space. Hence, the
variable ch whose value is currently updated.
More details.
In C, every local variable of a function is known as an automatic (auto) variable. Variables which are
declared inside the function block are known as a local variable. The local variables are also known as
an auto variable. It is optional to use an auto keyword before the data type of a variable. If no value
is stored in the local variable, then it consists of a garbage value.
Syntax
1. #include<stdio.h>
2. int main()
3. {
4. char a[20];
5. int n=sprintf(a,"javaToint");
6. printf("value of n is %d",n);
7. return 0;}
Output:
value of n is 9
But, if we use #define, we can compile and run a C program without using the main() function. For
example:
1. #include<stdio.h>
2. #define start main
3. void start() {
4. printf("Hello");
5. }
More details.
The Token is an identifier. It can be constant, keyword, string literal, etc. A token is the smallest
individual unit in a program. C has the following tokens:
2. Keywords: Keywords are the predefined words that are explained by the compiler.
3. Constants: Constants are the fixed values that cannot be changed during the execution of a
program.
4. Operators: An operator is a symbol that performs the particular operation.
5. Special characters: All the characters except alphabets and digits are treated as special
characters.
The argument passed to the main() function while executing the program is known as command line
argument. For example:
More details.
The ANSI stands for " American National Standard Institute." It is an organization that maintains the
broad range of disciplines including photographic film, computer languages, data encoding,
mechanical parts, safety and more.
32) What is the difference between getch() and getche()?
The getch() function reads a single character from the keyboard. It doesn't use any buffer, so
entered data will not be displayed on the output screen.
The getche() function reads a single character from the keyword, but data is displayed on the
output screen. Press Alt+f5 to see the entered character.
1. #include<stdio.h>
2. #include<conio.h>
3. int main()
4. {
5.
6. char ch;
7. printf("Enter a character ");
8. ch=getch(); // taking an user input without printing the value.
9. printf("\nvalue of ch is %c",ch);
10. printf("\nEnter a character again ");
11. ch=getche(); // taking an user input and then displaying it on the screen.
12. printf("\nvalue of ch is %c",ch);
13. return 0;
14. }
Output:
Enter a character
value of ch is a
Enter a character again a
value of ch is a
In the above example, the value entered through a getch() function is not displayed on the screen
while the value entered through a getche() function is displayed on the screen.
The new line escape sequence is represented by "\n". It inserts a new line on the output screen.
More details.
34) Who is the main contributor in designing the C language after Dennis Ritchie?
Brain Kernighan.
35) What is the difference between near, far and huge pointers?
A near pointer doesn't have explicit selector whereas far, and huge pointers have explicit selector.
When you perform pointer arithmetic on the far pointer, the selector is not modified, but in case of a
huge pointer, it can be modified.
These are the non-standard keywords and implementation specific. These are irrelevant in a modern
platform.
The typecasting is a process of converting one data type into another is known as typecasting. If we
want to store the floating type value to an int type, then we will convert the data type into another
data type explicitly.
Syntax
1. (type_name) expression;
38) What are the functions to open and close the file in C language?
The fopen() function is used to open file whereas fclose() is used to close file.
Yes, by holding the base address of array into a pointer, we can access the array using a pointer.
A loop running continuously for an indefinite number of times is called the infinite loop.
1. for(;;){
2. //code to be executed
3. }
1. do{
2. //code to be executed
3. }while(1);
1. #include<stdio.h>
2. void main(){
3. if(printf("hello world")){} // It prints the ?hello world? on the screen.
4. }
More details.
42) Write a program to swap two numbers without using the third variable?
1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int a=10, b=20; //declaration of variables.
6. clrscr(); //It clears the screen.
7. printf("Before swap a=%d b=%d",a,b);
8.
9. a=a+b;//a=30 (10+20)
10. b=a-b;//b=10 (30-20)
11. a=a-b;//a=20 (30-10)
12.
13. printf("\nAfter swap a=%d b=%d",a,b);
14. getch();
15. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. int n1=0,n2=1,n3,i,number;
6. clrscr();
7. printf("Enter the number of elements:");
8. scanf("%d",&number);
9. printf("\n%d %d",n1,n2);//printing 0 and 1
10.
11. for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
12. {
13. n3=n1+n2;
14. printf(" %d",n3);
15. n1=n2;
16. n2=n3;
17. }
18. getch();
19. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. void printFibonacci(int n) // function to calculate the fibonacci series of a given number.
4. {
5. static int n1=0,n2=1,n3; // declaration of static variables.
6. if(n>0){
7. n3 = n1 + n2;
8. n1 = n2;
9. n2 = n3;
10. printf("%d ",n3);
11. printFibonacci(n-1); //calling the function recursively.
12. }
13. }
14. void main(){
15. int n;
16. clrscr();
17. printf("Enter the number of elements: ");
18. scanf("%d",&n);
19. printf("Fibonacci Series: ");
20. printf("%d %d ",0,1);
21. printFibonacci(n-2);//n-2 because 2 numbers are already printed
22. getch();
23. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. int n,i,m=0,flag=0; //declaration of variables.
6. clrscr(); //It clears the screen.
7. printf("Enter the number to check prime:");
8. scanf("%d",&n);
9. m=n/2;
10. for(i=2;i<=m;i++)
11. {
12. if(n%i==0)
13. {
14. printf("Number is not prime");
15. flag=1;
16. break; //break keyword used to terminate from the loop.
17. }
18. }
19. if(flag==0)
20. printf("Number is prime");
21. getch(); //It reads a character from the keyword.
22. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int n,r,sum=0,temp;
6. clrscr();
7. printf("enter the number=");
8. scanf("%d",&n);
9. temp=n;
10. while(n>0)
11. {
12. r=n%10;
13. sum=(sum*10)+r;
14. n=n/10;
15. }
16. if(temp==sum)
17. printf("palindrome number ");
18. else
19. printf("not palindrome");
20. getch();
21. }
More details.
47) Write a program to print factorial of given number without using recursion?
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. int i,fact=1,number;
5. clrscr();
6. printf("Enter a number: ");
7. scanf("%d",&number);
8.
9. for(i=1;i<=number;i++){
10. fact=fact*i;
11. }
12. printf("Factorial of %d is: %d",number,fact);
13. getch();
14. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. long factorial(int n) // function to calculate the factorial of a given number.
4. {
5. if (n == 0)
6. return 1;
7. else
8. return(n * factorial(n-1)); //calling the function recursively.
9. }
10. void main()
11. {
12. int number; //declaration of variables.
13. long fact;
14. clrscr();
15. printf("Enter a number: ");
16. scanf("%d", &number);
17. fact = factorial(number); //calling a function.
18. printf("Factorial of %d is %ld\n", number, fact);
19. getch(); //It reads a character from the keyword.
20. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int n,r,sum=0,temp; //declaration of variables.
6. clrscr(); //It clears the screen.
7. printf("enter the number=");
8. scanf("%d",&n);
9. temp=n;
10. while(n>0)
11. {
12. r=n%10;
13. sum=sum+(r*r*r);
14. n=n/10;
15. }
16. if(temp==sum)
17. printf("armstrong number ");
18. else
19. printf("not armstrong number");
20. getch(); //It reads a character from the keyword.
21. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int n, reverse=0, rem; //declaration of variables.
6. clrscr(); // It clears the screen.
7. printf("Enter a number: ");
8. scanf("%d", &n);
9. while(n!=0)
10. {
11. rem=n%10;
12. reverse=reverse*10+rem;
13. n/=10;
14. }
15. printf("Reversed Number: %d",reverse);
16. getch(); // It reads a character from the keyword.
17. }
In this example Name of the function is Sum, the return type is the integer data type and it accepts
two integer parameters.
Q #13) What is the explanation for the cyclic nature of data types in C?
Answer: Some of the data types in C have special characteristic nature when a developer assigns
value beyond the range of the data type. There will be no compiler error and the value changes
according to a cyclic order. This is called cyclic nature. Char, int, long int data types have this
property. Further float, double and long double data types do not have this property.
Q #14) Describe the header file and its usage in C programming?
Answer: The file containing the definitions and prototypes of the functions being used in the
program are called a header file. It is also known as a library file.
Example: The header file contains commands like printf and scanf is from the stdio.h library file.
Q #15) There is a practice in coding to keep some code blocks in comment symbols than
delete it when debugging. How this affects when debugging?
Answer: This concept is called commenting out and this is the way to isolate some part of the code
which scans possible reason for the error. Also, this concept helps to save time because if the code is
not the reason for the issue it can simply be removed from comment.
Q #16) What are the general description for loop statements and available loop types in C?
Answer: A statement that allows the execution of statements or groups of statements in a repeated
way is defined as a loop.
The following diagram explains a general form of a loop.
There are 4 types of loop statements in C.
While loop
For Loop
Do…While Loop
Nested Loop
Q #17) What is a nested loop?
Answer: A loop that runs within another loop is referred to as a nested loop. The first loop is called
the Outer Loop and the inside loop is called the Inner Loop. The inner loop executes the number of
times defined in an outer loop.
Q #18) What is the general form of function in C?
Answer: The function definition in C contains four main sections.
return_type function_name( parameter list )
{
body of the function
}
Return Type: Data type of the return value of the function.
Function Name: The name of the function and it is important to have a meaningful name that
describes the activity of the function.
Parameters: The input values for the function that are used to perform the required action.
Function Body: Collection of statements that performs the required action.
Q #19) What is a pointer on a pointer in C programming language?
Answer: A pointer variable that contains the address of another pointer variable is called pointer on
a pointer. This concept de-refers twice to point to the data held by a pointer variable.
Answer:
#include <stdio.h>
int main () {
int a;
int b;
/* for loop execution */
for( a = 1; a < 6; a++ )
{
/* for loop execution */
for ( b = 1; b <= a; b++ )
{
printf("%d",b);
}
printf("\n");
}
return 0;
}
Q #26) Explain the use of function toupper() with an example code?
Answer: Toupper() function is used to convert the value to uppercase when it used with characters.
Code:
#include <stdio.h>
#include <ctype.h>
int main()
{
char c;
c = 'a';
printf("%c -> %c", c, toupper(c));
c = 'A';
printf("\n%c -> %c", c, toupper(c));
c = '9';
printf("\n%c -> %c", c, toupper(c));
return 0;
}
Result:
Q #27) What is the code in a while loop that returns the output of the given code?
#include <stdio.h>
int main () {
int a;
return 0;
}
Answer:
#include <stdio.h>
int main () {
int a;
while (a<=100)
{
printf ("%d\n", a * a);
a++;
}
return 0;
}
Q #28) Select the incorrect operator form in the following list(== , <> , >= , <=) and
what is the reason for the answer?
Answer: Incorrect operator is ‘<>'. This format is correct when writing conditional statements, but it
is not the correct operation to indicate not equal in C programming. It gives a compilation error as
follows.
Code:
#include <stdio.h>
int main () {
if ( 5 <> 10 )
printf( "test for <>" );
return 0;
}
Error:
Q #29) Is it possible to use curly brackets ({}) to enclose a single line code in C program?
Answer: Yes, it works without any error. Some programmers like to use this to organize the code.
But the main purpose of curly brackets is to group several lines of codes.
Q #30) Describe the modifier in C?
Answer: Modifier is a prefix to the basic data type which is used to indicate the modification for
storage space allocation to a variable.
Example– In a 32-bit processor, storage space for the int data type is 4.When we use it with
modifier the storage space change as follows:
Long int: Storage space is 8 bit
Short int: Storage space is 2 bit
Q #31) What are the modifiers available in C programming language?
Answer: There are 5 modifiers available in the C programming language as follows:
Short
Long
Signed
Unsigned
long long
Q #32) What is the process to generate random numbers in C programming language?
Answer: The command rand() is available to use for this purpose. The function returns an integer
number beginning from zero(0). The following sample code demonstrates the use of rand().
Code:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int a;
int b;
Output:
Q #33) Describe the newline escape sequence with a sample program?
Answer: The Newline escape sequence is represented by \n. This indicates the point that the new
line starts to the compiler and the output is created accordingly. The following sample program
demonstrates the use of the newline escape sequence.
Code:
/*
* C Program to print string
*/
#include <stdio.h>
#include <string.h>
int main(){
printf("String 01 ");
printf("String 02 ");
printf("String 03 \n");
printf("String 01 \n");
printf("String 02 \n");
return 0;
}
Output:
A list of top frequently asked C++ interview questions and answers are given below.
1) What is C++?
Initially, Stroustrup called the new language "C with classes". However, after sometime the name
was changed to C++. The idea of C++ comes from the C increment operator ++.
C++ doesn't only maintains all aspects from C language, it also simplifies memory management and
adds several features like:
o C++ is a highly portable language means that the software developed using C++ language can
run on any platform.
o C++ is an object-oriented programming language which includes the concepts such as classes,
objects, inheritance, polymorphism, abstraction.
o C++ has the concept of inheritance. Through inheritance, one can eliminate the redundant code
and can reuse the existing classes.
o Data hiding helps the programmer to build secure programs so that the program cannot be
attacked by the invaders.
C C++
C language was developed by Dennis Ritchie. C++ language was developed by Bjarne
Stroustrup.
C does not support the data hiding. Therefore, C++ supports data hiding. Therefore, the data
the data can be used by the outside world. cannot be accessed by the outside world.
C supports neither function nor operator C++ supports both function and operator
overloading. overloading.
In C, the function cannot be implemented In the C++, the function can be implemented
inside the structures. inside the structures.
Reference variables are not supported in C C++ supports the reference variables.
language.
C language does not support the virtual and C++ supports both virtual and friend functions.
friend functions.
In C, scanf() and printf() are mainly used for C++ mainly uses stream cin and cout to perform
input/output. input and output operations.
4) What is the difference between reference and pointer?
Reference Pointer
Reference behaves like an alias for an existing The pointer is a variable which stores the
variable, i.e., it is a temporary variable. address of a variable.
Reference variable does not require any indirection Pointer variable requires an indirection
operator to access the value. A reference variable operator to access the value of a variable.
can be used directly to access the value.
Once the reference variable is assigned, then it The pointer variable is an independent
cannot be reassigned with different address values. variable means that it can be reassigned
to point to different objects.
A null value cannot be assigned to the reference A null value can be assigned to the
variable. reference variable.
It is necessary to initialize the variable at the time of It is not necessary to initialize the variable
declaration. at the time of declaration.
5) What is a class?
The class is a user-defined data type. The class is declared with the keyword class. The class contains
the data members, and member functions whose access is defined by the three modifiers are private,
public and protected. The class defines the type definition of the category of things. It defines a
datatype, but it does not define the data it just specifies the structure of data.
The class is a user-defined data type which defines its properties and its functions. For example,
Human being is a class. The body parts of a human being are its properties, and the actions
performed by the body parts are known as functions. The class does not occupy any memory space.
Therefore, we can say that the class is the only logical representation of the data.
1. class student
2. {
3. //data members;
4. //Member functions
5. }
o Object:
An object is a run-time entity. An object is the instance of the class. An object can represent a
person, place or any other item. An object can operate on both data members and member
functions. The class does not occupy any memory space. When an object is created using a new
keyword, then space is allocated for the variable in a heap, and the starting address is stored in the
stack memory. When an object is created without a new keyword, then space is not allocated in the
heap memory, and the object contains the null value in the stack.
1. class Student
2. {
3. //data members;
4. //Member functions
5. }
o Inheritance:
Inheritance provides reusability. Reusability means that one can use the functionalities of the existing
class. It eliminates the redundancy of code. Inheritance is a technique of deriving a new class from
the old class. The old class is known as the base class, and the new class is known as derived class.
Syntax
o Encapsulation:
Encapsulation is a technique of wrapping the data members and member functions in a single unit. It
binds the data within a class, and no outside method can access the data. If the data member is
private, then the member function can only access the data.
o Abstraction:
Abstraction is a technique of showing only essential details without representing the implementation
details. If the members are defined with a public keyword, then the members are accessible outside
also. If the members are defined with a private keyword, then the members are not accessible by the
outside methods.
o Data binding:
Data binding is a process of binding the application UI and business logic. Any change made in the
business logic will reflect directly to the application UI.
o Polymorphism:
Polymorphism means multiple forms. Polymorphism means having more than one function with the
same name but with different functionalities. Polymorphism is of two types:
Polymorphism: Polymorphism means multiple forms. It means having more than one function with
the same function name but with different functionalities.
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void show()
7. {
8. cout<<"javaTpoint";
9. }
10. };
11. class Derived:public Base
12. {
13. public:
14. void show()
15. {
16. cout<<"javaTpoint tutorial";
17. }
18. };
19.
20. int main()
21. {
22. Base* b;
23. Derived d;
24. b=&d;
25. b->show();
26. return 0;
27. }
Output:
javaTpoint tutorial
Method overloading: Method overloading is a technique which allows you to have more than one
function with the same function name but with different functionality.
Output:
6
24
o In the above example, mul() is an overloaded function with the different number of parameters.
o The namespace is a logical division of the code which is designed to stop the naming conflict.
o The namespace defines the scope where the identifiers such as variables, class, functions are
declared.
o The main purpose of using namespace in C++ is to remove the ambiguity. Ambiquity occurs
when the different task occurs with the same name.
o For example: if there are two functions exist with the same name such as add(). In order to
prevent this ambiguity, the namespace is used. Functions are declared in different namespaces.
o C++ consists of a standard namespace, i.e., std which contains inbuilt classes and functions.
So, by using the statement "using namespace std;" includes the namespace "std" in our
program.
o Syntax of namespace:
1. namespace namespace_name
2. {
3. //body of namespace;
4. }
1. namespace_name::member_name;
1. #include <iostream>
2. using namespace std;
3. namespace addition
4. {
5. int a=5;
6. int b=5;
7. int add()
8. {
9. return(a+b);
10. }
11. }
12.
13. int main() {
14. int result;
15. result=addition::add();
16. cout<<result;
17. return 0;
18. }
Output:
10
1. Pre-increment pointer: The pre-increment operator increments the operand by 1, and the value
of the expression becomes the resulting value of the incremented. Suppose ptr is a pointer then pre-
increment pointer is represented as ++ptr.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a[5]={1,2,3,4,5};
6. int *ptr;
7. ptr=&a[0];
8. cout<<"Value of *ptr is : "<<*ptr<<"\n";
9. cout<<"Value of *++ptr : "<<*++ptr;
10. return 0;
11. }
Output:
Value of *ptr is : 1
Value of *++ptr : 2
2. Post-increment pointer: The post-increment operator increments the operand by 1, but the
value of the expression will be the value of the operand prior to the incremented value of the
operand. Suppose ptr is a pointer then post-increment pointer is represented as ptr++.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a[5]={1,2,3,4,5};
6. int *ptr;
7. ptr=&a[0];
8. cout<<"Value of *ptr is : "<<*ptr<<"\n";
9. cout<<"Value of *ptr++ : "<<*ptr++;
10. return 0;
11. }
Output:
Value of *ptr is : 1
Value of *ptr++ : 1
o Subtracting a pointer from another pointer: When two pointers pointing to the members of
an array are subtracted, then the number of elements present between the two members are
returned.
13) Which programming language's unsatisfactory performance led to the discovery of C++?
C++was discovered in order to cope with the disadvantages of C.
The Object is the instance of a class. A class provides a blueprint for objects. So you can create an
object from a class. The objects of a class are declared with the same sort of declaration that we
declare variables of basic types.
o Private: Functions and variables declared as private can be accessed only within the same
class, and they cannot be accessed outside the class they are declared.
o Public: Functions and variables declared under public can be accessed from anywhere.
o Protected: Functions and variables declared as protected cannot be accessed outside the class
except a child class. This specifier is generally used in inheritance.
OOP is a methodology or paradigm that provides many concepts. The basic concepts of Object
Oriented Programming are given below:
Classes and Objects: Classes are used to specify the structure of the data. They define the data
type. You can create any number of objects from a class. Objects are the instances of classes.
Encapsulation: Encapsulation is a mechanism which binds the data and associated operations
together and thus hides the data from the outside world. Encapsulation is also known as data hiding.
In C++, It is achieved using the access specifiers, i.e., public, private and protected.
Abstraction: Abstraction is used to hide the internal implementations and show only the necessary
details to the outer world. Data abstraction is implemented using interfaces and abstract classes in
C++.
Some people confused about Encapsulation and abstraction, but they both are different.
Inheritance: Inheritance is used to inherit the property of one class into another class. It facilitates
you to define one class in term of another class.
o Array memory allocation is static and continuous while List memory allocation is dynamic and
random.
o In Array, users don't need to keep in track of next memory allocation while In the list, the user
has to keep in track of next location where memory is allocated.
o There is no need to allocate the memory while using "new" but in malloc() you have to use
sizeof().
o "new" initializes the new memory to 0 while malloc() gives random value in the newly allotted
memory location.
o The new() operator allocates the memory and calls the constructor for the object initialization
and malloc() function allocates the memory but does not call the constructor for the object
initialization.
o The new() operator is faster than the malloc() function as operator is faster than the function.
To make an outside function friendly to the class, we need to declare the function as a
friend of the class as shown below:
1. class sample
2. {
3. // data members;
4. public:
5. friend void abc(void);
6. };
o The friend function is not in the scope of the class in which it has been declared.
o Since it is not in the scope of the class, so it cannot be called by using the object of the class.
Therefore, friend function can be invoked like a normal function.
o A friend function cannot access the private members directly, it has to use an object name and
dot operator with each member name.
o Friend function uses objects as arguments.
1. #include <iostream>
2. using namespace std;
3. class Addition
4. {
5. int a=5;
6. int b=6;
7. public:
8. friend int add(Addition a1)
9. {
10. return(a1.a+a1.b);
11. }
12. };
13. int main()
14. {
15. int result;
16. Addition a1;
17. result=add(a1);
18. cout<<result;
19. return 0;
20. }
Output:
11
o A virtual function is used to replace the implementation provided by the base class. The
replacement is always called whenever the object in question is actually of the derived class,
even if the object is accessed by a base pointer rather than a derived pointer.
o A virtual function is a member function which is present in the base class and redefined by the
derived class.
o When we use the same function name in both base and derived class, the function in base class
is declared with a keyword virtual.
o When the function is made virtual, then C++ determines at run-time which function is to be
called based on the type of the object pointed by the base class pointer. Thus, by making the
base class pointer to point different objects, we can execute different versions of the virtual
functions.
o C++ does not contain virtual constructors but can have a virtual destructor.
1. Never
2. Rarely
3. If you find that the problem domain cannot be accurately modeled any other way.
A Destructor is used to delete any extra resources allocated by the object. A destructor function is
called automatically once the object goes out of the scope.
Rules of destructor:
o Destructors have the same name as class name and it is preceded by tilde.
It is a type of arithmetical error. It happens when the result of an arithmetical operation been greater
than the actual space provided by the system.
o When a single object behaves in many ways is known as overloading. A single object has the
same name, but it provides different versions of the same function.
o C++ facilitates you to specify more than one definition for a function name or an operator in the
same scope. It is called function overloading and operator overloading respectively.
o Member function
o Non-member function
o Friend function
If you inherit a class into a derived class and provide a definition for one of the base class's function
again inside the derived class, then this function is called overridden function, and this mechanism is
known as function overriding.
Virtual inheritance facilitates you to create only one copy of each object even if the object appears
more than one in the hierarchy.
A Constructor is a special method that initializes an object. Its name must be same as class name.
31) What is the purpose of the "delete" operator?
The "delete" operator is used to release the dynamic memory created by "new" operator.
A scope resolution operator(::) is used to define the member function outside the class.
Delete [] is used to release the array of allocated memory which was allocated using new[] whereas
delete is used to release one chunk of memory which was allocated using new.
35) What is a pure virtual function?
The pure virtual function is a virtual function which does not contain any definition. The normal
function is preceded with a keyword virtual. The pure virtual function ends with 0.
1. #include<iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void show()=0;
7. };
8.
9. class Derived:public Base
10. {
11. public:
12. void show()
13. {
14. cout<<"javaTpoint";
15. }
16. };
17. int main()
18. {
19. Base* b;
20. Derived d;
21. b=&d;
22. b->show();
23. return 0;
24. }
Output:
javaTpoint
Structures class
A structure is a user-defined data type which The class is a user-defined data type which
contains variables of dissimilar data types. contains member variables and member
functions.
The variables of a structure are stored in the The variables of a class are stored in the heap
stack memory. memory.
We cannot initialize the variables directly. We can initialize the member variables
directly.
If access specifier is not specified, then by If access specifier is not specified, then by
default the access specifier of the variable is default the access specifier of a variable is
"public". "private".
A structure is declared by using a struct The class is declared by using a class keyword.
keyword.
The structure does not support the inheritance. The class supports the concept of inheritance.
The type of a structure is a value type. The type of a class is a reference type.
A class template is used to create a family of classes and functions. For example, we can create a
template of an array class which will enable us to create an array of various types such as int, float,
char, etc. Similarly, we can create a template for a function, suppose we have a function add(), then
we can create multiple versions of add().
1. template<class T>
2. class classname
3. {
4. // body of class;
5. };
1. classname<type> objectname(arglist);
38) What is the difference between function overloading and operator overloading?
Function overloading: Function overloading is defined as we can have more than one version of
the same function. The versions of a function will have different signature means that they have a
different set of parameters.
Operator overloading: Operator overloading is defined as the standard operator can be redefined
so that it has a different meaning when applied to the instances of a class.
A virtual destructor in C++ is used in the base class so that the derived class object can also be
destroyed. A virtual destructor is declared by using the ~ tilde operator and then virtual keyword
before the constructor.
Note: Constructor cannot be virtual, but destructor can be virtual.
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. Base()
7. {
8. cout<<"Base constructor is called"<<"\n";
9. }
10. ~Base()
11. {
12. cout<<"Base class object is destroyed"<<"\n";
13. }
14. };
15. class Derived:public Base
16. {
17. public:
18. Derived()
19. {
20. cout<<"Derived class constructor is called"<<"\n";
21. }
22. ~Derived()
23. {
24. cout<<"Derived class object is destroyed"<<"\n";
25. }
26. };
27. int main()
28. {
29. Base* b= new Derived;
30. delete b;
31. return 0;
32.
33. }
Output:
In the above example, delete b will only call the base class destructor due to which derived class
destructor remains undestroyed. This leads to the memory leak.
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. Base()
7. {
8. cout<<"Base constructor is called"<<"\n";
9. }
10. virtual ~Base()
11. {
12. cout<<"Base class object is destroyed"<<"\n";
13. }
14. };
15. class Derived:public Base
16. {
17. public:
18. Derived()
19. {
20. cout<<"Derived class constructor is called"<<"\n";
21. }
22. ~Derived()
23. {
24. cout<<"Derived class object is destroyed"<<"\n";
25. }
26. };
27. int main()
28. {
29. Base* b= new Derived;
30. delete b;
31. return 0;
32.
33. }
Output:
When we use the virtual destructor, then the derived class destructor is called first, and then the
base class destructor is called.
Questions and Answers
Object Oriented Programming& Methodology
Q1. What is oops?
Ans: OOPS is abbreviated as Object Oriented Programming system in which programs are considered
as a collection of objects. Each object is nothing but an instance of a class.
Q2.Write Basic Concepts Of Oops?
Ans: Following are the concepts of OOPS and are as follows:
1-Abstraction.
2-Encapsulation.
3-Inheritance.
4-Polymorphism.
Q3.what is a class?
Ans: A class is simply a representation of a type of object. It is the blueprint/ plan/ template that
describe the details of an object.
Q4.what is an object?
Ans: Object is termed as an instance of a class, and it has its own state, behavior and identity.
Q5.what is encapsulation?
Ans: Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden
data can be restricted to the members of that class.Levels are Public, Protected, Private, Internal and
Protected Internal.
Q6.what is polymorphism?
Ans: Polymorphism is nothing but assigning behavior or value in a subclass to something that was
already declared in the main class. Simply, polymorphism takes more than one form.
Q7.what is inheritance?
Ans: Inheritance is a concept where one class shares the structure and behavior defined in another
class. If inheritance applied on one class is called Single Inheritance, and if it depends on multiple
classes, then it is called multiple inheritances.
Q 8.What are manipulators?
Ans: Manipulators are the functions which can be used in conjunction with the insertion (<<) and
extraction (>>) operators on an object. Examples are endl and setw.
Q9. Define a constructor?
Ans: Constructor is a method used to initialize the state of an object, and it gets invoked at the time
of object creation. Rules for constructor are:.
1-Constructor Name should be same as class name.
2-Constructor must have no return type.
Q10. Define destructor?
Ans: Destructor is a method which is automatically called when the object is made of scope or
destroyed. Destructor name is also same as class name but with the tilde symbol before the name.
Q11. What is inline function?
Ans: Inline function is a technique used by the compilers and instructs to insert complete body of the
function wherever that function is used in the program source code.
Q12. What is a virtual function?
Ans: Virtual function is a member function of class and its functionality can be overridden in its derived
class. This function can be implemented by using a keyword called virtual, and it can be given during
function declaration. Virtual function can be achieved in C++, and it can be achieved in C Language by
using function pointers or pointers to function.
Q13. What is friend function?
Ans: Friend function is a friend of a class that is allowed to access to Public, private or protected data
in that same class. If the function is defined outside the class cannot access such information. Friend
can be declared anywhere in the class declaration, and it cannot be affected by access control keywords
like private, public or protected.
Q14. What is function overloading?
Ans: Function overloading is defined as a normal function, but it has the ability to perform different
tasks. It allows creation of several methods with the same name which differ from each other by type
of input and output of the function.
Example:
1-Void add (int& a, int& b);
2-Void add (double& a, double& b);
3-Void add (struct bob& a, struct bob& b);
Q15. What Is Operator Overloading?
Ans: Operator overloading is a function where different operators are applied and depends on the
arguments. Operator,-,* can be used to pass through the function, and it has their own precedence to
execute.
Example:
Class complex {
Double real,
Imag; public: complex (double r, double i) : real(r),
Imag (i) {} complex operator+ (complex a, complex b);
Complex operator*(complex a, complex b);
Complex& operator=(complex a, complex b);
}
A=1.2, b=6
Q16. What Is An Abstract Class?
Ans: An abstract class is a class which cannot be instantiated. Creation of an object is not possible
with abstract class, but it can be inherited. An abstract class can contain only abstract method. Java
allows only abstract method in abstract class while for other language it allows non-abstract method
as well.
Q17. What is a ternary operator?
Ans: Ternary operator is said to be an operator which takes three arguments. Arguments and results
are of different data types , and it is depends on the function. Ternary operator is also called as
conditional operator.
Q18. What Is the use of Finalize Method?
Ans: Finalize method helps to perform cleanup operations on the resources which are not currently
used. Finalize method is protected, and it is accessible only through this class or by a derived class.
Q19. What Are Different Types Of Arguments?
Ans: A parameter is a variable used during the declaration of the function or subroutine and arguments
are passed to the function, and it should match with the parameter defined. There are two types of
Arguments.
1-Call by Value –Value passed will get modified only inside the function, and it returns the same value
whatever it is passed it into the function.
2-Call by Reference –Value passed will get modified in both inside and outside the functions and it
returns the same or different value.
Q20. What Is Super Keyword?
Ans: Super keyword is used to invoke overridden method which overrides one of its superclass
methods. This keyword allows to access overridden methods and also to access hidden members of
the superclass. It also forwards a call from a constructor to a constructor in the superclass.
Q21. What Is Method Overriding?
Ans: Method overriding is a feature that allows sub class to provide implementation of a method that
is already defined in the main class. This will overrides the implementation in the superclass by
providing the same method name, same parameter and same return type.
Q22. What Is An Interface?
Ans: An interface is a collection of abstract method. If the class implements an inheritance, and then
thereby inherits all the abstract methods of an interface.
Q23. What Is Exception Handling?
Ans: Exception is an event that occurs during the execution of a program. Exceptions can be of any
type – Run time exception, Error exceptions. Those exceptions are handled properly through exception
handling mechanism like try, catch and throw keywords.
Q24. What Are Tokens?
Ans: Token is recognized by a compiler and it cannot be broken down into component elements.
Keywords, identifiers, constants, string literals and operators are examples of tokens. Even punctuation
characters are also considered as tokens – Brackets, Commas, Braces and Parentheses.
Q25. Difference between overloading and overriding?
Ans: Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but
the same method with different arguments, and it may or may not return the same value in the same
class itself. Overriding is the same method names with same arguments and returns types associates
with the class and its child class.
Q26. Difference between class and an object?
Ans: An object is an instance of a class. Objects hold any information, but classes don’t have any
information. Definition of properties and functions can be done at class and can be used by the object.
Class can have sub-classes, and an object doesn’t have sub-objects.
Q27. What is an abstraction?
Ans: Abstraction is a good feature of OOPS, and it shows only the necessary details to the client of an
object. Means, it shows only necessary details for an object, not the inner details of an object. Example
– When you want to switch on television, it not necessary to show all the functions of TV. Whatever is
required to switch on TV will be showed by using abstract class.
Q28. What Are Access Modifiers?
Ans: Access modifiers determine the scope of the method or variables that can be accessed from other
various objects or classes. There are 5 types of access modifiers, and they are as follows:.
1-Private.
2-Protected.
3-Public.
4-Friend.
5-Protected Friend.
Q29. What is sealed modifiers?
Ans: Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed
modifiers can also be applied to properties, events and methods. This modifier cannot be applied to
static members.
Q30. How can we call the base method without creating an instance?
Ans: Yes, it is possible to call the base method without creating an instance. And that method should
be,. Static method. Doing inheritance from that class.-Use Base Keyword from derived class.
Q31. What is the difference between new and override?
Answer: The new modifier instructs the compiler to use the new implementation instead of the base
class function. Whereas, Override modifier helps to override the base class function.
Q32. What are the various types of constructors?
Ans: There are three various types of constructors, and they are as follows:
1-Default Constructor – With no parameters.
2-Parametric Constructor – With Parameters. Create a new instance of a class and also passing
arguments simultaneously.
3-Copy Constructor – Which creates a new object as a copy of an existing object.
Q 33. What is early and late binding?
Answer: Early binding refers to assignment of values to variables during design time whereas late
binding refers to assignment of values to variables during run time.
Q34. What is ‘this’ pointer?
Ans: THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which
differentiates between the current object with the global object. Basically, it refers to the current object.
Q35. What is the difference between structure and a class?
Ans: Structure default access type is public, but class access type is private. A structure is used for
grouping data whereas class can be used for grouping data and methods. Structures are exclusively
used for data and it doesn’t require strict validation, but classes are used to encapsulates and inherit
data which requires strict validation.
Q36. What is the default access modifier in a class?
Ans: The default access modifier of a class is Private by default.
Q37. What is pure virtual function?
Ans: A pure virtual function is a function which can be overridden in the derived class but cannot be
defined. A virtual function can be declared as Pure by using the operator =0.
Example:
Virtual void function1 () // Virtual, Not pure
Virtual void function2 () = 0 //Pure virtual
Q38. What are all the operators that cannot be overloaded?
Ans: Following are the operators that cannot be overloaded -.
1-Scope Resolution (:: )
2-Member Selection (.)
3-Member selection through a pointer to function (.*)
Q 39. What is dynamic or run time polymorphism?
Ans: Dynamic or Run time polymorphism is also known as method overriding in which call to an
overridden function is resolved during run time, not at the compile time. It means having two or more
methods with the same name, same signature but with different implementation.
Q40. Do we require parameter for constructors?
Ans: No, we do not require parameter for constructors.
Q 41. What is a copy constructor?
Ans: This is a special constructor for creating a new object as a copy of an existing object. There will
be always only on copy constructor that can be either defined by the user or the system.
Q 42. What does the keyword virtual represented in the method definition?
Ans: It means, we can override the method.
Q43. What are base class, sub class and super class?
Ans: Base class is the most generalized class, and it is said to be a root class. Sub class is a class that
inherits from one or more base classes. Super class is the parent class from which another class
inherits.
Q 44. What is static and dynamic binding?
Ans: Binding is nothing but the association of a name with the class. Static binding is a binding in
which name can be associated with the class during compilation time , and it is also called as early
Binding. Dynamic binding is a binding in which name can be associated with the class during execution
time , and it is also called as Late Binding.
Q45. How many instances can be created for an abstract class?
Ans: Zero instances will be created for an abstract class.
Q46. Which keyword can be used for overloading?
Ans: Operator keyword is used for overloading.
Q 47. What is the default access specifier in a class definition?
Ans: Private access specifier is used in a class definition.
Q48. Which oops concept is used as reuse mechanism?
Ans: Inheritance is the OOPS concept that can be used as reuse mechanism.
Q 49. Which oops concept exposes only necessary information to the calling functions?
Ans: Data Hiding / Abstraction
Q 50. What are the types of constructors?
Ans: Basically constructors are 5 types those are
1-Default Constructor
2-Parameterized Constructor
3-Copy Constructor
4-Static Constructor
5-Private Constructor
Q51.What is OOPS?
Ans: Object Oriented Programming System is the programming technique to write programs based on
the real world objects. The states and behaviours of an object are represented as the member variables
and methods. In OOPS programming programs are organized around objects and data rather than
actions and logic.
Q52.What are the advantages of OOPS concepts
Ans: Major advantages of OOPS programming are;
1. Simplicity: OOPS programming objects model real world objects, so the complexity is reduced and
the program structure is clear.
2-Modularity: Each object forms a separate entity whose internal workings are decoupled from other
parts of the system.
3-Modifiability: It is easy to make minor changes in the data representation or the procedures in an
OO program. Changes inside a class do not affect any other part of a program, since the only public
interface that the external world has to a class is through the use of methods.
4-Extensibility: Adding new features or responding to changing operating environments can be solved
by introducing a few new objects and modifying some existing ones.
5-Maintainability: Objects can be maintained separately, making locating and fixing problems easier.
6-Reusability: Objects can be reused in different programs.
Q53.What is the difference between Procedural programming and OOPS?
Ans: 1-Procedural language is based on functions but object oriented language is based on real world
objects.
2-Procedural language gives importance on the sequence of function execution but object oriented
language gives importance on states and behaviours of the objects.
3-Procedural language exposes the data to the entire program but object oriented language
encapsulates the data.
4-Procedural language follows top down programming paradigm but object oriented language follows
bottom up programming paradigm.
5-Procedural language is complex in nature so it is difficult to modify, extend and maintain but object
oriented language is less complex in nature so it is easier to modify, extend and maintain.
6-Procedural language provides less scope of code reuse but object oriented language provides more
scope of code reuse.
Q54.What are the core concepts of OOPS?
Ans: OOPS core concepts are;
1-Abstraction
2-Encapsulation
3-Polymorphism
4-Inheritance
5-Composition
6-Association
7-Aggregation
Q55.What is Abstraction?
Ans: Abstraction is an OOPS concept to construct the structure of the real world objects. During this
construction only the general states and behaviours are taken and more specific states and behaviours
are left aside for the implementers.
Q56.What is Encapsulation?
Ans: Encapsulation is an OOPS concept to create and define the permissions and restrictions of an
object and its member variables and methods. A very simple example to explain the concept is to make
the member variables of a class private and providing public getter and setter methods. Java provides
four types of access level modifiers: public, protected, no modifier and private.
Q57.What is the difference between Abstraction and Encapsulation?
Ans:1-“Program to interfaces, not implementations” is the principle for Abstraction and “Encapsulate
what varies” is the OO principle for Encapsulation.
2-Abstraction provides a general structure of a class and leaves the details for the implementers.
Encapsulation is to create and define the permissions and restrictions of an object and its member
variables and methods.
3-Abstraction is implemented in Java using interface and abstract class while Encapsulation is
implemented using four types of access level modifiers: public, protected, no modifier and private.
Q58.What is Polymorphism?
Ans: Polymorphism is the occurrence of something in various forms. Java supports various forms of
polymorphism like polymorphic reference variables, polymorphic method, polymorphic return types
and polymorphic argument types.
Q59.What is Inheritance?
Ans: A subclass can inherit the states and behaviours of it’s super class is known as inheritance.
Q60.What is multiple inheritance?
Ans: A child class inheriting states and behaviours from multiple parent classes is known as multiple
inheritance.
Q61.What is the diamond problem in inheritance?
Ans: In case of multiple inheritance, suppose class A has two subclasses B and C, and a class D has
two super classes B and C. If a method present in A is overridden by both B and C but not by D then
from which class D will inherit that method B or C? This problem is known as diamond problem.
Q62.Why Java does not support multiple inheritance?
Ans: Java was designed to be a simple language and multiple inheritance introduces complexities like
diamond problem. Inheriting states or behaviours from two different type of classes is a case which in
reality very rare and it can be achieved easily through an object association.
Q63.What is Static Binding and Dynamic Binding?
Ans:1-Static or early binding is resolved at compile time. Method overloading is an example of static
binding.
2-Dynamic or late or virtual binding is resolved at run time. Method overriding is an example of dynamic
binding.
Q64.What is the meaning of “IS-A” and “HAS-A” relationship?
Ans: “IS-A” relationship implies inheritance. A sub class object is said to have “IS-A” relationship with
the super class or interface. If class A extends B then A “IS-A” B. It is transitive, that is, if class A
extends B and class B extends C then A “IS-A” C. The “instance of” operator in java determines the
“IS-A” relationship.
When a class A has a member reference variable of type B then A “HAS-A” B. It is also known as
Aggregation.
Q65.What is Association?
Ans: Association is a relationship between two objects with multiplicity.
Q66.What is Aggregation?
Ans: Aggregation is also known as “HAS-A” relationship. When class Car has a member reference
variable of type Wheel then the relationship between the classes Car and Wheel is known as
Aggregation. Aggregation can be understood as “whole to its parts” relationship.
Car is the whole and Wheel is part. Wheel can exist without the Car. Aggregation is a weak association.
Q67.What is Composition?
Ans: Composition is a special form of Aggregation where the part cannot exist without the whole.
Composition is a strong Association. Composition relationship is represented like aggregation with one
difference that the diamond shape is filled.
Q68.What is Dependency?
Ans: When one class depends on another because it uses that at some point in time then this
relationship is known as Dependency. One class depends on another if the independent class is a
parameter variable or local variable of a method of the dependent class. A Dependency is drawn as a
dotted line from the dependent class to the independent class with an open arrowhead pointing to the
independent class.
Q69.What is the difference between Association and Dependency?
Ans: The main difference between Association and Dependency is in case of Association one class has
an attribute or member variable of the other class type but in case of Dependency a method takes an
argument of the other class type or a method has a local variable of the other class type.
Q70.What is a Class?
Ans: A class is the specification or template of an object.
1-What is an Object?
2-Object is instance of class.
Q71.Define abstraction in software in general.
Ans: In computing, abstraction means separating concepts from details through a hierarchy of layers.
Examples:
1-Abit as an abstraction of a hardware electrical signal
2-Avariable name is an abstraction of a memory location
3-Adata type is an abstraction of a memory representation scheme by a compiler
4-Afunction call is an abstraction to the actual detailed code implemented in the body of the function
Q72.Define data abstraction.
Ans: 1-Creating a structure that defines a complex data type and legal operations on it. The design
makes the interface of the data and operations accessible but hides the actual implementation of them.
2-Example: a List class can choose to implement the container of the data elements as an array or as
a linked list. This container is kept hidden from the user interface but public interface is provided to
element read/write operations.
Q73.Define process abstraction.
Ans: 1-Separating the process (method, procedure, function, subroutine or subprogram)
signature/prototype from the detailed actual definition and implementation, so that the user is not
concerned with how the process is implemented but rather how to use it.
2-Example: a method is defined to sort a list of elements and can be implemented using insertion sort
or selection sort and the only thing the user has to worry about is how to call it.
Q74.What is encapsulation?
Ans: 1-It is a mechanism to package the data and its operations inside one structure
2-It is a data protection mechanism to dictate the way data is accessed (read/write)
Q75.What is information hiding?
Ans: The internal representation and implementation of an object is hidden from users. This concept
encompasses: data abstraction, process abstraction and encapsulation.
Q76. Define polymorphism.
Ans: 1-A mechanism that works in hierarchical inheritance where a certain behavior when invoked can
have different forms based on the called function of the derived class.
2-Example: a base class Animal defines “move” and “makeSound “ functions ;a derived class Dog
redefines the two functions to walk and bark respectively using the same function names in the base
class, where as a Bird class redefines the two functions to fly and chirp.
3-Polymorphism requires that functions in base class to be defined as “Virtual” so derived classes can
redefine them.
4-Virtual functions are bound dynamically at run-time whereas other functions are statically bound at
compile time.
Q77. What are accessors?
Ans: 1-They are the functions in the public interface that provide accessibility to the private data
members for “read” operations.
2-Example: see the getX, getY functions in the Point class.
Q78. What are mutators?
Ans: 1-They are the functions in the public interface that provide accessibility to the private data
members for “write” operations.
2-Example: see the setX, setY functions in the Point class.
Q79.How to do inline functions work?
Ans: 1-In inline functions, there is no function calls, the compiler replace every instance of their calls
in the code with the body of the function saving the overhead associated with the function call
mechanism.
2-“inline” keyword can be used to specify a function as an inline.
Q80. What is public interface?
Ans: 1-Is a set of public functions defined in the “public:” section in the class body. This section
provides the data accessibility of read/write operations as well as other service functions.
2-Example: see the “public” section in Point class. We can add another service function that prints the
data members x and y to the stdout as follows:
void print()
{ cout << “ X-coordinate = “ << x << endl << Y-coordinate = “ << y << endl; }
Q81.What are private functions?
Ans: 1-They are functions defined in the “private” section of the class body where they are only visible
to the class itself; They are used when the class needs to some internal functions that the user do not
need to know about and they are typically helper functions that help other public functions.
2-Example: suppose that in the Point3D function we need a function that will generate a random id#
for the current object and we want to hide this function from the user so whenever a random ID is
needed other functions in the class can automatically call this
function:
void Point3D::randID(){
id = 1000 + rand() % (9000);
}
Q82.Define access modifiers.
Ans: 1-Private: the section in the class that is only visible to the class itself.
2-Protected: the section in the class that is visible to the class and to its derived classes.
3-Public: the section in the class that is visible to all: class, derived classes and outer world.
Q83. Define state, data member, attribute, property.
Ans: 1-They all refer to one thing, that is, the data fields that provide data specification for the class.
2-Example: see the data members defined in the “protected:” section below.
class Point
{
private:
protected:
double x;
double y;
int id;
double size;
void randID();
Public:
};
Q84. Define function, method & behavior.
Ans: They all refer to the same thing, the means of modelling how the object can operate and behave.
While data members model states and attributes, functions model actions, operations and behaviors.
Q85. What is class specification?
Ans: The entire class body where every data member declarations, function members prototypes,
constructors, accessors mutator prototypes and other elements of class declaration; all of these are
typically kept in a header file “.h” apart from the implementation file of the class “.cpp”.
Q86. What is class implementation?
Ans: It is typically kept in a separate file apart from class specification. In the implementation file, all
functions declared in the class specification section/file are defined including the constructors,
destructor, accessors, mutators and other service functions.
Q87. Write the simplest class possible that does nothing.class.
Ans: MyClass { };
Q88. What is an instance of a class?
Ans: 1-It is an object instantiated from a class. An instance of a class is created at runtime using one
the available constructors. By setting its states/attributes/data members it becomes a specific
instant/object of the class.
Q89. Define instantiation.
Ans: To create a new instance (object) of a class. Only when you instantiate an object, then you can
use it and communicate with it.
Q90. What is a message?
Ans: Objects interact with each other using messaging which is simply calling each other’s functions
and receiving/causing the desired response.
Q91. Explain memory leakage.
Ans:1-Occurs when the programmer repeatedly allocates dynamic memory and does not release it
when it is no longer needed, this will eventually exhaust all memory resources and cause a fatal error
that will crash the program.
2-Example: in version one the function keeps allocating memory for about 10GB, if the system has
that space available, it would work but with a lot of wasted space.
Version-2 correctly and safely releases the allocated memory after it has finished using it and will use
100MB at any given time.
Q92. What is exception handling?
Ans:1-Is a construct and a mechanism that manages the occurrence of errors/abnormalities at run
time. Exception handling is designed to separate the error handling code from the original code to
gracefully handle the fault situation by transferring the program control to the exception handling code.
Many aspects of software development process can be improved such as: safety, readability,
writeability, maintainability, etc.
2-Examples of exceptions: Divide by zero, sqrt of a negative, un initialized variable, exceeding array
limits, dereferencing a dangling pointer, etc.
Q93. What is class extension?
Ans: It means inheritance; where a derived class inherits all of the base class content and extends the
data member or/and the function members. In OOP inheritance implies extension where, there is no
point of just inheriting the same content of the base class and not adding any data or function members,
if that is the case then, the base class by itself could be used directly and no need for inheritance.
Q94. How to resolve conflicts in naming between multiple parent classes if they are called
from a child?
Ans:1-Derived class redefines the multiply-defined function in parents or,
2-Derived class invokes member function in a particular base class using scope resolution operator ::
3-Compiler errors occur if derived class uses base class function without one of above solutions.
Q95. What is code reuse?
It is a mechanism in OOP that facilitates the utilization of previously created code; its main advantages
include: time saving, better resource utilization and reducing redundancy. One good example of code
reuse is inheritance.
Q96. Compare function overloading vs. overriding vs. Redefinition.
Ans:1-Overloading: defining multiple function using the same function name but with different
parameter list ether in type or number. In classes, the overloaded constructor is an example where
you can have many constructors with different parameter list signatures.
2-Redefinition: if a base class non-virtual function is redefined in a derived class, it is called redefined
and it is statically bound.
3-Overriding: Redefinition: if a base class virtual function is redefined in a derived class, it is called
overridden and it is dynamically bound.
Q97.What do you mean by ‘void’ return type?
Ans: All functions should return a value as per the general syntax. However, in case, if we don't want
a function to return any value, we use “void” to indicate that. This means that we use “void” to indicate
that the function has no return value or it returns “void”.
Q98-Why are arrays usually processed with for loop?
Ans: Array uses the index to traverse each of its elements. If A is an array then each of its element is
accessed as A[i]. Programmatically, all that is required for this to work is an iterative block with a loop
variable i that serves as an index (counter) incrementing from 0 to A.length-1.
This is exactly what a loop does and this is the reason why we process arrays using for loops.
Q99- State the difference between delete and delete[].
Ans: “delete[]” is used to release the memory allocated to an array which was allocated using new[].
“delete” is used to release one chunk of memory which was allocated using new.
1) What is Java?
Java is the high-level, object-oriented, robust, secure programming language, platform-independent,
high performance, Multithreaded, and portable programming language. It was developed by James
Gosling in June 1991. It can also be known as the platform as it provides its own JRE and API.
The differences between C++ and Java are given in the following table.
Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.
Design Goal C++ was designed for systems Java was designed and created as an
and applications programming. interpreter for printing systems but
It was an extension of C later extended as a support network
programming language. computing. It was designed with a goal
of being easy to use and accessible to a
broader audience.
Pointers C++ supports pointers. You can Java supports pointer internally.
write pointer program in C++. However, you can't write the pointer
program in java. It means java has
restricted pointer support in Java.
Compiler and C++ uses compiler only. C++ is Java uses compiler and interpreter
Interpreter compiled and run using the both. Java source code is converted into
compiler which converts source bytecode at compilation time. The
code into machine code so, C++ interpreter executes this bytecode at
is platform dependent. runtime and produces output. Java is
interpreted that is why it is platform
independent.
Call by Value and C++ supports both call by value Java supports call by value only. There
Call by reference and call by reference. is no call by reference in java.
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies on
third-party libraries for thread
support.
Documentation C++ doesn't support Java supports documentation comment
comment documentation comment. (/** ... */) to create documentation for
java source code.
Virtual Keyword C++ supports virtual keyword so Java has no virtual keyword. We can
that we can decide whether or override all non-static methods by
not override a function. default. In other words, non-static
methods are virtual by default.
unsigned right C++ doesn't support >>> Java supports unsigned right shift >>>
shift >>> operator. operator that fills zero at the top for the
negative numbers. For positive
numbers, it works same like >>
operator.
Inheritance Tree C++ creates a new inheritance Java uses a single inheritance tree
tree always. always because all classes are the child
of Object class in java. The object class
is the root of the inheritance tree in
java.
Hardware C++ is nearer to hardware. Java is not so interactive with
hardware.
o Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write
the program in it.
o Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our
code as the combination of different type of objects that incorporates both data and behavior.
o Portable: Java supports read-once-write-anywhere approach. We can execute the Java
program on every machine. Java program (.java) is converted to bytecode (.class) which can be
easily run on every machine.
o Secured: Java is secured because it doesn't use explicit pointers. Java also provides the
concept of ByteCode and Exception handling which makes it more secured.
o Robust: Java is a strong programming language as it uses strong memory management. The
concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
o Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture.
In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which
doesn't exist in Java.
o Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the
program execution.
o High Performance: Java is faster than other traditional interpreted programming languages
because Java bytecode is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++).
o Multithreaded: We can write Java programs that deal with many tasks at once by defining
multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for
each thread. It shares a common memory area. Threads are important for multi-media, Web
applications, etc.
o Distributed: Java is distributed because it facilitates users to create distributed applications in
Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us
able to access files by calling the methods from any machine on the internet.
o Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM
acts like a run-time engine which calls the main method present in the Java code. JVM is the
specification which must be implemented in the computer system. The Java code is compiled by JVM
to be a Bytecode which is machine independent and close to the native code.
JVM
JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime
environment in which Java bytecode can be executed. It is a specification which specifies the working
of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its
implementation is known as JRE.
JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a
runtime instance which is created when we run the Java class. There are three notions of the JVM:
specification, implementation, and instance.
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to
provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a
set of libraries + other files that JVM uses at runtime.
JDK
JDK is an acronym for Java Development Kit. It is a software development environment which is used
to develop Java applications and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
More Details.
Many types:
1. Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool,
field, method data, and the code for methods.
2. Heap: It is the runtime data area in which the memory is allocated to the objects
3. Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return. Each thread has a private JVM stack, created at the same time as
the thread. A new frame is created each time a method is invoked. A frame is destroyed when
its method invocation completes.
4. Program Counter Register: PC (program counter) register contains the address of the Java
virtual machine instruction currently being executed.
5. Native Method Stack: It contains all the native methods used in the application.
More Details.
7) What is JIT compiler?
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the
bytecode that have similar functionality at the same time, and hence reduces the amount of time
needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a
Java virtual machine (JVM) to the instruction set of a specific CPU.
A platform is the hardware or software environment in which a piece of software is executed. There
are two types of platforms, software-based and hardware-based. Java provides the software-based
platform.
9) What are the main differences between the Java platform and other platforms?
There are the following differences between the Java platform and other platforms.
o Java is the software-based platform whereas other platforms may be the hardware platforms or
software-based platforms.
o Java is executed on the top of other hardware platforms whereas other platforms can only have
the hardware components.
10) What gives Java its 'write once and run anywhere' nature?
The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the
intermediate language between source code and machine code. This bytecode is not platform specific
and can be executed on any computer.
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the classloader. There are three built-in classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the superclass of Extension
classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like
java.lang package classes, java.net package classes, java.util package classes, java.io package
classes, java.sql package classes, etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of
System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It
loads the class files from the classpath. By default, the classpath is set to the current directory.
You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application
classloader.
Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run
by java classname Let's take a simple example:
run it by java A
13) Is delete, next, main, exit or null keyword in java?
No.
14) If I don't provide any arguments on the command line, then what will the value stored in the
String array passed into the main() method, empty or NULL?
15) What if I write static public void instead of public static void?
The program compiles and runs correctly because the order of specifiers doesn't matter in Java.
The local variables are not initialized to any default value, neither primitives nor object references.
17) What are the various access specifiers in Java?
In Java, access specifiers are the keywords which are used to define the access scope of the method,
class, or a variable. In Java, there are four access specifiers given below.
o Public The classes, methods, or variables which are defined as public, can be accessed by any
class or method.
o Protected Protected can be accessed by the class of the same package, or by the sub-class of
this class, or within the same class.
o Default Default are accessible within the package only. By default, all the classes, methods,
and variables are of default scope.
o Private The private class, methods, or variables defined as private can be accessed within the
class only.
The methods or variables defined as static are shared among all the objects of the class. The static is
the part of the class and not of the object. The static variables are stored in the class area, and we
do not need to create the object to access such variables. Therefore, static is used in the case, where
we need to define variables or methods which are common to all the objects of the class.
For example, In the class simulating the collection of the students in a college, the name of the
college is the common attribute to all the students. Therefore, the college name will be defined
as static.
o We can also have the hidden classes that are not visible outside and used by the package.
1. class Test
2. {
3. public static void main (String args[])
4. {
5. System.out.println(10 + 20 + "Javatpoint");
6. System.out.println("Javatpoint" + 10 + 20);
7. }
8. }
30Javatpoint
Javatpoint1020
Explanation
In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated
as the string and concatenated with the string Javatpoint. Therefore, the output will
be 30Javatpoint.
1. class Test
2. {
3. public static void main (String args[])
4. {
5. System.out.println(10 * 20 + "Javatpoint");
6. System.out.println("Javatpoint" + 10 * 20);
7. }
8. }
200Javatpoint
Javatpoint200
Explanation
In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as
the string and concatenated with the string Javatpoint to produce the output 200Javatpoint.
In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence
of the multiplication is higher than addition. The result 200 will be treated as the string and
concatenated with the string Javatpointto produce the output as Javatpoint200.
The above code will give the compile-time error because the for loop demands a boolean value in the
second part and we are providing an integer value, i.e., 0.
There is given more than 50 OOPs (Object-Oriented Programming and System) interview questions.
However, they have been categorized in many sections such as constructor interview questions,
static interview questions, Inheritance Interview questions, Abstraction interview question,
Polymorphism interview questions, etc. for better understanding.
23) What is object-oriented paradigm?
It is a programming paradigm based on objects having data and methods defined in the class to
which it belongs. Object-oriented paradigm aims to incorporate the advantages of modularity and
reusability. Objects are the instances of classes which interacts with one another to design
applications and programs. There are the following features of the object-oriented paradigm.
o Includes the concept like Encapsulation and abstraction which hides the complexities from the
user and show only functionality.
o The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.
The Object is the real-time entity having some state and behavior. In Java, Object is an instance of
the class having the instance variables as the state of the object and the methods as the behavior of
the object. The object of a class can be created by using the new keyword.
25) What is the difference between an object-oriented programming language and object-based
programming language?
There are the following basic differences between the object-oriented language and object-based
language.
o Object-oriented languages follow all the concepts of OOPs whereas, the object-based language
doesn't follow all the concepts of OOPs like inheritance and polymorphism.
o Object-oriented languages do not have the inbuilt objects whereas Object-based languages
have the inbuilt objects, for example, JavaScript has window object.
o Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the examples
of object-based languages are JavaScript, VBScript, etc.
26) What will be the initial value of an object reference which is defined as an instance variable?
The constructor can be defined as the special type of method that is used to initialize the state of an
object. It is invoked when the class is instantiated, and the memory is allocated for the object. Every
time, an object is created using the new keyword, the default constructor of the class is called. The
name of the constructor must be similar to the class name. The constructor must not have an explicit
return type.
More Details.
Based on the parameters passed in the constructors, there are two types of constructors in Java.
o Default Constructor: default constructor is the one which does not accept any value. The
default constructor is mainly used to initialize the instance variable with the default values. It
can also be used for performing some useful task on object creation. A default constructor is
invoked implicitly by the compiler if there is no constructor defined in the class.
o Parameterized Constructor: The parameterized constructor is the one which can initialize the
instance variables with the given values. In other words, we can say that the constructors which
can accept the arguments are called parameterized constructors.
29) What is the purpose of a default constructor?
The purpose of the default constructor is to assign the default value to the objects. The java compiler
creates a default constructor implicitly if there is no constructor in the class.
1. class Student3{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. s1.display();
11. s2.display();
12. }
13. }
Test it Now
Output:
0 null
0 null
Explanation: In the above class, you are not creating any constructor, so compiler provides you a
default constructor. Here 0 and null values are provided by default constructor.
More Details.
Ans: yes, The constructor implicitly returns the current instance of the class (You can't use an
explicit return type with the constructor). More Details.
Yes, the constructors can be overloaded by changing the number of arguments accepted by the
constructor or by changing the data type of the parameters. Consider the following example.
1. class Test
2. {
3. int i;
4. public Test(int k)
5. {
6. i=k;
7. }
8. public Test(int k, int m)
9. {
10. System.out.println("Hi I am assigning the value max(k, m) to i");
11. if(k>m)
12. {
13. i=k;
14. }
15. else
16. {
17. i=m;
18. }
19. }
20. }
21. public class Main
22. {
23. public static void main (String args[])
24. {
25. Test test1 = new Test(10);
26. Test test2 = new Test(12, 15);
27. System.out.println(test1.i);
28. System.out.println(test2.i);
29. }
30. }
31.
In the above program, The constructor Test is overloaded with another constructor. In the first call to
the constructor, The constructor with one argument is called, and i will be initialized with the value
10. However, In the second call to the constructor, The constructor with the 2 arguments is called,
and i will be initialized with the value 15.
There is no copy constructor in java. However, we can copy the values from one object to another
like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
o By constructor
In this example, we are going to copy the values of one object into another using java constructor.
111 Karan
111 Karan
35) What are the differences between the constructors and methods?
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you The method is not provided by the
don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class name. The method name may or may not be
same as class name.
36) What is the output of the following Java program?
a = 10 b = 15
Here, the data type of the variables a and b, i.e., byte gets promoted to int, and the first
parameterized constructor with the two integer parameters is called.
1. class Test
2. {
3. int i;
4. }
5. public class Main
6. {
7. public static void main (String args[])
8. {
9. Test test = new Test();
10. System.out.println(test.i);
11. }
12. }
The output of the program is 0 because the variable i is initialized to 0 internally. As we know that a
default constructor is invoked implicitly if there is no constructor in the class, the variable i is
initialized to 0 since there is no constructor in the class.
1. class Test
2. {
3. int test_a, test_b;
4. Test(int a, int b)
5. {
6. test_a = a;
7. test_b = b;
8. }
9. public static void main (String args[])
10. {
11. Test test = new Test();
12. System.out.println(test.test_a+" "+test.test_b);
13. }
14. }
There is a compiler error in the program because there is a call to the default constructor in the
main method which is not present in the class. However, there is only one parameterized constructor
in the class Test. Therefore, no default constructor is invoked by the constructor implicitly.
The static variable is used to refer to the common property of all objects (that is not unique for each
object), e.g., The company name of employees, college name of students, etc. Static variable gets
memory only once in the class area at the time of class loading. Using a static variable makes your
program more memory efficient (it saves memory). Static variable belongs to the class rather than
the object.
o A static method can access and change the value of the static variable.
More Details.
41) What are the restrictions that are applied to the Java static methods?
o The static method can not use non-static data member or call the non-static method directly.
o this and super cannot be used in static context as they are non-static.
Because the object is not required to call the static method. If we make the main method non-static,
JVM will have to create its object first and then call main() method which will lead to the extra
memory allocation. More Details.
1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Test it Now
More Details.
Ans) Yes, one of the ways to execute the program without the main method is using static
block. More Details.
46) What if the static modifier is removed from the signature of the main method?
47) What is the difference between static (class) method and instance method?
1)A method that is declared as static is known as the static A method that is not declared as
method. static is known as the instance
method.
2)We don't need to create the objects to call the static The object is required to call the
methods. instance methods.
3)Non-static (instance) members cannot be accessed in the Static and non-static variables both
static context (static method, static block, and static nested can be accessed in instance
class) directly. methods.
4)For example: public static int cube(int n){ return For example: public void
n*n*n;} msg(){...}.
As we know that the static context (method, block, or variable) belongs to the class, not the object.
Since Constructors are invoked only when the object is created, there is no sense to make the
constructors static. However, if you try to do so, the compiler will show the compiler error.
In Java, if we make the abstract methods static, It will become the part of the class, and we can
directly call it which is unnecessary. Calling an undefined method is completely useless therefore it is
not allowed.
50) Can we declare the static variables and methods in an abstract class?
Yes, we can declare static variables and methods in an abstract method. As we know that there is no
requirement to make the object to access the static context, therefore, we can access the static
context declared inside the abstract class by using the name of the abstract class. Consider the
following example.
Output
hi !! I am good !!
i = 102
The this keyword is a reference variable that refers to the current object. There are the various uses
of this keyword in Java. It can be used to refer to current class properties such as instance methods,
variable, constructors, etc. It can also be passed as an argument into the methods or constructors. It
can also be returned from the method as the current class instance.
More Details.
52) What are the main uses of this keyword?
o this can be used to return the current class instance from the method.
No, this cannot be assigned to any value because it always points to the current class object and this
is the final reference in Java. However, if we try to do so, the compiler error will be shown. Consider
the following example.
Output
Yes, It is possible to use this keyword to refer static members because this is just a reference
variable which refers to the current class object. However, as we know that, it is unnecessary to
access static variables through objects, therefore, it is not the best practice to use this to refer static
members. Consider the following example.
Output
10
Output
56) What are the advantages of passing this into a method instead of the current class object itself?
As we know, that this refers to the current class object, therefore, it must be similar to the current
class object. However, there can be two main advantages of passing this into a method instead of
the current class object.
o this is a final variable. Therefore, this cannot be assigned to any new value whereas the current
class object might not be final and can be changed.
Inheritance is a mechanism by which one object acquires all the properties and behavior of another
object of another class. It is used for Code Reusability and Method Overriding. The idea behind
inheritance in Java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you
can add new methods and fields in your current class also. Inheritance represents the IS-A
relationship which is also known as a parent-child relationship.
o Single-level inheritance
o Multi-level inheritance
o Multiple Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
Multiple inheritance is not supported in Java through class.
More Details.
There are various advantages of using inheritance in Java that is given below.
o Inheritance provides code reusability. The derived class does not need to redefine the method of
base class unless it needs to provide the specific implementation of the method.
o We can simulate the inheritance of classes with the real-time objects which makes OOPs more
realistic.
o Inheritance provides data hiding. The base class can hide some data from the derived class by
making it private.
o Method overriding cannot be achieved without inheritance. By method overriding, we can give a
specific implementation of some basic method contained by the base class.
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A
and B classes have the same method and you call it from child class object, there will be ambiguity to
call the method of A or B class.
Since the compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have the same method or different, there will be a compile time
error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Aggregation can be defined as the relationship between two classes where the aggregate class
contains a reference to the class it owns. Aggregation is best described as a has-a relationship. For
example, The aggregate class Employee having various fields such as age, name, and salary also
contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-
code. In other words, we can say that Employee (class) has an object of Address class. Consider the
following example.
Address.java
Employee.java
Output
111 varun
gzb UP india
112 arun
gno UP india
Holding the reference of a class within some other class is known as composition. When an object
contains the other object, if the contained object cannot exist without the existence of container
object, then it is called composition. In other words, we can say that composition is the particular
case of aggregation which represents a stronger relationship between two objects. Example: A class
contains students. A student cannot exist without a class. There exists composition between class
and students.
Aggregation represents the weak relationship whereas composition represents the strong
relationship. For example, the bike has an indicator (aggregation), but the bike has an engine
(composition).
The super keyword in Java is a reference variable that is used to refer to the immediate parent class
object. Whenever you create the instance of the subclass, an instance of the parent class is created
implicitly which is referred by super reference variable. The super() is called in the class constructor
implicitly by the compiler if there is no super or this.
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }
13. }
Test it Now
Output:
animal is created
dog is created
More Details.
66) How can constructor chaining be done by using the super keyword?
1. class Person
2. {
3. String name,address;
4. int age;
5. public Person(int age, String name, String address)
6. {
7. this.age = age;
8. this.name = name;
9. this.address = address;
10. }
11. }
12. class Employee extends Person
13. {
14. float salary;
15. public Employee(int age, String name, String address, float salary)
16. {
17. super(age,name,address);
18. this.salary = salary;
19. }
20. }
21. public class Test
22. {
23. public static void main (String args[])
24. {
25. Employee e = new Employee(22, "Mukesh", "Delhi", 90000);
26. System.out.println("Name: "+e.name+" Salary: "+e.salary+" Age: "+e.age+" Address: "+
e.address);
27. }
28. }
Output
o super can be used to refer to the immediate parent class instance variable.
68) What are the differences between this and super keyword?
There are the following differences between this and super keyword.
o The super keyword always points to the parent class contexts whereas this keyword always
points to the current class context.
o The super keyword is primarily used for initializing the base class variables within the derived
class constructor whereas this keyword primarily used to differentiate between local and
instance variables when passed in the class constructor.
o The super and this must be the first statement inside constructor otherwise the compiler will
throw an error.
1. class Person
2. {
3. public Person()
4. {
5. System.out.println("Person class constructor called");
6. }
7. }
8. public class Employee extends Person
9. {
10. public Employee()
11. {
12. System.out.println("Employee class constructor called");
13. }
14. public static void main (String args[])
15. {
16. Employee e = new Employee();
17. }
18. }
Output
Explanation
The super() is implicitly invoked by the compiler if no super() or this() is included explicitly within the
derived class constructor. Therefore, in this case, The Person class constructor is called first and then
the Employee class constructor is called.
No, because this() and super() must be the first statement in the class constructor.
Example:
Output:
The object cloning is used to create the exact copy of an object. The clone() method of the Object
class is used to clone an object. The java.lang.Cloneable interface must be implemented by the
class whose object clone we want to create. If we don't implement Cloneable interface, clone()
method generates CloneNotSupportedException.
Method overloading is the polymorphism technique which allows us to create multiple methods with
the same name but different signature. We can achieve method overloading in two ways.
Method overloading increases the readability of the program. Method overloading is performed to
figure out the program quickly.
More Details.
73) Why is method overloading not possible by changing the return type in java?
In Java, method overloading is not possible by changing the return type of the program due to avoid
the ambiguity.
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));//ambiguity
8. }}
Test it Now
Output:
Compile Time Error: method add(int, int) is already defined in class Adder
More Details.
No, We cannot overload the methods by just applying the static keyword to them(number of
parameters and types are the same). Consider the following example.
1. public class Animal
2. {
3. void consume(int a)
4. {
5. System.out.println(a+" consumed!!");
6. }
7. static void consume(int a)
8. {
9. System.out.println("consumed static "+a);
10. }
11. public static void main (String args[])
12. {
13. Animal a = new Animal();
14. a.consume(10);
15. Animal.consume(20);
16. }
17. }
Output
Yes, we can have any number of main methods in a Java program by using method overloading.
More Details.
By Type promotion is method overloading, we mean that one data type can be promoted to another
implicitly if no exact matching is found.
As displayed in the above diagram, the byte can be promoted to short, int, long, float or double. The
short datatype can be promoted to int, long, float or double. The char datatype can be promoted to
int, long, float or double and so on. Consider the following example.
1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9. }
10. }
Test it Now
Output
40
60
1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Output
Explanation
There are two methods defined with the same name, i.e., sum. The first method accepts the integer
and long type whereas the second method accepts long and the integer type. The parameter passed
that are a = 20, b = 20. We can not tell that which method will be called as there is no clear
differentiation mentioned between integer literal and long literal. This is the case of ambiguity.
Therefore, the compiler will throw an error.
Core Java - OOPs Concepts: Method Overriding Interview Questions
If a subclass provides a specific implementation of a method that is already provided by its parent
class, it is known as Method Overriding. It is used for runtime polymorphism and to implement the
interface methods.
o The method must have the same name as in the parent class.
o The method must have the same signature as in the parent class.
More Details.
No, you can't override the static method because they are the part of the class, not the object.
Yes.
2) Method overloading occurs Method overriding occurs in two classes that have IS-A
within the class. relationship between them.
3) In this case, the parameters In this case, the parameters must be the same.
must be different.
No, we cannot override the private methods because the scope of private methods is limited to the
class and we cannot access them outside of the class.
84) Can we change the scope of the overridden method in the subclass?
Yes, we can change the scope of the overridden method in the subclass. However, we must notice
that we cannot decrease the accessibility of the method. The following point must be taken care of
while changing the accessibility of the method.
Yes, we can modify the throws clause of the superclass method while overriding it in the subclass.
However, there are some rules which are to be followed while overriding in case of exception
handling.
o If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception, but it can declare the unchecked exception.
o If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
1. class Base
2. {
3. void method(int a)
4. {
5. System.out.println("Base class method called with integer a = "+a);
6. }
7.
8. void method(double d)
9. {
10. System.out.println("Base class method called with double d ="+d);
11. }
12. }
13.
14. class Derived extends Base
15. {
16. @Override
17. void method(double d)
18. {
19. System.out.println("Derived class method called with double d ="+d);
20. }
21. }
22.
23. public class Main
24. {
25. public static void main(String[] args)
26. {
27. new Derived().method(10);
28. }
29. }
Output
Explanation
The method() is overloaded in class Base whereas it is derived in class Derived with the double type
as the parameter. In the method call, the integer is passed.
Now, since java5, it is possible to override any method by changing the return type if the return type
of the subclass overriding method is subclass type. It is known as covariant return type. The
covariant return type specifies that the return type may vary in the same direction as the subclass.
1. class A{
2. A get(){return this;}
3. }
4.
5. class B1 extends A{
6. B1 get(){return this;}
7. void message(){System.out.println("welcome to covariant return type");}
8.
9. public static void main(String args[]){
10. new B1().get().message();
11. }
12. }
Test it Now
1. class Base
2. {
3. public void baseMethod()
4. {
5. System.out.println("BaseMethod called ...");
6. }
7. }
8. class Derived extends Base
9. {
10. public void baseMethod()
11. {
12. System.out.println("Derived method called ...");
13. }
14. }
15. public class Test
16. {
17. public static void main (String args[])
18. {
19. Base b = new Derived();
20. b.baseMethod();
21. }
22. }
Output
The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the
reference variable b (of type Base class) refers to the instance of the Derived class. Here, Runtime
polymorphism is achieved between class Base and Derived. At compile time, the presence of method
baseMethod checked in Base class, If it presence then the program compiled otherwise the compiler
error will be shown. In this case, baseMethod is present in Base class; therefore, it is compiled
successfully. However, at runtime, It checks whether the baseMethod has been overridden by
Derived class, if so then the Derived class method is called otherwise Base class method is called. In
this case, the Derived class overrides the baseMethod; therefore, the Derived class method is called.
In Java, the final variable is used to restrict the user from updating it. If we initialize the final
variable, we can't change its value. In other words, we can say that the final variable once assigned
to a value, can never be changed after that. The final variable which is not assigned to any value can
only be assigned through the class constructor.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
If we change any method to a final method, we can't override it. More Details.
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
If we make any class final, we can't inherit it into any of the subclasses.
1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
More Details.
Yes, if it is not static, we can initialize it in the constructor. If it is static blank final variable, it can be
initialized only in the static block. More Details.
1. class Main {
2. public static void main(String args[]){
3. final int i;
4. i = 20;
5. System.out.println(i);
6. }
7. }
Output
20
Explanation
Since i is the blank final variable. It can be initialized only once. We have initialized it to 20.
Therefore, 20 will be printed.
97) What is the output of the following Java program?
1. class Base
2. {
3. protected final void getInfo()
4. {
5. System.out.println("method of Base class");
6. }
7. }
8.
9. public class Derived extends Base
10. {
11. protected final void getInfo()
12. {
13. System.out.println("method of Derived class");
14. }
15. public static void main(String[] args)
16. {
17. Base obj = new Base();
18. obj.getInfo();
19. }
20. }
Output
Explanation
The getDetails() method is final; therefore it can not be overridden in the subclass.
The constructor can never be declared as final because it is never inherited. Constructors are not
ordinary methods; therefore, there is no sense to declare constructors as final. However, if you try to
do so, The compiler will throw an error.
One is that it depends on how often a deadlock is likely to occur under the implementation of this
algorithm. The other has to do with how many processes will be affected by deadlock when this
algorithm is applied.
20) State the main difference between logical from physical address space.
Logical address refers to the address that is generated by the CPU. On the other hand, physical address
refers to the address that is seen by the memory unit.
21) How does dynamic loading aid in better memory space utilization?
With dynamic loading, a routine is not loaded until it is called. This method is especially useful when
large amounts of code are needed in order to handle infrequently occurring cases such as error
routines.
Overlays are used to enable a process to be larger than the amount of memory allocated to it. The
basic idea of this is that only instructions and data that are needed at any given time are kept in
memory.
Paging is a memory management scheme that permits the physical address space of a process to be
non-contiguous. It avoids the considerable problem of having to fit varied sized memory chunks onto
the backing store.
Fragmentation is memory wasted. It can be internal if we are dealing with systems that have fixed-
sized allocation units, or external if we are dealing with systems that have variable-sized allocation
units.
Direct Access method is based on a disk model of a file, such that it is viewed as a numbered sequence
of blocks or records. It allows arbitrary blocks to be read or written. Direct access is advantageous
when accessing large amounts of information.
30) What is the best page size when designing an operating system?
The best paging size varies from system to system, so there is no single best when it comes to page
size. There are different factors to consider in order to come up with a suitable page size, such as page
table, paging time, and its effect on the overall efficiency of the operating system.
31) When designing the file structure for an operating system, what attributes are
considered?
Typically, the different attributes for a file structure are naming, identifier, supported file types, and
location for the files, size, and level of protection.
Root partition is where the operating system kernel is located. It also contains other potentially
important system files that are mounted during boot time.
Device drivers provide a standard means of representing I/O devices that maybe manufactured by
different companies. This prevents conflicts whenever such devices are incorporated in a systems unit.
35) What are the different types of CPU registers in a typical operating system design?
– Accumulators
– Index Registers
– Stack Pointer
– General Purpose Registers
I/O status information provides information about which I/O devices are to be allocated for a particular
process. It also shows which files are opened, and other I/O device state.
Multitasking is the process within an operating system that allows the user to run several applications
at the same time. However, only one application is active at a time for user interaction, although some
applications can run “behind the scene”.
However, the main problem with a command line interface is that users have to be familiar with the
commands, including the switches and parameters that come with it. This is a downside for people who
are not fond of memorizing commands.
Caching is the processing of utilizing a region of fast memory for a limited data and process. A cache
memory is usually much efficient because of its high access speed.
Spooling is normally associated with printing. When different applications want to send an output to
the printer at the same time, spooling takes all of these print jobs into a disk file and queues them
accordingly to the printer.
An assembler acts as a translator for low-level language. Assembly codes written using mnemonic
commands are translated by the Assembler into machine language.
GUI is short for Graphical User Interface. It provides users with an interface wherein actions can be
performed by interacting with icons and graphical symbols. People find it easier to interact with the
computer when in a GUI especially when using the mouse. Instead of having to remember and type
commands, users click on buttons to perform a process.
Pre-emptive multitasking allows an operating system to switch between software programs. This, in
turn, allows multiple programs to run without necessarily taking complete control over the processor
and resulting in system crashes.
Partitioning and formatting create a preparatory environment on the drive so that the operating system
can be copied and installed properly. This includes allocating space on the drive, designating a drive
name, determining and creating the appropriate file system and structure.
NOS is short for Network Operating System. It is a specialized software that will allow a computer to
communicate with other devices over the network, including file/folder sharing.
Internal commands are built-in commands that are already part of the operating system. External
commands are separate file programs that are stored in a separate folder or directory.
49) Under DOS, what command will you type when you want to list down the files in a
directory, and at the same time pause after every screen output?
a) dir /w
b) dir /p
c) dir /s
d) dir /w /p
Answer: d) dir /w /p
50) How would a file name EXAMPLEFILE.TXT appear when viewed under the DOS command
console operating in Windows 98?
The filename would appear as EXAMPL~1.TXT. The reason behind this is that filenames under this
operating system are limited to 8 characters when working under DOS environment.
Deadlock is a situation when two or more processes wait for each other to finish and none of them ever
finish. Consider an example when two trains are coming toward each other on same track and there
is only one track, none of the trains can move once they are in front of each other. Similar situation
occurs in operating systems when there are two or more processes hold some resources and wait for
resources held by other(s).
Kernel is the core of every operating system. It connects applications to the actual processing of data.
It also manages all communications between software and hardware components to ensure usability
and reliability.
Server systems can be classified as either computer-server systems or file server systems. In the first
case, an interface is made available for clients to send requests to perform an action. In the second
case, provisions are available for clients to create, access and update files.
56) Differentiate Logical from Physical Address Space.?
Logical address refers to the address that is generated by the CPU. On the other hand, physical address
refers to the address that is seen by the memory unit.
57) Question 20. How Does Dynamic Loading Aid In Better Memory Space Utilization?
With dynamic loading, a routine is not loaded until it is called. This method is especially useful when
large amounts of code are needed in order to handle infrequently occurring cases such as error
routines.
Overlays are used to enable a process to be larger than the amount of memory allocated to it. The
basic idea of this is that only instructions and data that are needed at any given time are kept in
memory.
During regular intervals that are set by the operating system, processes can be copied from main
memory to a backing store, and then copied back later. Swapping allows more processes to be run
that can fit into memory at one time.
60)What Is the Best Page Size When Designing An Operating System?
The best paging size varies from system to system, so there is no single best when it comes to page
size. There are different factors to consider in order to come up with a suitable page size, such as page
table, paging time, and its effect on the overall efficiency of the operating system.
61)When Designing the File Structure for An Operating System, What Attributes Are
Considered?
Typically, the different attributes for a file structure are naming, identifier, supported file types, and
location for the files, size, and level of protection.
Device drivers provides a standard means of representing I/O devices that maybe manufactured by
different companies. This prevents conflicts whenever such devices are incorporated in a systems unit.
63) What Are the Different Types of CPU Registers In A Typical Operating System Design?
o Accumulators
o Index Registers
o Stack Pointer
o General Purpose Registers
I/O status information provides info about which I/O devices are to be allocated for a particular process.
It also shows which files are opened, and other I/O device state.
65) What Are Some Pros and Cons ofa Command Line Interface?
A command line interface allows the user to type in commands that can immediately provide results.
Many seasoned computer users are well accustomed to using the command line because they find it
quicker and simpler. The main problem with a command line interface is that users have to be familiar
with the commands, including the switches and parameters that come with it. This is a downside for
people who are not fond of memorizing commands.
66)What Is an Assembler?
An assembler acts as a translator for low level language. Assembly codes, written using mnemonic
commands are translated by the Assembler into machine language.
67) What Are Interrupts?
Interrupts are part of a hardware mechanism that sends a notification to the CPU when it wants to
gain access to a particular resource. An interrupt handler receives this interrupt signal and “tells” the
processor to take action based on the interrupt request.
GUI is short for Graphical User Interface. It provides users with an interface wherein actions can be
performed by interacting with icons and graphical symbols. People find it easier to interact with the
computer when in a GUI especially when using the mouse. Instead of having to remember and type
commands, users just click on buttons to perform a process.
Internal commands are built-in commands that are already part of the operating system.
External commands are separate file programs that are stored in a separate folder or directory.
71) Explain Booting the system and Bootstrap program in operating system.
The procedure of starting a computer by loading the kernel is known as booting the system. When
a user first turns on or booted the computer, it needs some initial program to run. This initial program
is known as Bootstrap Program. It is stored in read-only memory (ROM) or electrically erasable
programmable read-only memory (EEPROM). Bootstrap program locates the kernel and loads it into
main memory and starts its execution.
Main memory is also called random access memory (RAM). CPU can access Main memory directly.
Data access from main memory is much faster than Secondary memory. It is implemented in a
semiconductor technology, called dynamic random-access memory (DRAM).
Main memory is usually too small to store all needed programs. It is a volatile storage device that
loses its contents when power is turned off. Secondary memory can store large amount of data and
programs permanently. Magnetic disk is the most common secondary storage device. If a user wants
to execute any program it should come from secondary memory to main memory because CPU can
access main memory directly.
a. Monolithic Kernels - In this architecture of kernel, all the system services were packaged into a
single system module which lead to poor maintainability and huge size of kernel.
b. Microkernels - They follow the modular approach of architecture. Maintainability became easier
with this model as only the concerned module is to be altered and loaded for every function. This
model also keeps a tab on the ever-growing code size of the kernel.
Following are the main disadvantages of Microkernels. Usually these disadvantages are situation
based.
It is a program that interprets the command input through keyboard or command batch file. It helps
the user to interact with the OS and trigger the required system programs or execute some user
application.
Shell
- The address of each Interrupt service routine is provided in a list which is maintained in interrupt
vector.
- Daemon - Disk and execution monitor, is a process that runs in the background without user’s
interaction. They usually start at the booting time and terminate when the system is shut down.
- The name of daemons usually end with 'd' at the end in Unix.
- These are dead processes which are not yet removed from the process table.
- It happens when the parent process has terminated while the child process is still running. This
child process now stays as a zombie.
- It is an IPC mechanism used for one way communication between two processes which are related.
- A single process doesn't need to use pipe. It is used when two process wish to communicate one-
way.
- A traditional pipe is unnamed and can be used only for the communication of related process. If
unrelated processes are required to communicate - named pipes are required.
- It is a pipe whose access point is a file available on the file system. When this file is opened for
reading, a process is granted access to the reading end of the pipe. Similarly, when the file is opened
for writing, the process is granted access to writing end of the pipe.
a. Sockets
b. Pipes
c. Shared memory
d. Signals
e. Message Queues
- A semaphore is a hardware or a software tag variable whose value indicates the status of a common
resource.
- Its purpose is to lock the common resource being used. A process which needs the resource will
check the semaphore to determine the status of the resource followed by the decision for proceeding.
- In multitasking operating systems, the activities are synchronized by using the semaphore
techniques.
- Context is associated with each process encompassing all the information describing the current
execution state of the process
- When the OS saves the context of program that is currently running and restores the context of
the next ready to run process, it is called as context switching.
- It is important for multitasking OS.
- Mutex - ‘Mutual Exclusion Lock’ is a lock which protects access to shared data resource.
- Before entering a critical region the mutex is locked. It is unlocked after exiting the critical region.
If any thread tries to lock the mutex during this time, it can't do so.
Synchronization means controlling access to a resource that is available to two or more threads or
process. Different synchronization mechanisms are:
- Mutex
- Semaphores
- Monitors
- Condition variables
- Critical regions
89) What is the basic difference between pre-emptive and non-pre-emptive scheduling?
Pre-emptive scheduling allows interruption of a process while it is executing and taking the CPU to
another process while non-pre-emptive scheduling ensures that a process keeps the CPU under
control until it has completed execution.
- It can not ensure that each user gets a share of CPU regularly.
- The idle time with this increases reducing the efficiency and overall performance of the system.
- It allows program to run indefinitely which means that other processes have to wait for very long.
- These are synchronization objects which help threads wait for particular conditions to occur.
- Without condition variable, the thread has to continuously check the condition which is very costly
on the resources.
- Condition variable allows the thread to sleep and wait for the condition variable to give it a signal.
- Read - write locks provide simultaneous read access to many threads while the write access stays
with one thread at a time. They are especially useful in protecting the data that is not frequently
written but read simultaneously by many threads.
- It is a condition where a group of two or more waiting for the resources currently in use by other
processes of the same group.
- In this situation every process is waiting for an event to be triggered by another process of the
group.
- Since no thread can free up the resource a deadlock occurs and the application hangs.
- Integrity maintenance
- Swapping
- Virtual memory
c. Cache
- This memory consists of a set of high-speed registers. They work as temporary storage for
instructions and data.
During the process of loading and removal of process into and out of the memory, the free memory
gets broken into smaller pieces. These pieces lie scattered in the memory. Compaction means
movement of these pieces close to each other to form a larger chunk of memory which works as a
resource to run larger processes.
Page frames are the fixed size contiguous areas into which the main memory is divided by the virtual
memory.
- Pages are same sized pieces of logical memory of a program. Usually they range from 4 KB to 8
KB depending on the addressing hardware of the machine.
- Pages improve the overall system performance and reduces requirement of physical storage as the
data is read in 'page' units.
DataBase Management System
Q25) What restrictions can you apply when you are creating views?
Restrictions that are applied are:
Only the current database can have views.
You are not liable to change any computed value in any particular view.
Integrity constants decide the functionality of INSERT and DELETE.
Full-text index definitions cannot be applied.
Temporary views cannot be created.
Temporary tables cannot contain views.
No association with DEFAULT definitions.
Triggers such as INSTEAD OF is associated with views.
Q36) What do you mean by Fill Factor concept with respect to indexes?
Fill Factor can be defined as being that value which defines the percentage of left space on every leaf-
level page that is to be packed with data. 100 is the default value of Fill Factor.
VARCHAR will hold the space for characters defined during declaration even if all of them are not used
whereas VARCHAR2 will release the unused space.
Q54) What is the difference between TRUNCATE & DELETE command?
QBoth the commands are used to remove data from a database.
The finer differences between the two include:
TRUNCATE is a DDL operation while DELETE is a DML operation.
TRUNCATE drops the structure of a database and hence cannot be rolled back while DELETE
command can be rolled back.
The TRUNCATE command will free the object storage space while the DELETE command does not.
Example: [Select SUBSTR (‘India is my country’, 1, 4) from dual] will return “Indi”.
INSTR will return the position number of the sub-string within the string.
Example: [SELECT INSTR (‘India is my country’, ‘a’) from dual] will return 5.
Q58) How can we find out the duplicate values in an Oracle table?
We can use the below example query to fetch the duplicate records.
SELECT EMP_NAME, COUNT (EMP_NAME)
FROM EMP
GROUP BY EMP_NAME
HAVING COUNT (EMP_NAME) > 1;
Syntax:
ALTER TABLE CHILD_T1 ADD CONSTRAINT CHILD_PARENT_FK REFERENCES
PARENT_T1 (COLUMN1) ON DELETE CASCADE;
Q61) What is the difference between a Primary Key & a Unique Key?
Primary key is used to identify each table row uniquely, while a Unique Key prevents duplicate values
in a table column.
Given below are few differences:
The primary key can be only one on the table while unique keys can be multiple.
The primary key cannot hold null value at all while Unique key allows multiple null values.
The primary key is a clustered index while a unique key is a non-clustered index.
Q63) How can we find out the current date and time in Oracle?
We can find the current Date & Time using SYSDATE in Oracle.
Syntax:
SELECT SYSDATE into CURRENT_DATE from dual;
Q65) How will you write a query to get a 5th RANK student from a table STUDENT_REPORT?
The Query will be as follows:
SELECT TOP 1 RANK
FROM (SELECT TOP 5 RANK
FROM STUDENT_REPORT
ORDER BY RANK DESC) AS STUDENT
ORDER BY RANK ASC;
Q67) What is the quickest way to fetch the data from a table?
The quickest way to fetch the data would be to use ROWID in the SQL Query.
CASE Function
Select ORDERNUM
, CASE (WHEN STATUS ='O' then ‘ORDERED’
WHEN STATUS ='P' then PACKED
WHEN STATUS ='S' then ’SHIPPED’
ELSE ’ARRIVED’) END
FROM ORDERS;
Both the commands will display Order Numbers with respective Status as,
If,
Status O= Ordered
Status P= Packed
Status S= Shipped
Status A= Arrived
Q70) What do you mean by MERGE in Oracle and how can we merge two tables?
MERGE statement is used to merge the data from two tables. It selects the data from the source table
and inserts/updates it in the other table based on the condition provided in the MERGE query.
Syntax:
MERGE INTO TARGET_TABLE_1
USING SOURCE_TABLE_1
ON SEARCH_CONDITION
WHEN MATCHED THEN
INSERT (COL_1, COL_2…)
VALUES (VAL_1, VAL_2…)
WHERE <CONDITION>
WHEN NOT MATCHED THEN
UPDATE SET COL_1=VAL_1, COL_2=VAL_2…
WHEN <CONDITION>
Q71) What is the use of Aggregate functions in Oracle?
Aggregate functions perform summary operations on a set of values to provide a single value. There
are several aggregate functions that we use in our code to perform calculations.
Few of them are listed below:
AVG
MIN
MAX
COUNT
SUM
STDEV
Q72) What are the set operators UNION, UNION ALL, MINUS & INTERSECT meant to do?
Set operator facilitates the user to fetch the data from two or more than two tables at once if the
columns and relative data types are same in the source tables.
UNION operator returns all the rows from both the tables except the duplicate rows.
UNION ALL returns all the rows from both the tables along with the duplicate rows.
MINUS returns rows from the first table, which does not exist in the second table.
INTERSECT returns only the common rows in both the tables.
Q73) Can we convert a date to char in Oracle and if so, what would be the syntax?
We can use the TO_CHAR function to do the above conversion.
The syntax will be as follows:
[SELECT to_char (to_date ('30-01-2018′, ‘DD-MM-YYYY'), ‘YYYY-MM-DD') FROM dual;]
Q 74) What do you mean by a database transaction & what all TCL statements are available in Oracle?
Transaction occurs when a set of SQL statements are executed in one go. To control the execution of
these statements, Oracle has introduced TCL i.e. Transaction Control Statements that use a set of
statements.
The set of statements include:
COMMIT: Used to make a transaction permanent.
ROLLBACK: Used to roll back the state of DB to last the commit point.
SAVEPOINT: Helps to specify a transaction point to which rollback can be done later.
Q75) What do you understand by a database object? Can you list a few of them?
An object used to store the data or references of the data in a database is known as a Database object.
The database consists of various types of DB objects such as tables, views, indexes, constraints, stored
procedures, triggers etc.
Q76) What is a Nested table and how is it different from a normal table?
A nested table is a database collection object, which can be stored as a column in a table. While
creating a normal table, an entire nested table can be referenced in a single column. Nested tables
have only one column with no restriction of rows.
Example:
CREATE TABLE EMP (
EMP_ID NUMBER,
EMP_NAME TYPE_NAME)
Here we are creating a normal table as EMP and referring a nested table TYPE_NAME as a column.
Q78) What do you understand by database schema and what does it hold?
Schema is a collection of database objects owned by a database user who can create or manipulate
new objects within this schema.
The schema can contain any DB objects like table, view, indexes, clusters, stored procs, functions etc.
Q86) Why do we create Stored Procedures & Functions in PL/SQL and how are they different?
A stored procedure is a set of SQL statements that are written to perform a specific task. These
statements can be saved as a group in the database with an assigned name and can be shared with
different programs if permissions are there to access the same.
Functions are again subprograms that are written to perform specific tasks but there are differences
between both of them.
Functions
Stored Procedures
SPs may or may not return a value and Function will always return
can return multiple values as well. only single value.
Q 87) What are the parameters that we can pass through a stored procedure?
We can pass IN, OUT & INOUT parameters through a stored procedure and they should be
defined while declaring the procedure itself.
Q91)What is a Self-Join?
A self JOIN is a case of regular join where a table is joined to itself based on some relation between its
own column(s). Self-join uses the INNER JOIN or LEFT JOIN clause and a table alias is used to assign
different names to the table within the query.
SELECT A.emp_id AS"Emp_ID",A.emp_name AS"Employee",
B.emp_id AS"Sup_ID",B.emp_name AS"Supervisor"
FROM employee A, employee B
WHERE A.emp_sup = B.emp_id;
Q92)What is a Cross-Join?
Cross join can be defined as a cartesian product of the two tables included in the join. The table after
join contains the same number of rows as in the cross-product of number of rows in the two tables. If
a WHERE clause is used in cross join then the query will work like an INNER JOIN.
SELECT stu.name, sub.subject
FROM students AS stu
CROSSJOIN subjects AS sub;
Collation refers to a set of rules that determine how data is sorted and compared. Rules defining the
correct character sequence are used to sort the character data. It incorporates options for specifying
case-sensitivity, accent marks, kana character types and character width. Below are the different types
of collation sensitivity:
Case sensitivity: A and a are treated differently.
Accent sensitivity: a and á are treated differently.
Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated differently.
Width sensitivity: Same character represented in single-byte (half-width) and double-byte (full-
width) are treated differently.
Q98)How to create empty tables with the same structure as another table?
Creating empty tables with the same structure can be done smartly by fetching the records of one
table into a new table using the INTO operator while fixing a WHERE clause to be false for all records.
Hence, SQL prepares the new table with a duplicate structure to accept the fetched records but since
no records get fetched due to the WHERE clause in action, nothing is inserted into the new table.
SELECT*INTO Students_copy
FROM Students WHERE1 = 2;
Q.99)Write a SQL query to fetch employee names having a salary greater than or equal to 5000 and
less than or equal 10000.
Ans. Here, we will use BETWEEN in the ‘where’ clause to return the EmpId of the employees with salary
satisfying the required criteria and then use it as subquery to find the fullName of the employee form
EmployeeDetails table.
SELECTFullName
FROMEmployeeDetails
WHEREEmpId IN
(SELECTEmpId FROMEmpolyeeSalary
WHERESalary BETWEEN5000 AND10000);
Q100). Write a SQL query to fetch project-wise count of employees sorted by project’s count in
descending order.
Ans. The query has two requirements – first to fetch the project-wise count and then to sort the result
by that count. For project-wise count, we will be using GROUPBY clause and for sorting, we will use
ORDER BY clause on the alias of the project-count.
SELECTProject, count(EmpId) EmpProjectCount
FROMEmployeeSalary
GROUP BY Project
ORDERBYEmpProjectCount DESC;