You are on page 1of 58

C interview questions

Q1). What is C Programming Language?


Ans:
C is an imperative procedural Programming language.
This is designed by Dennis Ritchie. C was originally
developed by Dennis Ritchie between 1969 and 1973 at
AT & T Bell Labs. C Language was first appeared in 1972.
It was mainly developed as a system programming
language to write OS (operating system).

Q2). Write some features of C Programming Language.


Ans: The features of the C programming Language are:

 Portability:It means that we can easily run


programs written on one platform on the other
platform. Ex- A sum of number programs written on
Turbo C++ can run on Codeblocks.
 Simple: Simple is also a feature of C programming
language because it is very easy to learn and
understand the programming concepts and build the
logics.
 Memory Management: Memory management is
also a good features of c programming language. It
supports both static as well as dynamic memory
allocation. Using the concept of dynamic memory
allocation we can allocate memory as per
requirement and can free useless allocated memory
space by calling free() function.
 Speed: The compilation and execution time of the c
language is fast as compared to other programming
languages like Python or Java.
 Case Sensitive: The meaning of both Upper and
Lower case letters is different. EX: If we assign value
4 to lowercase x and try to access with uppercase X
then we encounter error.
 Rich Library: C language has a lot of in-built
functions which makes development fast.

Q3). What do you mean by Data Type in C?


Ans:
Data Type defines which type of value a variable can
store. In C programming language each variable is
associated with a data type and each data type requires
different size of memory.
Some most usable data type:
char: char shows the variable of type char stores single
character. char requires a one byte of memory.
Ex: char ch;
Here ch is variable and having data type “char”.
int: int shows the variable having data type int stores
integer value. int requires a four byte of memory.
Ex: int i;
here i is variable of type integers.
float: float is used to store decimal numbers with single
precision. float requires a four byte of memory.
Ex:float f;
Here f is variable of type float.
double: double is used to store decimal numbers with
double precision.
Ex: double d;
Here d is variable of type double.
Q4). How many types of data type in C Language?
Ans:
C language supports 2 type of data types:
a). Primary data types:
Primary data types are known as fundamental data
types.Some primary data types are integer(int), floating
point(float), character(char) and void.
b).Derived data types:
Derived data types are derived from primary datatypes.
Some derived data types are array, structure, union and
pointer.

Q5). What is constant and variable in C .


Ans:
Constant: A constant is a value or an identifier whose
value cannot be changed in a program. identifier also can
be defined as a constant.
For example:
const double PI = 3.14
Here, PI is a constant. And the PI contains 3.14 for this
program.

Variables
A variables is a value or an identifier whose value can be
changed in a program. Variable is a container to hold
data.
For example:
int score = 6;
Here, score is a variable of integer type and it contains
value 6. The value of score can be change so here score
is variable.

Q6) What is the use of printf() and scanf() functions?


Ans:
printf(): The printf() function is used to print values on
to the screen(console). Value may be anythings like
integer, float, character and string.
scanf():The scanf() function is used to take input from
the user.

Q7). What is the difference between the local variable


and global variable in C.
Ans:
local variable: It is defined inside a function. It is
accessible only in the function in which it is defined.

Global variable : It is defined outside of all the


functions in a program. It is available to all the functions
in the program.

Q8) Write format specifiers in C.


Ans:
%d: It is used to print an integer value.
%s: It is used to print a string.
%c: It is used to display a character value.
%f: It is used to display a floating point value.

Q9) How many spaces a Tab has in C.


Ans: A Tab has 8 spaces.

Q10) What is static variable in C? What is its use?


Ans:
static keyword is used to declared static variable. Static
variables preserves their value outside of their scope.
Hence, static variables preserve their previous value in
their previous scope and are not initialized again in the
new scope.
Scope of the static variable is available in the entire
program. So, we can access a static variable anywhere in
the program.
The initial value of the static variable is zero. The static
variable shares common value with all the methods.The
static variable is initialized only once in the memory heap
to reduce the memory usage.

Q11) Can we compile and execute a program without


main() function?
Ans:
Yes, we can compile and execute using macros.
#include <stdlib.h>
#include <stdio.h>
#define fun main
int fun(void)
{
printf("Quescol");
return 0;

}
Output:

Q12) Difference between getc(), getchar(), getch() and


getche().
Ans:
All of these functions read a character from input and
return an integer value. The integer is returned to
accommodate a special value used to indicate failure. The
value EOF is generally used for this purpose.
getc(): It reads a single character from a given input
stream and on success returns the integer value. And on
failure it returns EOF.
Syntax:
int getc(FILE *stream);
Example:
#include <stdio.h>
int main()
{
printf("%c", getc(stdin));
return(0);
}
Input: a (press enter key)
Output: a
getchar(): getchar() reads from standard input. it
returns only single charater from input stream. Also
getchar() is equivalent to getc(stdin).
Syntax:
int getchar(void);
Example:
#include <stdio.h>
int main()
{
printf("%c", getchar());
return 0;
}
Input: a(press enter key) Output: a
getch(): getch() is a nonstandard function.It is present
in conio.h header file. It is not a part of the C standard
library. getch() reads a single character from keyboard.
It does not use any buffer, so when we give a character
as input it immediately returned without waiting for the
enter key.
Syntax:
int getch();
Example:
#include <stdio.h>
#include <conio.h>
int main()
{
printf("%c", getch());
return 0;
}
Input: a
Output: Program terminates immediately. But when you
go on DOS shell in Turbo C, you see single ‘a’ as output.
getche() getche() is also a non-standard function which
is present in conio.h header file. When you give a
character as a input from the keyboard it displays
immediately on output screen without pressing enter key.
Syntax:
int getche(void);
Example:
#include <stdio.h>
#include <conio.h>
int main()
{
printf("%c", getche());
return 0;
}
Input: a
Output: Program terminates immediately. But when you
go on DOS shell in Turbo C, you see double ‘a’ as output
i.e. aa.

