Java Interview Questions
Java Interview Questions
Java language was developed in such a way that it does not depend on any hardware
or software due to the fact that the compiler compiles the code and then converts
it to platform-independent byte code which can be run on multiple systems.
The only condition to run that byte code is for the machine to have a runtime
environment (JRE) installed in it
2. Why is Java not a pure object oriented language?
Java supports primitive data types - byte, boolean, char, short, int, float, long,
and double and hence it is not a pure object oriented language.
3. Difference between Heap and Stack Memory in java. And how java utilizes this.
Stack memory is the portion of memory that was assigned to every individual
program. And it was fixed. On the other hand, Heap memory is the portion that was
not allocated to the java program but it will be available for use by the java
program when it is required, mostly during the runtime of the program.
When we write a java program then all the variables, methods, etc are stored in the
stack memory.
And when we create any object in the java program then that object was created in
the heap memory. And it was referenced from the stack memory.
Example- Consider the below java program:
class Main {
public void printArray(int[] array){
for(int i : array)
System.out.println(i);
}
public static void main(String args[]) {
int[] array = new int[10];
printArray(array);
}
}
For this java program. The stack and heap memory occupied by java is -
Main and PrintArray is the method that will be available in the stack area and as
well as the variables declared that will also be in the stack area.
And the Object (Integer Array of size 10) we have created, will be available in the
Heap area because that space will be allocated to the program during runtime.
Download PDF
All the objects of the class will have their copy of the variables for utilization.
If any modification is done on these variables, then only that instance will be
impacted by it, and all other class instances continue to remain unaffected.
Example:
class Athlete {
public String athleteName;
public double athleteSpeed;
public int athleteAge;
}
Local variables are those variables present within a block, function, or
constructor and can be accessed only inside them. The utilization of the variable
is restricted to the block scope. Whenever a local variable is declared inside a
method, the other class methods don’t have any knowledge about the local variable.
Example:
8. What are the default values assigned to variables and instances in java?
There are no default values assigned to the variables in java. We need to
initialize the value before using it. Otherwise, it will throw a compilation error
of (Variable might not be initialized).
But for instance, if we create the object, then the default value will be
initialized by the default constructor depending on the data type.
If it is a reference, then it will be assigned to null.
If it is numeric, then it will assign to 0.
If it is a boolean, then it will be assigned to false. Etc.
9. What do you mean by data encapsulation?
Data Encapsulation is an Object-Oriented Programming concept of hiding the data
attributes and their behaviours in a single unit.
It helps developers to follow modularity while developing software by ensuring that
each object is independent of other objects by having its own methods, attributes,
and functionalities.
It is used for the security of the private properties of an object and hence serves
the purpose of data hiding.
11. Can you tell the difference between equals() method and equality operator (==)
in Java?
We are already aware of the (==) equals operator. That we have used this to compare
the equality of the values. But when we talk about the terms of object-oriented
programming, we deal with the values in the form of objects. And this object may
contain multiple types of data. So using the (==) operator does not work in this
case. So we need to go with the .equals() method.
Both [(==) and .equals()] primary functionalities are to compare the values, but
the secondary functionality is different.
So in order to understand this better, let’s consider this with the example -
System.out.println(str1 == str2);
This code will print true. We know that both strings are equals so it will print
true. But here (==) Operators don’t compare each character in this case. It
compares the memory location. And because the string uses the constant pool for
storing the values in the memory, both str1 and str2 are stored at the same memory
location. See the detailed Explanation in Question no 73: Link.
Then in this case, it will print false. Because here no longer the constant pool
concepts are used. Here, new memory is allocated. So here the memory address is
different, therefore ( == ) Operator returns false. But the twist is that the
values are the same in both strings. So how to compare the values? Here
the .equals() method is used.
.equals() method compares the values and returns the result accordingly. If we
modify the above code with -
System.out.println(str1.equals(str2));
Then it returns true.
equals() ==
This is a method defined in the Object class. It is a binary operator in Java.
The .equals() Method is present in the Object class, so we can override our
custom .equals() method in the custom class, for objects comparison. It cannot be
modified. They always compare the HashCode.
This method is used for checking the equality of contents between two objects as
per the specified business logic. This operator is used for comparing addresses
(or references), i.e checks if both the objects are pointing to the same memory
location.
Note:
In the cases where the equals method is not overridden in a class, then the class
uses the default implementation of the equals method that is closest to the parent
class.
Object class is considered as the parent class of all the java classes. The
implementation of the equals method in the Object class uses the == operator to
compare two objects. This default implementation can be overridden as per the
business logic.
12. How is an infinite loop declared in Java?
Infinite loops are those loops that run infinitely without any breaking conditions.
Some examples of consciously declaring infinite loop is:
Three constructors are defined here but they differ on the basis of parameter type
and their numbers.
class InterviewBit{
String department;
String service;
InterviewBit(InterviewBit ib){
this.departments = ib.departments;
this.services = ib.services;
}
}
Here we are initializing the new object value from the old object value in the
constructor. Although, this can also be achieved with the help of object cloning.
class Main {
public static void main(String args[]) {
System.out.println(" Main Method");
}
public static void main(int[] args){
System.out.println("Overloaded Integer array Main Method");
}
public static void main(char[] args){
System.out.println("Overloaded Character array Main Method");
}
public static void main(double[] args){
System.out.println("Overloaded Double array Main Method");
}
public static void main(float args){
System.out.println("Overloaded float Main Method");
}
}
16. Comment on method overloading and overriding by citing relevant examples.
In Java, method overloading is made possible by introducing different methods in
the same class consisting of the same name. Still, all the functions differ in the
number or type of parameters. It takes place inside a class and enhances program
readability.
The only difference in the return type of the method does not promote method
overloading. The following example will furnish you with a clear picture of it.
class OverloadingHelp {
public int findarea (int l, int b) {
int var1;
var1 = l * b;
return var1;
}
public int findarea (int l, int b, int h) {
int var2;
var2 = l * b * h;
return var2;
}
}
Both the functions have the same name but differ in the number of arguments. The
first method calculates the area of the rectangle, whereas the second method
calculates the area of a cuboid.
Method overriding is the concept in which two methods having the same method
signature are present in two different classes in which an inheritance relationship
is present. A particular method implementation (already present in the base class)
is possible for the derived class by using method overriding.
Let’s give a look at this example:
class HumanBeing {
public int walk (int distance, int time) {
int speed = distance / time;
return speed;
}
}
class Athlete extends HumanBeing {
public int walk(int distance, int time) {
int speed = distance / time;
speed = speed * 2;
return speed;
}
}
Both class methods have the name walk and the same parameters, distance, and time.
If the derived class method is called, then the base class method walk gets
overridden by that of the derived class.
17. A single try block and multiple catch blocks can co-exist in a Java Program.
Explain.
Yes, multiple catch blocks can exist but specific approaches should come prior to
the general approach because only the first catch block satisfying the catch
condition is executed. The given code illustrates the same:
18. Explain the use of final keyword in variable, method and class.
In Java, the final keyword is used as defining something as constant /final and
represents the non-access modifier.
final variable:
When a variable is declared as final in Java, the value can’t be modified once it
has been assigned.
If any value has not been assigned to that variable, then it can be assigned only
by the constructor of the class.
final method:
A method declared as final cannot be overridden by its children's classes.
A constructor cannot be marked as final because whenever a class is inherited, the
constructors are not inherited. Hence, marking it final doesn't make sense. Java
throws compilation error saying - modifier final not allowed here
final class:
No classes can be inherited from the class declared as final. But that final class
can extend other classes for its usage.
19. Do final, finally and finalize keywords have the same function?
All three keywords have their own utility while programming.
Final: If any restriction is required for classes, variables, or methods, the final
keyword comes in handy. Inheritance of a final class and overriding of a final
method is restricted by the use of the final keyword. The variable value becomes
fixed after incorporating the final keyword. Example:
Finally: It is the block present in a program where all the codes written inside it
get executed irrespective of handling of exceptions. Example:
try {
int variable = 5;
}
catch (Exception exception) {
System.out.println("Exception occurred");
}
finally {
System.out.println("Execution of finally block");
}
Finalize: Prior to the garbage collection of an object, the finalize method is
called so that the clean-up activity is implemented. Example:
Parent(){
System.out.println("Parent class default constructor.");
}
Parent(String x){
System.out.println("Parent class parameterised constructor.");
}
Child(){
//super constructor call should always be in the first line
// super(); // Either call default super() to call default
parent constructor OR
super("Call Parent"); // call parameterised super to call
parameterised parent constructor.
System.out.println("Child class default Constructor");
}
void printNum(){
System.out.println(num);
System.out.println(super.num); //prints the value of num of parent class
}
@Override
public void foo(){
System.out.println("Child class foo!");
super.foo(); //Calls foo method of Parent class inside the Overriden
foo method of Child class.
}
}
Because there must be only 1 main method in the java program as the execution
starts from the main method. So for this reason the main method is static.
This ensures that the memory resource is used efficiently, but it provides no
guarantee that there would be sufficient memory for the program execution.
28. What is a ClassLoader?
Java Classloader is the program that belongs to JRE (Java Runtime Environment). The
task of ClassLoader is to load the required classes and interfaces to the JVM when
required.
Example- To get input from the console, we require the scanner class. And the
Scanner class is loaded by the ClassLoader.
29. What part of memory - Stack or Heap - is cleaned in garbage collection process?
Heap.
Example -
class Rectangle{
int length = 5;
int breadth = 3;
}
Object for this Rectangle class - Rectangle obj1 = new Rectangle();
Shallow copy - The shallow copy only creates a new reference and points to the same
object. Example - For Shallow copy, we can do this by -
Rectangle obj2 = obj1;
Now by doing this what will happen is the new reference is created with the name
obj2 and that will point to the same memory location.
Deep Copy - In a deep copy, we create a new object and copy the old object value to
the new object. Example -
Rectangle obj3 = new Rectangle();
Obj3.length = obj1.length;
Obj3.breadth = obj1.breadth;
Both these objects will point to the memory location as stated below -
Now, if we change the values in shallow copy then they affect the other reference
as well. Let's see with the help of an example -
class Rectangle
{
int length = 5;
int breadth = 3;
}
public class Main
{
public static void main(String[] args) {
Rectangle obj1 = new Rectangle();
//Shallow Copy
Rectangle obj2 = obj1;
}
}
Output -
Now, if we change the code to deep copy, then there will be no effect on object2 if
it is of type deep copy. Consider some snippets to be added in the above code.
class Rectangle
{
int length = 5;
int breadth = 3;
}
public class Main
{
public static void main(String[] args) {
Rectangle obj1 = new Rectangle();
//Shallow Copy
Rectangle obj2 = new Rectangle();
obj2.length = obj1.length;
obj2.breadth = obj1.breadth;
}
}
The above snippet will not affect the object2 values. It has its separate values.
The output will be
The clone() will do this deep copy internally and return a new object. And to do
this we need to write only 1 line of code. That is - Rectangle obj2 = obj1.clone();
String Pool: Designers of Java were aware of the fact that String data type is
going to be majorly used by the programmers and developers. Thus, they wanted
optimization from the beginning. They came up with the notion of using the String
pool (a storage area in Java heap) to store the String literals. They intended to
decrease the temporary String object with the help of sharing. An immutable class
is needed to facilitate sharing. The sharing of the mutable structures between two
unknown parties is not possible. Thus, immutable Java String helps in executing the
concept of String Pool.
Consider the water jug in the office and if every employee wants that water then
they will not create a new water jug for drinking water. They will use the existing
one with their own reference as a glass. So programmatically it should be
implemented as -
class WaterJug{
private int waterQuantity = 500;
private WaterJug(){}
private WaterJug object = null;
When singletons are written with double-checked locking, they can be thread-safe.
We can use static singletons that are initialized during class loading. Like we did
in the above example.
But the most straightforward way to create a thread-safe singleton is to use Java
enums.
33. Which of the below generates a compile-time error? State the reason.
int[] n1 = new int[0];
boolean[] n2 = new boolean[-200];
double[] n3 = new double[2241423798];
char[] ch = new char[20];
We get a compile-time error in line 3. The error we will get in Line 3 is - integer
number too large. It is because the array requires size as an integer. And Integer
takes 4 Bytes in the memory. And the number (2241423798) is beyond the capacity of
the integer. The maximum array size we can declare is - (2147483647).
Because the array requires the size in integer, none of the lines (1, 2, and 4)
will give a compile-time error. The program will compile fine. But we get the
runtime exception in line 2. The exception is - NegativeArraySizeException.
Here what will happen is - At the time when JVM will allocate the required memory
during runtime then it will find that the size is negative. And the array size
can’t be negative. So the JVM will throw the exception.
Comparator is the interface in java that contains the compare method. And by
overloading the compare method, we can define that on what basis we need to compare
the values.
The phenomenon mentioned here is popularly known as method hiding, and overriding
is certainly not possible. Private method overriding is unimaginable because the
visibility of the private method is restricted to the parent class only. As a
result, only hiding can be facilitated and not overriding.
Implementation: For a HashSet, the hash table is utilized for storing the elements
in an unordered manner. However, TreeSet makes use of the red-black tree to store
the elements in a sorted manner.
Complexity/ Performance: For adding, retrieving, and deleting elements, the time
amortized complexity is O(1) for a HashSet. The time complexity for performing the
same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the
performance of HashSet is faster in comparison to TreeSet.
Methods: hashCode() and equals() are the methods utilized by HashSet for making
comparisons between the objects. Conversely, compareTo() and compare() methods are
utilized by TreeSet to facilitate object comparisons.
Objects type: Heterogeneous and null objects can be stored with the help of
HashSet. In the case of a TreeSet, runtime exception occurs while inserting
heterogeneous objects or null objects.
40. Why is the character array preferred over string for storing confidential
information?
In Java, a string is basically immutable i.e. it cannot be modified. After its
declaration, it continues to stay in the string pool as long as it is not removed
in the form of garbage. In other words, a string resides in the heap section of the
memory for an unregulated and unspecified time interval after string value
processing is executed.
42. What are the differences between JVM, JRE and JDK in Java?
Criteria JDK JRE JVM
Abbreviation Java Development Kit Java Runtime Environment Java Virtual
Machine
Definition JDK is a complete software development kit for developing Java
applications. It comprises JRE, JavaDoc, compiler, debuggers, etc. JRE is a
software package providing Java class libraries, JVM and all the required
components to run the Java applications. JVM is a platform-dependent, abstract
machine comprising of 3 specifications - document describing the JVM implementation
requirements, computer program meeting the JVM requirements and instance object for
executing the Java byte code and provide the runtime environment for execution.
Main Purpose JDK is mainly used for code development and execution. JRE is
mainly used for environment creation to execute the code. JVM provides
specifications for all the implementations to JRE.
Tools provided JDK provides tools like compiler, debuggers, etc for code
development JRE provides libraries and classes required by JVM to run the program.
JVM does not include any tools, but instead, it provides the specification
for implementation.
Summary JDK = (JRE) + Development tools JRE = (JVM) + Libraries to execute
the application JVM = Runtime environment to execute Java byte code.
43. What are the differences between HashMap and HashTable in Java?
HashMap HashTable
HashMap is not synchronized thereby making it better for non-threaded applications.
HashTable is synchronized and hence it is suitable for threaded applications.
Allows only one null key but any number of null in the values. This does not
allow null in both keys or values.
Supports order of insertion by making use of its subclass LinkedHashMap. Order
of insertion is not guaranteed in HashTable.
44. What is the importance of reflection in Java?
The term reflection is used for describing the inspection capability of a code on
other code either of itself or of its system and modify it during runtime.
Consider an example where we have an object of unknown type and we have a method
‘fooBar()’ which we need to call on the object. The static typing system of Java
doesn't allow this method invocation unless the type of the object is known
beforehand. This can be achieved using reflection which allows the code to scan the
object and identify if it has any method called “fooBar()” and only then call the
method if needed.
Method methodOfFoo = fooObject.getClass().getMethod("fooBar", null);
methodOfFoo.invoke(fooObject, null);
Using reflection has its own cons:
Speed — Method invocations due to reflection are about three times slower than the
direct method calls.
Type safety — When a method is invoked via its reference wrongly using reflection,
invocation fails at runtime as it is not detected at compile/load time.
Traceability — Whenever a reflective method fails, it is very difficult to find the
root cause of this failure due to a huge stack trace. One has to deep dive into the
invoke() and proxy() method logs to identify the root cause.
Hence, it is advisable to follow solutions that don't involve reflection and use
this method as a last resort.
45. What are the different ways of threads usage?
We can define and implement a thread in java using two ways:
Extending the Thread class
class InterviewBitThreadExample extends Thread{
public void run(){
System.out.println("Thread runs...");
}
public static void main(String args[]){
InterviewBitThreadExample ib = new InterviewBitThreadExample();
ib.start();
}
}
Implementing the Runnable interface
class InterviewBitThreadExample implements Runnable{
public void run(){
System.out.println("Thread runs...");
}
public static void main(String args[]){
Thread ib = new Thread(new InterviewBitThreadExample());
ib.start();
}
}
Implementing a thread using the method of Runnable interface is more preferred and
advantageous as Java does not have support for multiple inheritances of classes.
start() method is used for creating a separate call stack for the thread execution.
Once the call stack is created, JVM calls the run() method for executing the thread
in that call stack.
46. What are the different types of Thread Priorities in Java? And what is the
default priority of a thread assigned by JVM?
There are a total of 3 different types of priority available in Java.
In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default
priority for any thread is NORM_PRIORITY assigned by JVM.
47. What is the difference between the program and the process?
A program can be defined as a line of code written in order to accomplish a
particular task. Whereas the process can be defined as the programs which are under
execution.
A program doesn't execute directly by the CPU. First, the resources are allocated
to the program and when it is ready for execution then it is a process.
48. What is the difference between the ‘throw’ and ‘throws’ keyword in java?
The ‘throw’ keyword is used to manually throw the exception to the calling method.
And the ‘throws’ keyword is used in the function definition to inform the calling
method that this method throws the exception. So if you are calling, then you have
to handle the exception.
Example -
class Main {
public static int testExceptionDivide(int a, int b) throws ArithmeticException{
if(a == 0 || b == 0)
throw new ArithmeticException();
return a/b;
}
public static void main(String args[]) {
try{
testExceptionDivide(10, 0);
}
catch(ArithmeticException e){
//Handle the exception
}
}
}
Here in the above snippet, the method testExceptionDivide throws an exception. So
if the main method is calling it then it must have handled the exception.
Otherwise, the main method can also throw the exception to JVM.
And the method testExceptionDivide 'throws’ the exception based on the condition.
49. What are the differences between constructor and method of a class in Java?
Constructor Method
Constructor is used for initializing the object state. Method is used for
exposing the object's behavior.
Constructor has no return type. Method should have a return type. Even if it
does not return anything, return type is void.
Constructor gets invoked implicitly. Method has to be invoked on the object
explicitly.
If the constructor is not defined, then a default constructor is provided by the
java compiler. If a method is not defined, then the compiler does not provide
it.
The constructor name should be equal to the class name. The name of the method
can have any name or have a class name too.
A constructor cannot be marked as final because whenever a class is inherited, the
constructors are not inherited. Hence, marking it final doesn't make sense. Java
throws compilation error saying - modifier final not allowed here A method can
be defined as final but it cannot be overridden in its subclasses.
Final variable instantiations are possible inside a constructor and the scope of
this applies to the whole class and its objects. A final variable if
initialised inside a method ensures that the variable cant be changed only within
the scope of that method.
50. Identify the output of the below java program and Justify your answer.
class Main {
public static void main(String args[]) {
Scaler s = new Scaler(5);
}
}
class InterviewBit{
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
}
class Scaler extends InterviewBit{
Scaler(){
System.out.println(" Welcome to Scaler Academy ");
}
Scaler(int x){
this();
super();
System.out.println(" Welcome to Scaler Academy 2");
}
}
The above code will throw the compilation error. It is because the super() is used
to call the parent class constructor. But there is the condition that super() must
be the first statement in the block. Now in this case, if we replace this() with
super() then also it will throw the compilation error. Because this() also has to
be the first statement in the block. So in conclusion, we can say that we cannot
use this() and super() keywords in the same block.
Case 1: When the object is pointed to another location: In this case, the changes
made to that object do not get reflected the original object before it was passed
to the method as the reference points to another location.
For example:
class InterviewBitTest{
int num;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
class Driver {
public static void main(String[] args)
{
//create a reference
InterviewBitTest ibTestObj = new InterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in the
object.
System.out.println(ibTestObj.num);
}
public static void updateObject(InterviewBitTest ibObj)
{
// Point the object to new reference
ibObj = new InterviewBitTest();
// Update the value
ibObj.num = 50;
}
}
Output:
20
Case 2: When object references are not modified: In this case, since we have the
copy of reference the main object pointing to the same memory location, any changes
in the content of the object get reflected in the original object.
For example:
class InterviewBitTest{
int num;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
class Driver{
public static void main(String[] args)
{
//create a reference
InterviewBitTest ibTestObj = new InterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in the
object.
System.out.println(ibTestObj.num);
}
public static void updateObject(InterviewBitTest ibObj)
{
// no changes are made to point the ibObj to new location
// Update the value of num
ibObj.num = 50;
}
}
Output:
50
52. What is the ‘IS-A ‘ relationship in OOPs java?
‘IS-A’ relationship is another name for inheritance. When we inherit the base class
from the derived class, then it forms a relationship between the classes. So that
relationship is termed an ‘IS-A’ Relationship.
Example - Consider a Television (Typical CRT TV). Now another Smart TV that is
inherited from television class. So we can say that the Smart iv is also a TV.
Because CRT TV things can also be done in the Smart TV.
53. Which among String or String Buffer should be preferred when there are lot of
updates required to be done in the data?
StringBuffer is mutable and dynamic in nature whereas String is immutable. Every
updation / modification of String creates a new String thereby overloading the
string pool with unnecessary objects. Hence, in the cases of a lot of updates, it
is always preferred to use StringBuffer as it will reduce the overhead of the
creation of multiple String objects in the string pool.
56. Consider the below program, identify the output, and also state the reason for
that.
public class Main{
public static void main(String[] args) {
System.out.println(" Hello. Main Method. ");
}
public static void main(int[] args) {
System.out.println(" Hello. Main Method2. ");
}
}
The output of the above program will be Hello. Main Method. This is because JVM
will always call the main method based on the definition it already has. Doesn't
matter how many main methods we overload it will only execute one main method based
on its declaration in JVM.
58. What happens if there are multiple main methods inside one class in Java?
The program can't compile as the compiler says that the method has been already
defined inside the class.
59. What do you understand by Object Cloning and how do you achieve it in Java?
It is the process of creating an exact copy of any object. In order to support
this, a java class has to implement the Cloneable interface of java.lang package
and override the clone() method provided by the Object class the syntax of which
is:
protected Object clone() throws CloneNotSupportedException{
return (Object)super.clone();
}
In case the Cloneable interface is not implemented and just the method is
overridden, it results in CloneNotSupportedException in Java.
60. How does an exception propagate in the code?
When an exception occurs, first it searches to locate the matching catch block. In
case, the matching catch block is located, then that block would be executed. Else,
the exception propagates through the method call stack and goes into the caller
method where the process of matching the catch block is performed. This propagation
happens until the matching catch block is found. If the match is not found, then
the program gets terminated in the main method.
logo
Practice Problems
Solve these problems to ace this concept
Exception Handling
Easy
5.12 Mins
Solve
Finally Block
Easy
2.45 Mins
Solve
63. Will the finally block get executed when the return statement is written at the
end of try block and catch block as shown below?
public int someMethod(int i){
try{
//some statement
return 1;
}catch(Exception e){
//some statement
return 999;
}finally{
//finally block statements
}
}
finally block will be executed irrespective of the exception or not. The only case
where finally block is not executed is when it encounters ‘System.exit()’ method
anywhere in try/catch block.
64. Can you call a constructor of a class inside the another constructor?
Yes, the concept can be termed as constructor chaining and can be achieved using
this().
65. Contiguous memory locations are usually used for storing actual values in an
array but not in ArrayList. Explain.
In the case of ArrayList, data storing in the form of primitive data types (like
int, float, etc.) is not possible. The data members/objects present in the
ArrayList have references to the objects which are located at various sites in the
memory. Thus, storing of actual objects or non-primitive data types (like Integer,
Double, etc.) takes place in various memory locations.
However, the same does not apply to the arrays. Object or primitive type values can
be stored in arrays in contiguous memory locations, hence every element does not
require any reference to the next element.
Example - Consider the array and assume each element takes 4-byte memory space.
Then the address will be like this -
Now if we want to access index 4. Then internally java calculates the address using
the formula-
Now if we apply the same formula here. Then we get - 116 as the starting address of
the 4th index. Which is wrong. Then we need to apply formula - [Base Address +
((index-1) * no_of_bytes)].
And for calculating this, an extra arithmetic operation has to be performed. And
consider the case where millions of addresses need to be calculated, this causes
complexity. So to avoid this, ) the index array is supported by java.
67. Why is the remove method faster in the linked list than in an array?
In the linked list, we only need to adjust the references when we want to delete
the element from either end or the front of the linked list. But in the array,
indexes are used. So to manage proper indexing, we need to adjust the values from
the array So this adjustment of value is costlier than the adjustment of
references.
Example - To Delete from the front of the linked list, internally the references
adjustments happened like this.
The only thing that will change is that the head pointer will point to the head’s
next node. And delete the previous node. That is the constant time operation.
For deletion of the first element, all the next element has to move to one place
ahead. So this copying value takes time. So that is the reason why removing in
ArrayList is slower than LinkedList.
68. How many overloaded add() and addAll() methods are available in the List
interface? Describe the need and uses.
There are a total of 4 overloaded methods for add() and addAll() methods available
in List Interface. The below table states the description of all.
1. Consider initially that there are 2 elements in the ArrayList. [2, 3].
2. If we need to add the element into this. Then internally what will happen is-
ArrayList will allocate the new ArrayList of Size (current size + half of the
current size). And add the old elements into the new. Old - [2, 3], New - [2, 3,
null].
Then the new value will be inserted into it. [2, 3, 4, null]. And for the next
time, the extra space will be available for the value to be inserted.
3. This process continues and the time taken to perform all of these is considered
as the amortized constant time.
This is how the ArrayList grows dynamically. And when we delete any entry from the
ArrayList then the following steps are performed -
1. It searches for the element index in the array. Searching takes some time.
Typically it’s O(n) because it needs to search for the element in the entire array.
2. After searching the element, it needs to shift the element from the right side
to fill the index.
So this is how the elements are deleted from the ArrayList internally. Similarly,
the search operations are also implemented internally as defined in removing
elements from the list (searching for elements to delete).
Multiple-inheritance is not possible in Java. Classes can only extend from one
superclass. In cases where multiple functionalities are required, for example - to
read and write information into the file, the pattern of composition is preferred.
The writer, as well as reader functionalities, can be made use of by considering
them as the private members.
Composition assists in attaining high flexibility and prevents breaking of
encapsulation.
Unit testing is possible with composition and not inheritance. When a developer
wants to test a class composing a different class, then Mock Object can be created
for signifying the composed class to facilitate testing. This technique is not
possible with the help of inheritance as the derived class cannot be tested without
the help of the superclass in inheritance.
The loosely coupled nature of composition is preferable over the tightly coupled
nature of inheritance.
Let’s take an example:
package comparison;
public class Top {
public int start() {
return 0;
}
}
class Bottom extends Top {
public int stop() {
return 0;
}
}
In the above example, inheritance is followed. Now, some modifications are done to
the Top class like this:
class Bottom {
Top par = new Top();
public int stop() {
par.start();
par.stop();
return 0;
}
}
71. What is the difference between ‘>>’ and ‘>>>’ operators in java?
These 2 are the bitwise right shift operators. Although both operators look
similar. But there is a minimal difference between these two right shift operators.
‘>>’ Bitwise Right Shift Operator- This operator shifts each bit to its right
position. And this maintains the signed bit.
‘>>>’ Bitwise Right Shift Operator with trailing zero- This operator also shifts
each bit to its right. But this doesn’t maintain the signed bit. This operator
makes the Most significant bit to 0.
Example- Num1 = 8, Num2 = -8.
Consider the University as a class that has some departments in it. So the
university will be the container object. And departments in it will contain
objects. Now in this case, if the container object destroys then the contained
objects will also get destroyed automatically. So here we can say that there is a
strong association between the objects. So this Strong Association is called
Composition.
Now consider one more example. Suppose we have a class department and there are
several professors' objects there in the department. Now if the department class is
destroyed then the professor's object will become free to bind with other objects.
Because container objects (Department) only hold the references of contained
objects (Professor’s). So here is the weak association between the objects. And
this weak association is called Aggregation.
73. How is the creation of a String using new() different from that of a literal?
When a String is formed as a literal with the assistance of an assignment operator,
it makes its way into the String constant pool so that String Interning can take
place. This same object in the heap will be referenced by a different String if the
content is the same for both of them.
Conversely, when a String formation takes place with the help of a new() operator,
interning does not take place. The object gets created in the heap memory even if
the same content object is present.
74. How is the ‘new’ operator different from the ‘newInstance()’ operator in java?
Both ‘new’ and ‘newInstance()’ operators are used to creating objects. The
difference is- that when we already know the class name for which we have to create
the object then we use a new operator. But suppose we don’t know the class name for
which we need to create the object, Or we get the class name from the command line
argument, or the database, or the file. Then in that case we use the
‘newInstance()’ operator.
75. Is exceeding the memory limit possible in a program despite having a garbage
collector?
Yes, it is possible for the program to go out of memory in spite of the presence of
a garbage collector. Garbage collection assists in recognizing and eliminating
those objects which are not required in the program anymore, in order to free up
the resources used by them.
Moreover, exhaustion of the heap memory takes place if objects are created in such
a manner that they remain in the scope and consume memory. The developer should
make sure to dereference the object after its work is accomplished. Although the
garbage collector endeavors its level best to reclaim memory as much as possible,
memory limits can still be exceeded.
No synchronization:
package anonymous;
public class Counting {
private int increase_counter;
public int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
With synchronization:
package anonymous;
public class Counting {
private int increase_counter;
public synchronized int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then
the thread Thread2 will view the count as 11, it will be increased by 1 to 12.
Thus, consistency in count values takes place.
This is a java tricky interview question frequently asked in java interviews for
the experienced. The output will be like this because, when the java program is
compiled and gets executed, then there are various steps followed for execution.
And the steps are -
Now from the above code, the execution will happen like this -
static int j.
static block.
main method.
static method_2.
During identification, the JVM will assign the default value in the static int j
variable. Then it is currently in the state of reading and indirectly writing.
Because the original value is not assigned.
2. In the next step, it will execute the static block and assign the value in
static variables.
First static block it will print and because execution from top to bottom and
original value in j is not assigned. So it will print the default value of 0.
After executing static block 1. It will execute the static method_1 because it is
called from the static block 1.
Then it will assign the original value of 5 in the j variable. And executes the
remaining static block.
3. Now it will execute the main method. In which it will create an object for the
class InterviewBit. And then the execution of instances will happen.
int i.
Instance block 1.
Instance method_1.
Like a static variable, the instance variable also has been initialized with the
default value 0 and will be in the state of reading and writing indirectly.
5. It will execute the instance methods and assign the original value to the
instance variable.
Prints the Instance block 1. And the current value of i is not assigned till now,
so it will print 0.
Assign the original value to i. Then print instance block 2. And after that
instance method will be called and printed because it is being called in the
instance block.
6. And at the last step, the constructor will be invoked and the lines will be
executed in the constructor.
So if we justify the statement, then we can say that if we want to print anything
on the console then we need to call the println() method that was present in
PrintStream class. And we can call this using the output object that is present in
the System class.
New – When the instance of the thread is created and the start() method has not
been invoked, the thread is considered to be alive and hence in the NEW state.
Runnable – Once the start() method is invoked, before the run() method is called by
JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also
be entered from the Waiting or Sleeping state of the thread.
Running – When the run() method has been invoked and the thread starts its
execution, the thread is said to be in a RUNNING state.
Non-Runnable (Blocked/Waiting) – When the thread is not able to run despite the
fact of its aliveness, the thread is said to be in a NON-RUNNABLE state. Ideally,
after some time of its aliveness, the thread should go to a runnable state.
A thread is said to be in a Blocked state if it wants to enter synchronized code
but it is unable to as another thread is operating in that synchronized block on
the same object. The first thread has to wait until the other thread exits the
synchronized block.
A thread is said to be in a Waiting state if it is waiting for the signal to
execute from another thread, i.e it waits for work until the signal is received.
Terminated – Once the run() method execution is completed, the thread is said to
enter the TERMINATED step and is considered to not be alive.
The following flowchart clearly explains the lifecycle of the thread in Java.
81. What could be the tradeoff between the usage of an unordered array versus the
usage of an ordered array?
The main advantage of having an ordered array is the reduced search time complexity
of O(log n) whereas the time complexity in an unordered array is O(n).
The main drawback of the ordered array is its increased insertion time which is
O(n) due to the fact that its element has to reordered to maintain the order of
array during every insertion whereas the time complexity in the unordered array is
only O(1).
Considering the above 2 key points and depending on what kind of scenario a
developer requires, the appropriate data structure can be used for implementation.
82. Is it possible to import the same class or package twice in Java and what
happens to it during runtime?
It is possible to import a class or package more than once, however, it is
redundant because the JVM internally loads the package or class only once.
83. In case a package has sub packages, will it suffice to import only the main
package? e.g. Does importing of com.myMainPackage.* also import
com.myMainPackage.mySubPackage.*?
This is a big NO. We need to understand that the importing of the sub-packages of a
package needs to be done explicitly. Importing the parent package only results in
the import of the classes within it and not the contents of its child/sub-packages.
84. Will the finally block be executed if the code System.exit(0) is written at the
end of try block?
NO. The control of the program post System.exit(0) is immediately gone and the
program gets terminated which is why the finally block never gets executed.
import java.util.HashSet;
import java.util.Set;
doSomething(stringSets);
}
The first brace does the task of creating an anonymous inner class that has the
capability of accessing the parent class’s behavior. In our example, we are
creating the subclass of HashSet so that it can use the add() method of HashSet.
The second braces do the task of initializing the instances.
Care should be taken while initializing through this method as the method involves
the creation of anonymous inner classes which can cause problems during the garbage
collection or serialization processes and may also result in memory leaks.
87. Why is it said that the length() method of String class doesn't return accurate
results?
The length method returns the number of Unicode units of the String. Let's
understand what Unicode units are and what is the confusion below.
We know that Java uses UTF-16 for String representation. With this Unicode, we need
to understand the below two Unicode related terms:
Code Point: This represents an integer denoting a character in the code space.
Code Unit: This is a bit sequence used for encoding the code points. In order to do
this, one or more units might be required for representing a code point.
Under the UTF-16 scheme, the code points were divided logically into 17 planes and
the first plane was called the Basic Multilingual Plane (BMP). The BMP has classic
characters - U+0000 to U+FFFF. The rest of the characters- U+10000 to U+10FFFF were
termed as the supplementary characters as they were contained in the remaining
planes.
The code points from the first plane are encoded using one 16-bit code unit
The code points from the remaining planes are encoded using two code units.
Now if a string contained supplementary characters, the length function would count
that as 2 units and the result of the length() function would not be as per what is
expected.
‘b’ = 98
‘i’ = 105
‘t’ = 116
98 + 105 + 116 = 319
89. What are the possible ways of making object eligible for garbage collection
(GC) in Java?
First Approach: Set the object references to null once the object creation purpose
is served.
In the above figure on line 3, we can see that on each array index we are declaring
a new array so the reference will be of that new array on all the 3 indexes. So the
old array will be pointed to by none. So these three are eligible for garbage
collection. And on line 4, we are creating a new array object on the older
reference. So that will point to a new array and older multidimensional objects
will become eligible for garbage collection.
91. What is the best way to inject dependency? Also, state the reason.
There is no boundation for using a particular dependency injection. But the
recommended approach is -
Setters are mostly recommended for optional dependencies injection, and constructor
arguments are recommended for mandatory ones. This is because constructor injection
enables the injection of values into immutable fields and enables reading them more
easily.
92. How we can set the spring bean scope. And what supported scopes does it have?
A scope can be set by an annotation such as the @Scope annotation or the "scope"
attribute in an XML configuration file. Spring Bean supports the following five
scopes:
Singleton
Prototype
Request
Session
Global-session
93. What are the different categories of Java Design patterns?
Java Design patterns are categorized into the following different types. And those
are also further categorized as
Structural patterns:
Adapter
Bridge
Filter
Composite
Decorator
Facade
Flyweight
Proxy
Behavioral patterns:
Interpreter
Template method/ pattern
Chain of responsibility
Command pattern
Iterator pattern
Strategy pattern
Visitor pattern
J2EE patterns:
MVC Pattern
Data Access Object pattern
Front controller pattern
Intercepting filter pattern
Transfer object pattern
Creational patterns:
Factory method/Template
Abstract Factory
Builder
Prototype
Singleton
94. What is a Memory Leak? Discuss some common causes of it.
The Java Garbage Collector (GC) typically removes unused objects when they are no
longer required, but when they are still referenced, the unused objects cannot be
removed. So this causes the memory leak problem. Example - Consider a linked list
like the structure below -
In the above image, there are unused objects that are not referenced. But then also
Garbage collection will not free it. Because it is referencing some existing
referenced object. So this can be the situation of memory leak.
StringBuffer
Easy
24.11 Mins
Solve
98. Write a Java program to check if the two strings are anagrams.
The main idea is to validate the length of strings and then if found equal, convert
the string to char array and then sort the arrays and check if both are equal.
import java.util.Arrays;
import java.util.Scanner;
public class InterviewBit {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//Input from two strings
System.out.print("First String: ");
String string1 = s.nextLine();
System.out.print("Second String: ");
String string2 = s.nextLine();
// check for the length
if(string1.length() == string2.length()) {
// convert strings to char array
char[] characterArray1 = string1.toCharArray();
char[] characterArray2 = string2.toCharArray();
// sort the arrays
Arrays.sort(characterArray1);
Arrays.sort(characterArray2);
// check for equality, if found equal then anagram, else not an anagram
boolean isAnagram = Arrays.equals(characterArray1, characterArray2);
System.out.println("Anagram: "+ isAnagram);
}
}
99. Write a Java Program to find the factorial of a given number.
public class FindFactorial {
public static void main(String[] args) {
int num = 10;
long factorialResult = 1l;
for(int i = 1; i <= num; ++i)
{
factorialResult *= i;
}
System.out.println("Factorial: "+factorialResult);
}
}
100. Given an array of non-duplicating numbers from 1 to n where one number is
missing, write an efficient java program to find that missing number.
Idea is to find the sum of n natural numbers using the formula and then finding the
sum of numbers in the given array. Subtracting these two sums results in the number
that is the actual missing number. This results in O(n) time complexity and O(1)
space complexity.
int[] array={4,3,8,7,5,2,6};
int missingNumber = findMissingNum(array);
System.out.println("Missing Number is "+ missingNumber);
}
//Pointers.
int i = 0, j = str.length()-1;
104. Write a Java program to rotate arrays 90 degree clockwise by taking matrices
from user input.
mport java.util.Scanner;
public class InterviewBit
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int no;
System.out.print("Enter size of Array : ");
no = sc.nextInt();
int[][] a = new int[no][no];
System.out.print("Enter "+ no*no+" Element Array : ");
System.out.println("\n");
//Rotation
//Transpose
for(int i = 0; i < no; i++){
for(int j = i; j < no; j++){
int temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
105. Write a java program to check if any number given as input is the sum of 2
prime numbers.
Example :
Input - 18
Output -
18 = 13 + 5
18 = 11 + 7
106. Write a Java program for solving the Tower of Hanoi Problem.
public class InterviewBit
{
//Recursive Method for Solving the Tower of hanoi.
private static void TOH(char source, char auxiliary, char destination, int
numOfDisk){
if (numOfDisk > 0){
TOH(source, destination, auxiliary, numOfDisk-1);
System.out.println("Move 1 disk from "+source+" to "+destination+"
using "+auxiliary+".");
TOH(auxiliary, source, destination, numOfDisk-1);
}
}
public static void main(String[] args) {
TOH('A','B','C', 3);
}
}
In the above code we are first moving the n-1 disk from Tower A to Tower B, then
moving that nth disk from Tower A to Tower C, and finally, the remaining n-1 disk
from Tower B to Tower C. And we are doing this recursively for the n-1 disk.
//Calculating Mid.
int mid = (low + high)/2;
//Base Case.
if(low > high)
return false;
Conclusion
108. Conclusion