Q13). What is typecasting?


Ans:
The typecasting is a process of converting one data type
into another data type. Suppose If we want to store the
floating type value to an int type, then we will use
typecasting to convert floating point data type into int
data type explicitly.
Ex: int i = (int) 3.4

Q14) Write a program to print "hello world" without using


a semicolon?
Ans:
#include<stdio.h>
void main(){
if(printf("hello world")){}
}
Output:

Q15). What is the difference between the = symbol and


== symbol?
Ans:
The single = symbol is an assignment operator which is
used to assign value to a variable whereas the double ==
symbol is an relational operator which is used to compare
the two values, is also called “equal to” or “equivalent
to”.

Q16). What is C Token?


Ans: In c, Keywords, Constants, Special Symbols,
Strings, Operators, Identifiers are referred as Tokens.

Q17). Where can we not use &(address operator in C)?


Ans: We cannot use ‘&’ on constants and on a variable
which is declared using the register storage class.
Q18). What is l-value and r-value?
Ans: The term l-value and r-value are named because of
their appearance in the expression.
L-value appeared on the left side of the assignment
operator. Basically in general case variable is considered
as L-value in which we are going to assign some values.
R-value appeared on the right side of the assignment
operator.
Example: In this expression “x = 15”, x is considered as
l-value and 15 is as r-value.

Q19). What is the difference between puts() and printf()?


Ans:

puts() printf()
1. The printf() function
1. The puts() function only can print strings as well as
allows you to print a string on mixed types of variables
the console output screen. on the console output
screen.
2.The syntax for puts: 2.The syntax for printf:
puts(str) printf(str)
3. The puts() function prints
3.The printf() function
string and automatically adds
prints text, string, text+
one new character at the end
value, etc, without adding
of the string that is a new line
extra character at the end.
character(\n).
4. Its implementation is
4. Its implementation is
complex as compared to
simpler than printf.
puts.

C interview questions on statements and loops


Q1). Explain IF-Else Statement in C Language.
Ans:
IF-Else Statement works as a control flow statement in C.
if statement is followed by an optional else statement.
Syntax :
if(boolean_expression) {
/* statement s1 will execute if the
boolean_expression is true */
} else {
/* statement s2 will execute if the
boolean_expression is false */
}
If the Boolean_expression is true, then the if block will be
executed, otherwise, the else block will be executed.

Q2). What is a nested loop?


Ans:
It is also a type of loop which runs within another loop is
called nested loop.
Syntax :
for(initialization; condition;
increment/decrement)
{
Statements
for(initialization; condition;
increment/decrement)
{
statements
}
}

Q3). Break and continue in C Language with example.


Ans:
break: break statement terminates the loop when it is
encountered. The break statement can be used with
decision making statement such as if…else and loop like
for, while and do..while.
#include <stdio.h>
int main()
{
int i, n, sum = 0;
for(i=1; i <= 5; ++i)
{
printf("Enter a n%d: ",i);
scanf("%d",&n);
if(n > 6)
{
break;
}
sum += n;
}
printf("Sum = %d",sum);
return 0;
}
Output:

continue :
The continue statement is used to skips some statements
inside the loop. The continue statement is used with
decision making statement such as if…else.
# include <stdio.h>
int main()
{
int i,n, sum = 0;
for(i=1; i <= 5; ++i)
{
printf("Enter a n%d: ",i);
scanf("%d",&n);
if(n < 5)
{
continue;
}
sum += n;
}
printf("Sum = %d",sum);
return 0;
}
Output:

Q4). What are the valid places where the programmer


can apply Break Control Statement?
Ans:
It is valid to be used inside a loop and Switch control
statements.

Q5). Switch in C Language with example.


Ans:
A switch statement allows to test a variable for equality
against a list of cases. It is good practise to use switch
statement than nested if…else . Because switch is faster
than nested if…else(not always).
#include <stdio.h>
int main () {
int division = 3;
switch(division) {
case 1 :
printf("1st Division\n" );
break;
case 2 :
printf("2nd Division\n" );
break;
case 3 :
printf("3rd Division\n" );
break;
default :
printf("runner up\n" );
}
return 0;
}
Output:

Q6). While Loop in C Language with example.


Ans:
A while loop is used to executes a statement multiple
time as long as a given condition is true.
#include <stdio.h>
int main () {
int a = 0;
while( a < 10 ) {
printf("value of a: %d\n", a);
a++;
}
return 0;
}
Output:

Q7). What is the difference between while (0) and while


(1)?
Ans:
The term while is conditional based loop, While(0) means
the condition of while loop is false so it will never execute
a particular section of the code inside the program.
Whereas while(1) is the opposite of while(0) and it will
execute the particular section of code infinite times.
Q8). Difference b/w Entry controlled and Exit controlled
loop?
Ans:
In Entry controlled loop first the loop condition is checked
then after the body of the loop is executed whereas in
Exit controlled loop first the body of the loop is executed
then after condition is checked.
Entry Controlled Loops are : for, while
Exit Controlled Loop is : do while

Q9). Can we use continue statement without using a


loop?
Ans:
No, we cannot use continue statement without using a
loop, it can be used within any loop whether its while ,
for , or Do-while loop. In case if we try to use continue
without using loop, there will be a compile error
i.e”Misplaced continue”.

Q10) Explain for Loop in C Language with example.


Ans:
A for loop is used to executes a statement for a specific
number of times.
#include <stdio.h>
int main () {
int i;
for( i = 0; i < 10; i++ ){
printf("value of a: %d\n", i);
}
return 0;
}
Output:
Q11). What is the difference between ++a and a++.
Ans:
‘++a’ is called prefix increment. In this, first value of the
variable “a” gets incremented and then assigned to the
variable a. On the other hand “a++” is called post
increment.The value stored in the variable “a” gets
incremented after the execution of the particular line.

C interview questions on functions

Q1). What is function? Why to use function.


Ans:
A function is a block of code which performs some
specific task.
Uses of C function are: functions helps to avoid the
rewriting the same code again and again in our program.
functions can be called from any place of our program
and any number of times. functions helps to make code
more readable and simple.

#include<stdio.h>
void hello(){
printf("hello c programming \n");
}
int main(){

hello();
return 0;
}
Output:

Q2). What is recursion in C?


Ans:
When a function calls itself, and this process is known as
recursion. The function that calls itself is known as a
recursive function.
#include<stdio.h>
int fibonacci(int);
int main(){
int n, i, k;
printf("Enter maximum length of fibonacci
series\n");
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("%d ",fibonacci(i));
}
}

int fibonacci(int i){


if(i==0)
return 0;
else if(i==1)
return 1;
else
return (fibonacci(i-1)+fibonacci(i-2));

}
Output:

Q3). What are called and calling functions?


Ans:
Parent function which calls any function is known as
called function and the function which is being called is
known as calling function.
int main()
{
name_Func()
}
Here, name_Func() is called within the main() function,
so main() is called function, while name_Func() is calling
function.

Q4). Are exit () and return statements same in function


definition?
Ans:
No, both are different as we used exit() to immediately
exit from the program, where as return is used to return
the control of programs execution from the called
function to calling function.

Q5). When is the “void” keyword used in a function?


Ans:
When we declare the function we have to decide whether
we want some return value from the function or not, if
we only want to print some value or statements on the
screen we use void on the left side of function name
otherwise we place the data type of the value on the left
side of function name.

Q6). Differentiate between call by value and call by


reference.
Ans:
Factor Call by Value Call by Reference
In call by value actual In call by value
parameters are safe operations are
Safety because operations performed on actual
are performed on parameters so it is
formal parameter. not safe here.
Memory In this separate In this actual and
Location memory locations are Formal parameters
created for actual and share the same
formal parameters memory space.
In this copy of actual
In this actual
parameters are
Parameters parameters are
passed.
passed.

Q7). Explain rand() function in c. Write a program in c to


generate a random number.
Ans: The rand() function in c is used to generate a
random number.
#include <stdio.h>
int main()
{
int x,y;
for(x=1;x<=5;x++)
{
y=rand();
printf("%d\n",y);
}
return 0;
}

Output:

C interview questions on array and pointer

Q1). What is an array in C?


Ans:
An Array is a collection of similar types of elements i.e.
data having similar type of data type. Array takes
memory in contiguous fashion to store data. We cannot
change the size and type of arrays after its declaration.
Array are of two types:
One-dimensional array: One-dimensional array is an
array that stores the elements one after the another in
rowwise .
Syntax:
int arr[size];
Multidimensional array: Multidimensional array is a
collection of more than one one-dimensional array.
Syntax:
int arr[size][size];

Q2) What is a pointer in C?


Ans:
A pointer is a variable that contains the address of
another variable. We use variable of pointer type when
we want to store direct address of any variable’s memory
locaion.
For example:
int *p,i;
p = &i;
The above syntax show that p is a pointer variable. And p
can store the address of variable i.
One more things always keep in mind data type of
pointer variable and variable must be same. Pointer
variable can store only the similar type of datatype.
Example of pointer:
#include <stdio.h>
int main()
{
int *p;
int i=1;
p=&i;
printf("Address of 'i' variable is %p",p);
return 0;
}
Output:

Q3) What is a NULL pointer in C?


Ans:
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.

Q4) What is a far pointer in C?


Ans:
A pointer which can access all the 16 segments 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.

Q5) What is a dangling pointer in C?


Ans:
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.

Q6). What is Wild Pointers in C.


Ans: Such pointers in C which are Uninitialized in c code
are called Wild Pointers. In general these pointers are
pointing to the arbitrary memory location and cause
program to crash.

Q7) can a pointer access the array?


Ans:
Pointers can access the array by holding the base
address of the array.

8). Why a[5] == 5[a]?


Ans: As we know that
a[b] == *(a+b)
so
a[2] == *(a+2)
therefore,
2[a] = *(2+a)
Here is basically commutative law which is followed by it.

C interview questions on structure and unions

Q1) What is structure in C?


Ans:
The structure is a user-defined data type. Structure
allows to combine data items of different kinds. It
occupies the sum of the memory of all members in
structure. Structure members can be accessed only
through structure variables.
Syntax of structure
struct structure_name
{
variable1;
variable2
.
.
variable n;
}[structure variables];
Let’s see a simple example.
#include <stdio.h>
struct student
{
char name[5];
int roll_no;
}s1;
int main()
{
printf("Enter the name=");
scanf("%s",s1.name);
printf("Enter the roll_no=");
scanf("%d",&s1.roll_no);
printf("Name and Roll No of a student is:
%s,%d",s1.name,s1.roll_no);
return 0;
}
Output:

Q2). What is union in C?


Ans:
The union is also user-defined data type. Union allows to
combine data items of different kinds. Union doesn’t
occupy the sum of the memory of all members. It holds
only the memory of the largest member only. In union,
we can access only one variable at a time.It allocates one
common space for all the members of a union.
Syntax of union
struct union_name { variable1;
variable2; . . variable n;
}[union variables];
Let’s see a simple example.
#include<stdio.h>
#include<string.h>
union Employee
{
char name[20];
float salary;

} emp;

int main()
{
strcpy(emp.name, "Prakash");
emp.salary = 28000;

printf("name = %s\n", emp.name);


printf("salary = %.1f", emp.salary);
return 0;
}

Output:

Q3). Difference between malloc() and calloc() functions?


Ans:
Malloc() Calloc()
1. The term malloc()
1. The term malloc() stands
stands for contiguous
for memory allocation.
allocation.
2. It takes two arguments
2. It takes one argument,
i.e number of blocks and
that is, the number of bytes.
size of each block.
3.syntax of malloc(): 3.syntax of calloc():
void *malloc(size_t n); void *calloc(size_t n,
Where n indicates allocates size_t size);
bytes of memory. If the Allocates a contiguous
allocation succeeds, a void block of memory large
pointer to the allocated enough to hold n elements
memory is returned. of size bytes each. The
Otherwise, NULL is returned. allocated region is
initialized to zero.
4. It is somewhat slower
than malloc() as it takes
4. It is faster than calloc.
extra steps to initialize the
allocated memory by zero.

Q4). What do you mean by a Nested Structure?


struct Date
{
int birth_date;
int birth_month;
int birth_year;
};
struct personal_recod
{
char name[25];
struct Date birth_date;
float salary;
}person;

C interview questions on file handling and memory


allocation

Q1.) What is static memory allocation?


Ans:
In static memory allocation, memory is allocated during
compile time. And we cannot increase memory while
executing the program. Array use the static memory
allocation. lifetime of a variable in static memory is the
lifetime of the program. It applies to global variables, file
scope variables etc.The static memory is implemented
using stacks or heap.
For example: int arr[20]; The above example creates an
array of integer type, and the size of an array is fixed,
i.e., 20.

Q2) What is dynamic memory allocation?


Ans:
In dynamic memory allocation, memory is allocated at
runtime. We can increase memory while executing the
program. The malloc() or calloc() function is used to
allocate the memory at the runtime. Dynamic memory
allocation is used in linked list.
Basics of JAVA based Interview Questions
Q1). What do you understand by Class in Java?
Ans: A class is a blueprint from which objects are
created. WE can also define it as it is a group of objects
which have common properties. This properties is set by
class for all method and properties of class.
Class declaration have component mentioned
below:

 Class name
 Modifiers
 Interface
 Super Class

Class can Contains

 Methods
 Members
 Constructor
 Blocks
 Nested Class
 Nested Interface

Declaration of Class
class {
field;
method;
}

Q2 ). What do you understand by Object?


Ans : Object is a basic unit of OOPs. It is also an instance
of a class. Everything in OOPs is represented using
Objects.
In General we can define Object as it is a real world
entity that has its own some states and behaviour.
For Example: Cat is a suitable example of an objects.
Cat has its own states and behaviour and its is also a real
world entity.
Cat can walk, eat is its behaviour and Cat can be white,
black is its states.
Objects have some characteristics :
1). State : State Reflects the properties of Objects. Just
like Cat can be white, black or may be combination of
both is its properties. State can be denoted by attributes.
2). Behaviour : Behaviours shows that how object is
responding to other objects. Behaviour can be denoted
by Methods.
3). Identity: Every objects should have unique identity.
Like if we say cat then it may be a group of cat but If we
talk about a particular cat then we need a identity for
that particular cat.

Q3). Explain JDK, JVM and JRE.


JDK: JDK stands for Java Development Kit which
contains JRE. It gives a development environment for
Java applications where developer can code and run java
programs.
JRE: JRE Stands for Java Runtime Environment that
contains class libraries, loader class and JVM. Its main
function is to run Java Program. If you don’t want to
develop program then you don’t need JDK But, for only
the purpose of execution of java program you only need
JRE. JRE comes with JDK bundle you don’t need to
download it separately.
JVM: JVM stands for Java Virtual Machine that provide
the runtime environment to java code where Java code is
executed. JVM is a part of JRE that converts java byte
code into machine code. In java, compiler produces code
for JVM.

Q4). Explain Public Static void Main(String args[]) in


Java.
Ans: It is an entry point of any Java program from where
Execution starts.
Public: Public is a access modifier that define the
accessibility of method. If any method have Public access
modifier it means that it can access by any other class.
Static: static is a keyword in java that define class level
member. It means that without creating any instance it
can be accessible using class name.
void: void is also a keyword that define the return type
of any methods. If method have void keyword it means
that method will not return any value.
Main: It is a method from where execution starts. It is
searched by JVM to start the execution.
String args[]: it is a main method argument.

Q5). What is the different between Final, finally and


finilize?
Ans: Final:
final is a modifier which is used with classes, methods
and variables. If the class is declared as final then that
class is not extended by other class. If the method is
declared as final then we cannot override that method in
the child class. i.e. final method is not overridden by child
class. If the variable is declared as final then it behave as
a constant and we cannot re-assingment for that
variable.
finally:
finally is a block which is always associated with try-catch
block.finally block is always executed whether exception
is handled or not.finally block is used to execute
important code such as closing connection, stream when
any exception arise.
finalize();
finalize() method is used to perform cleanup operation
just before destroying any object. This finalize() method
is always invoked by garbage collector.

Q6). What is the difference between “==” and “equals()”


method.
Ans: “==” is used for address/reference comparison.
Example:
String str1=new String("prakash");
String str2=new String("prakash");
System.out.println(str1==str2);
output: false
equals() is used for content comparision.
Example:
String str1=new String("prakash");
String Str2=new String("prakash");
System.out.println(str1.equals(str2));
output: true

Q7). Why Java is called as platform independent ?


Ans: After the compilation of Java code, code is
converted into byte code. This byte code can be executed
in any other system and environment. Because of that it
is known as platform independent.
Q8). What is meant by Local variable and Instance
variable?
Ans:
Local variables are defined in the method and scope of
the variables that have existed inside the method itself.
An instance variable is defined inside the class and
outside the method and scope of the variables exist
throughout the class.

Oops Concept Interview Questions

Q1). Define Constructor.


Ans: We can define as constructor is a method or block
which is use to initialise the objects. Constructor should
have same name as a name of class which have no
return type. It is automatically called by java at the time
of object creation.
There are 3 types of constructor
1). Default constructor: It is automatically inserted by
Java when we not declared any constructor. It is not
visible in your source code.
2). Parameterised constructor : Constructor with
arguments are known as Parameterised constructor.
3). No-arg Constructor : it is very similar to default
constructor. We declare it when we want to perform
some operation at a time of object creation then we write
that code in no-args constructor. For example some
initialization of value.

Q2). Explain access modifiers in Java.


Ans: Access modifiers is a keywords in Java that define
the accessibility of any class, methods and member
variables.
There are 4 types of access modifiers in Java:-

 Public
 Private
 Protected
 Default

Modifier Default Private Protected Public


Same class YES YES YES YES
Same Package
YES NO YES YES
subclass
Same Package non-
YES NO YES YES
subclass
Different package
NO NO YES YES
subclass
Different package
NO NO NO YES
non-subclass

Q3). Explain some features of oops.


Ans:
Inheritance: Inheritance is process in which child
objects of child class acquires the all properties and
behaviour of its parent class. It improves the code
reusability.
Abstraction: Abstraction means hide the complexity and
show the functionality. For examples in education portal
you just sign up and then login by giving credential and
then access your dashboard but you won’t aware of how
its happening in backend. It is known as abstraction.
Encapsulation: Encapsulation is a process of binding the
data and methods together in a single entity known as
class for data safety.
Polymorphism: Polymorphism defines to perform single
actions in multiple form. It is derived from two word Poly
+ morphs that means many forms.
It is of two types:

 Method overloading
 Method Overriding

Q4). What is this and super keyword in Java?


Ans:
this : this is a keyword is use to access the member of
present class.
super : super keyword is used to access the member of
parent class.

Q5). What is the different between static and non-static


method of java?
Ans:
Static method: static method is a class level method.
We need not required any instance to access them we
can access it directly using class. A static method can
only access static variable.
non-static method: non-static method belongs to
objects of the class. It can be accessible inside the static
method with the help of class instance.

Q6). What do you mean by Polymorphism?


Polymorphism is derived from two greek word “poly” and
“morphs” means many form. It allows to perform single
task in multiple form. In Java term we can say that there
can be multiple methods with same name but different
functionality.
It is of two types:
1). Compile time polymorphism
2). Runtime Polymorphism
Compile time polymorphism is also known as method
overloading and Runtime polymorphism is known as
overriding.

Q7). Explain Method overloading and method overriding.


Ans:
Method overloading: In method overloading a class
have different methods with same name but different
number of arguments. In Overloading case methods
should have different signature. It is also known as
compile time polymorphism.
Method Overriding: In Method Overriding sub class
have similar method as parent class. Similar mean name,
return type, parameter of methods for both parent and
sub class method.

Q8). How many ways you can overload method?


Ans: There are various way to overload a method :
1) By number of passing parameters the valid case for
overloading the method is
add(int,int)
add(int,int,int)
2) By changing the data type of parameter
add(int,int)
add(float,int)
3) By changing the sequence of data type
add(int, float)
add(float,int)
Q9). What is the some invalid cases of method
overloading in java?
Ans: In java if two methods having the same name,
same parameters but different return type, then this is
not a valid method overloading. Also if two methods
having the same name, same parameters and different
return type, then this is also not a valid method
overloading. This will throw compilation error.
Example:
int sum(int,int)
float sum(int,int)

Q10). What do you mean by abstract class?


Ans: Abstract class is declared with the help of Abstract
Keyword. It can have both abstract and non-abstract
method. We cannot instantiate abstract method. It is
extended by another class which can implement its
methods to use. It can have static and final methods.

Q11). What do you mean by Interface?


Ans: Interface is a blueprint of class that have abstract
and public methods without body. Class that implements
interface should implement all methods of interface.
public interface Man {
public void eat();
public void sleep();
public void walk();
}
Interface Example to find square in java
interface DemoInterface{
public int square(int a);
}
public class Main implements DemoInterface{
public int square(int a){
return a*a;
}
public static void main(String[] args)
{
Main obj = new Main();
System.out.println(obj.square(2));
}
}

view raw
Interface program example in java.java hosted with
by GitHub
Output
4

Java String Interview Questions

Q1). Difference between String and StringBuffer.


Ans:
String: String object is immutable but the StringBuffer
objects are mutable. Immutable means once we create a
String object we cannot perform any changes on object.
Example of String:
String str=new String("prakash");
str.concat("kumar");
System.out.println(str);
output:- prakash

Example of StringBuffer:
StringBuffer strbfr=new StringBuffer("prakash");
strbfr.append("kumar");
System.out.println(strbfr);
output:- prakash kumar

Q2). Difference between StringBuffer and StringBuilder.


Ans: Both StringBuffer and StringBuilder are mutable.
StringBuffer:
All method of StringBuffer is synchronized. Its
performance is low because every task is dependent to
each other.
StringBuilder:
Methods are not synchronized. Its performance is high
because more than one thread can allowed.

Q3). Difference between String, StringBuilder, and


StringBuffer.
Factor String StringBuilder StringBuffer
Constant
Storage Area Heap Area Heap Area
String Pool
Mutability Immutable Mutable Mutable
Thread
Yes No Yes
Safety
Performance Fast More efficient Less efficient

Java Array & Collection Interview Questions

Q1). Difference between Array and Array List


Ans:
Array

 Array is fixed in size which is decided at a time of


array declaration.
 Array can contain both primitives data and objects.
ArrayList

 Size of ArrayList is dynamic.


 It is a part of collection framework of java.
 ArrayList can contain only object. After Java 5 It
converts primitive data into object itself.

Q2). What do you mean by Collections in Java.


Ans: Collection is a Java framework that have some
predefined class and interfaces to store and manipulate
the group of objects.
Interfaces comes with Collection framework:

 Set
 List
 Queue
 Dequeue

Classes comes with Collection framework:

 ArrayList
 LinkedList
 HashSet
 TreeSet
 LinkedHashSet etc.

Q3). Explain the lists that are present in Java Collection.


Ans:
Types of Lists are:
1). ArrayList

 Fast iteration and fast Random Access


 It is an ordered collection.
 It is not sorted collection.
Example:
import java.util.*;
public class Animal{
public static void main (String [ ] args){
ArrayList <String>names=new ArrayList <String>();
names.add ("Dog");
names.add ("Cat");
names.add ("Donkey");
names.add ("Cow");
System.out.println (names);
}
}
Output:
[Dog, Cat, Donkey, Cow]

2). Linked List

 Performance is slow than ArrayList.


 Maintain the Insertion Order.
 It can have duplicate values

import java.util.*;
public class Animal{
public static void main (String [ ] args){
Linkedlist <String>names=new Linkedlist <String>();
names.add ("Dog");
names.add ("Cat");
names.add ("Donkey");
names.add ("Cow");
System.out.println (names);
}
}
Output:
[Dog, Cat, Donkey, Cow]
3). Vector

 Similar as ArrayList.
 Maintain the Insertion Order.
 It can have duplicate values.
 Its Methods are Synchronized.

import java.util.*;
public class Animal{
public static void main (String [ ] args){
Vector <String>names=new Vector <String>();
names.add ("Dog");
names.add ("Cat");
names.add ("Donkey");
names.add ("Cow");
System.out.println (names);
}
}
Output:
[Dog, Cat, Donkey, Cow]

Q4). Explain the Set and their types in a Java Collection.


Ans: Set cares of uniqueness, It means that it does not
allow duplicate value.

Types of Set in Java Collection are:

1). Hash Set

 HashSet is unordered and unsorted.


 It uses the hash code of the object to insert the
values.
 We can use Hash Set when order is not concerned
and we want no duplicate value.

Example:
import java.util.*;
public class Animal{
public static void main (String [ ] args){
HashSet <String>names=new HashSet <String>();
names.add ("Dog");
names.add ("Cat");
names.add ("Donkey");
names.add ("Cow");
names.add ("Dog");
System.out.println (names);
}
}
Output:
[Dog, Cat, Donkey, Cow]

2). Linked Hash set

 It maintains the insertion order.


 Does not allows duplicate value.
 It can be used when iteration order is required.

import java.util.*;
public class Animal{
public static void main (String [ ] args){
LinkedHashSet <String>names=new LinkedHashSet
<String>();
names.add ("Dog");
names.add ("Cat");
names.add ("Donkey");
names.add ("Cow");
names.add ("Dog");
System.out.println (names);
}
}
Output:
[Dog, Cat, Donkey, Cow]

3). Tree Set

 It sorts the elements in ascending order.


 It does not allow duplicate values.

import java.util.*;
public class Animal{
public static void main (String [ ] args){
TreeSet <String>names=new TreeSet <String>();
names.add ("Dog");
names.add ("Cat");
names.add ("Donkey");
names.add ("Cow");
names.add ("Dog");
System.out.println (names);
}
}
Output:
[Dog, Cat, Donkey, Cow]

Q5). Difference between HashMap and HashTable


Ans:
HashMap HashTable
1. HashMap is non
1. HashTable is synchronized
synchronized
2. HashMap allows NULL 2. HashTable does not allows
Key and Value. any NULL Key and Value.
3. Performance of
3. HashTable is slow.
HashMap is fast.
4. HashMap inherits 4. HashTable inherits class
class AbstractMap. Dictionary.
5. We can traverse 5. We can traverse HashTable
HashMap using Iterator. using Iterator and Enumerator.

Q6). Difference between HashSet and TreeSet.


Ans:
HashSet TreeSet
1. HashSet is faster and 1. TreeSet is little bit slower
gives better performace. than HashSet.
2. HashSet performs 2. TreeSet performs
operation in constant time operation in Log(n) time.
3. HashSet does not follow 3. TreeSet elements are
any order arranged in ascending order.
4. HashSet does not hold 4. TreeSet also does not
duplicate value. hold duplicate value.
SQL interview questions
Q1). What is SQL and MySQL?
Ans:
SQL stands for Structured Query Language. This query
language is used to maintain and manage a database.
SQL comes with various syntax to perform database
operations like retrieving, managing, adding, or
manipulating data.

MySQL is a relational database management system


developed in 1995 by MySQL AB. It uses SQL queries to
perform operations on the database. MySQL
allows us to handle, store, modify and delete data and
store data in an organized way.

Q2). What are the subset of SQL?


Ans:
There are three main subsets of the SQL language:

 Data Control Language (DCL)


 Data Definition Language (DDL)
 Data Manipulation Language (DML)

Q3). What is DDL?


Ans:
DDL stands for Data Definition Language, consists
some SQL commands that is used to define data
structures such as to create, alter, or drop tables. List of
DDL Commands are CREATE, DROP, ALTER, TRUNCATE,
COMMENT, RENAME.
Q4). What is DML?
Ans:
DML Stands for Data Manipulation Language, Consists
the SQL commands that is used for data manipulation in
database. Some DML Statements are SELECT, INSERT,
UPDATE, DELETE, MERGE, CALL, LOCK TABLE.

Q5). What is DCL?


Ans:
DCL Stands for Data Control Language, Consists the
SQL commands that is used for permission, rights and
other control in database. Some DCL commands are
GRANT and REVOKE.

Q6) What is TCL?


Ans:
TCL stands for Transaction Control Language, Consist
the SQL commands that deals with transactions within
database. Some TCL commands are COMMIT, ROLLBACK,
SAVEPOINT, SET TRANSACTION.

Q7). What is Table and Fields in SQL?


Ans :
Table is used to store data in a RDMS that contains rows
and columns where data is stored.
In Table, The rows are known as records and the
columns are known as fields.

Q8) Tell some list of Constraints in SQL.


Ans:
SQL constraint is a rule on the data in a table that limit
the data that can go into a table on a given condition.
Constraints can be applied to table labels and column
labels.
Some List of SQL constraints are
NOT NULL – This constraint ensures no NuLL value can
be added to the Column.
PRIMARY KEY – Primary Key Uniquely Identify each row
in a table it can’t be duplicated. It is a combination of
NOT NULL and UNIQUE.
UNIQUE – This constraint ensure unique value in a given
column. Unique key can have a NULL value.

Q9) What is Primary Key in table?


Ans:
Primary Key Uniquely Identify each row in a table it can’t
be duplicated. It is a combination of NOT NULL and
UNIQUE.
Syntax
CREATE TABLE EMPLOYEE(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
SALARY DECIMAL (10, 2),
PRIMARY KEY (ID)
);

Q10) What is Foreign Key?


Ans:
A FOREIGN KEY is a field in a table that links to the
Primary Key of another table. We can also say it is a
constraint that is used to prevent actions that might
destroy the links between tables.
The table has a primary key known as the parent table
and a table with a foreign key known as the child table.
For example
To demonstrate the Foreign key we have to create two
tables one will be Primary and Second will be child Table.
And there will be one Common Column in both the
tables.
CREATE TABLE Class (
ClassID int NOT NULL,
StudentID int,
PRIMARY KEY (ClassID),
FOREIGN KEY (StudentID) REFERENCES Student(S
tudentID)
);

Q11) What is Unique Key?


Ans:
UNIQUE Key Constraint in a column ensures all values
are different.
It is similar to Primary Key only the difference is UNIQUE
key constraints allow NULL value and a table can have
multiple UNIQUE Key .
CREATE TABLE Student (
ID int NOT NULL UNIQUE,
Name varchar(255) NOT NULL,
Age int
);

Q12) Tell the difference between Primary Key and Unique


Key.
Ans:

 Primary Key won’t allow NULL value But Unique Key


allows NULL Value.
 The table can have only one Primary Key But More
than one unique Key.
 Primary Key supports auto-increment whereas
Unique Key won’t support auto increments.
 The primary key creates clustered index on selection
but Unique Key creates a non-clustered index.
 The primary Key value cannot be changed or
modified but the Unique key value can be changed.

Q13). What is Join in SQL?


Ans:
Join is an operation to combine two or more tables to
fetch the rows or data on the given conditions. Suppose
we are stored data in multiple tables that are linked with
Foreign Key.
Now when we have to fetch the data, we will have to join
the table in order to fetch the required information from
all the tables.
To Perform Join, A common field should be present in
both tables.

Q14) Tell some different types of Join.


Ans:
There are different types of Join listed below
INNER JOIN: INNER Join will return information from
both tables if the condition is matched.
LEFT JOIN: LEFT Join will return all information from the
left table and only match data from the right table.
RIGHT JOIN: RIGHT Join will return all information from
the right table and only match data from the left table.
FULL JOIN: Full Join will return all information either
from left or right for matched conditions.
SELF JOIN :
CARTESIAN JOIN: CARTESIAN JOIN also known as
CROSS JOIN, is used to combine each row of the first
table with each row of the second table.

Q15). What is Cross-Join?


Ans:
CROSS JOIN also known as CARTESIAN JOIN, is used to
combine each row of the first table with each row of the
second table.
Syntax of CROSS-JOIN
SELECT column_name(s), column_name(p)
FROM table1 CROSS JOIN table2;

Q16). What is Normalization?


Ans:
Normalization is a process to reduce the data duplication
in the large table by breaking it into smaller tables and
linking them using relationships.
Normalizations also eliminate undesirable characteristics
like Insertion, Update, and Deletion Anomalies.
Types of Normal forms are
1). 1 NF
2). 2NF
3). 3NF
4). BCNF
5). 4NF
6). 5NF

Q17). What is denormalization?


Ans:
Denormalization is a process in which we add some
redundant data to the table to get rid of the complex join
operation. In normalization operation, we break the large
table into the smaller table. This increase the execution
time to get the data after performing multiple joins on
the table. To get rid of this we do denormalization to
increase the execution time.

Q18). What are the different types of SQL operators?


Ans:
SQL has some special keywords to perform some specific
operations known as SQL Operators. Mostly these
operators are used in the WHERE clause of SQL
commands.
Below are the list of SQL operators :
Arithmetic Operators to perform mathematical operations

 addition (+)
 subtraction (-)
 multiplication (*)
 division (/)
 remainder/modulus (%)

Comparison Operators to perform comparisons


operations

 equal to (=)
 not equal to (!= or <>)
 less than (<),
 greater than (>)
 less than or equal to (<=)
 greater than or equal to (>=)
 not less than (!<)
 not greater than (!>)

Logical Operators to evaluate the expressions


 ALL
 AND
 ANY
 ISNULL
 EXISTS
 BETWEEN
 IN
 LIKE
 NOT
 OR
 UNIQUE

Bitwise Operators to perform operations on bits

 AND (& symbol)


 OR (|, ^)
 NOT (~)

Q19). Tell some clauses used with Select Query.


Ans:
List of clauses used with Select Query are

 SELECT
 FROM
 WHERE
 GROUP BY
 HAVING
 ORDER BY
 OFFSET
 FETCH FIRST
 UNION
 INTERSECT
 EXCEPT
 WITH
Q20). What is SET Operators ? Explain UNION, UNION
ALL, Minus and Intersect commands?
Ans:
UNION : UNION Command is used to combine the result
of two select queries and make it one. To Perform the
UNION Operation, Select query should have similar field
and also the data type of the all field should be similar.
Here Duplicate rows will be eliminated
Syntax:
SELECT (coloumn) from table1 [WHERE condition]
UNION SELECT (coloumn) from table2 [WHERE
condition];
UNION ALL: UNION ALL is similar to UNION the only
difference is, UNION ALL can’t eliminate the duplicate
value.
Syntax:
SELECT (coloumn) from table1 [WHERE condition]
UNION ALL SELECT (coloumn) from table2 [WHERE
condition];
MINUS : MINUS Command returns the result only from
the first select query which is not available in second
select query. In MINUS Operation, Select query should
have similar field and also the data type of the all field
should be similar.
SELECT (coloumn) from table1 [WHERE condition]
MINUS SELECT (coloumn) from table2 [WHERE
condition];
INTERSECT : INTERSECT Command is used to return
only common data as a result from two select queries.
Intersection operation always returns the distinct rows.
SELECT (coloumn) from table1[WHERE condition]
INTERSECT SELECT (coloumn) from table2 [WHERE
condition];
Q21). What is Cursor in SQL?
Ans:
A Cursor in SQL is a Temporary Memory or temporary
work area which is used when a DML operation is
performed on the table.
There are two types of Cursor
1. Implicit Cursor
2. Explicit Cursor

Q22). What is Trigger in SQL?


Ans:
A trigger is a set of SQL statements that is called
automatically whenever a database event occurs.
Triggers are associated with tables. The trigger can be
called when any row is inserted into the table or we
updated any column value.
The trigger is useful in a scenario to suppose in Student
Report Database students marks are recorded. Now we
want to suppose whenever a new record is the total and
average of specified marks should automatically insert.

Trigger Syntax

CREATE TRIGGER schema.trigger_name


ON table_name
AFTER {INSERT, UPDATE, DELETE}
NOT FOR REPLICATION]
AS
{SQL_Statements}

Q23). What is Alias in SQL?


Ans:
Alias is a temporary name given to a table or a column in
a table. With the help of AS keywords alias is created and
it only exists for the duration of that query.
Syntax of alias
SELECT column_name AS alias_name
FROM table_name;

Q24). What is View in SQL?


Ans:
In SQL, View is a virtual table that also contains rows and
columns. To create View, we use CREATE
VIEW statement. View can be created from one or many
tables which depends on the written SQL query to create
a view.

CREATE VIEW view_name ASSELECT column1,


column2.....FROM table_nameWHERE [condition];
Types of View are

 Simple View
 Complex View
 Inline View
 Materialized View

Q25). Differences between views and tables


Ans:

 A View is a virtual table extracted from a database


whereas table is real with rows and columns.
 View depends on the table but the Table is an
independent object.
 View is used to extract data from a table whereas
Table is used to store data.
 View Don’t allow to add, update or delete any data
from view But In the table, we can perform this
operation.
 View Doesn’t occupy space in the system but the
Table occupies the space in System.

Q26). What is IN operator?


Ans:
The IN operator allows us to use multiple values in a
WHERE clause. Instead of using multiple OR we can use
IN Operator.
Syntax
WHERE column IN (value1, value2, ...);
Suppose we need the Details of Student that have Roll
Number 1, 3, 4, 7, Our Query will be
SELECT SId, FirstName, LastName, MarksFROM
StudentWHERE SId IN (1, 3, 4, 7)

Q27). What is Between Operator?


Ans:
BETWEEN operator is used to define the range to select
the output. This range can apply on numbers, text, or
dates.
Syntax
SELECT column(s)
FROM table
WHERE column BETWEEN value1 AND value2;
Query Example
SELECT * FROM Student
WHERE RollNo BETWEEN 1 AND 3;

Q28). What are Aggregate functions?


Ans:
In SQL, Aggregate functions is used to perform operation
on multiple values to get a result in a single value. For
example sum of marks obtained by all student in a table.
Here we will use aggregate function.
Some Aggregate Functions are

 Count()
 Sum()
 Avg()
 Min()
 Max()
 FIRST()
 LAST()

29). What is the difference between DELETE and


TRUNCATE Statement in SQL.
Ans:

 DELETE command is used to delete specific rows


whereas Truncate Command is used to delete all
rows from a table.
 With DELETE Command we can use the WHERE
clause But With TRUNCATE we can’t use the WHERE
Clause.
 DELETE Command Lock the table row before deleting
Whereas TRUNCATE Command Lock the entire table.
 DELETE Command is slower as compared to
TRUNCATE Command.
 DELETE Command can be rollback But Truncate can’t
roll back

30). What is the difference between DROP and


TRUNCATE Statement in SQL.
Ans:
 DROP command removes the table definition and its
contents But the TRUNCATE command only removes
the content, not the table definition.
 DROP command frees the memory after deletion But
the TRUNCATE command does not free the memory.
 DROP Command removes integrity constraints from
the table But the TRUNCATE command Won’t.
 DROP Command also deletes the table structure But
TRUNCATE Command Keeps the Table Structure
safe.

31). What is DISTINCT Keyword?


Ans:
DISTINCT keyword is used with the SELECT statement to
fetch only unique records. It eliminates the duplicate
values if any are available in Colum.
Suppose the Name of students may be common in the
Student table. But if we want only the unique name then
we can use DISTINCT Keyword with select Query.
Syntax
SELECT DISTINCT column1, column2
FROM table;
Example
SELECT DISTINCT Name FROM Student;

32). What is Order By clause?


Ans:
ORDER By Clause in SQL is used to sort the result either
in ascending order or descending order.
ORDER BY ASC
This is used to sort output in ascending order.
Syntax
ORDER BY age ASC;
ORDER BY DESC
This is used to sort output in descending order.
Syntax
SELECT *
FROM Customers
ORDER BY age DESC;

33). Tell the difference between WHERE & HAVING


clause.
Ans:

 WHERE Clause is used to filter the rows from the


table on given conditions whereas the HAVING
clause is used to filter groups instead of one row at a
time.
 We can use the WHERE Clause without GROUP BY
Clause but Having clause can’t be used without
GROUP BY clause.
 Where Clause can be used with Select, update, and
delete statements but Having Clause can be used
with Select only.
 WHERE Clause can be used before GROUP BY Clause
But Having Clause can be used after GROUP BY
Clause.

34). What is FLOOR function used in SQL?


Ans:
The FLOOR() function finds the largest integer value to a
given number, which can be an equal or lesser number.
Example
SELECT FLOOR(21.55) AS FloorValue;

35). What is the COALESCE function?


Ans:
The COALESCE function returns the first non-null value from the
input.
Syntax
SELECT COALESCE(val1, val2, val3,……, nth );
Example
SELECT COALESCE(NULL, 1, 2, ‘sql’);

You might also like