Java PDF
Java PDF
What is Java?
Java is the high-level programming language that was developed by James Gosling in
the year 1982. It is based on the principles of object-oriented programming and can
be used to develop large-scale applications. Learn More.
The following article will cover all the popular Core Java interview questions, String
Handling interview questions, java 8 interview questions, java multithreading
interview questions, java OOPs interview questions, java exception handling
interview questions, collections interview questions, and some frequently asked java
coding interview questions.
Go through all the questions to enhance your chances of performing well in the
interviews. The questions will revolve around the basic, core & advanced
fundamentals of Java.
So, let’s dive deep into the plethora of useful Java Interview questions and answers
for freshers and experienced candidates in depth.
Java Basic Interview Questions
1. Why is Java a platform independent language?
Java language was developed in such a way that it does not depend on any
hardware or so ware 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
class Main {
publicvoidprintArray(int[] array){
for(inti:array)
System.out.println(i);
}
publicstaticvoidmain(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.
4. Can java be said to be the complete object-oriented
programming language?
6. Pointers are used in C/ C++. Why does Java not make use of
pointers?
Pointers are quite complicated and unsafe to use by beginner programmers. Java
focuses on code simplicity, and the usage of pointers can make it challenging. Pointer
utilization can also cause potential errors. Moreover, security is also compromised if
pointers are used because the users can directly access memory with the help of
pointers.
variable?
Instance variables are those variables that are accessible by all the methods in the
class. They are declared outside the methods and inside the class. These variables
describe the properties of an object and remain bound to it at any cost.
All the objects of the class will have their copy of the variables for utilization. If any
modification is done on these variables, then only that instance will be impacted by
it, and all other class instances continue to remain unaffected.
Example:
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:
JIT stands for Just-In-Time and it is used for improving the performance during
run time. It does the task of compiling parts of byte code having similar
functionality at the same time thereby reducing the amount of compilation time
for the code to run.
The compiler is nothing but a translator of source code to machine-executable
code. But what is special about the JIT compiler? Let us see how it works:
First, the Java source code (.java) conversion to byte code (.class) occurs
with the help of the javac compiler.
Then, the .class files are loaded at run time by JVM and with the help of an
interpreter, these are converted to machine understandable code.
JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM
analyzes the method calls in the .class files and compiles them to get more
efficient and native code. It also ensures that the prioritized method calls
are optimized.
Once the above step is done, the JVM executes the optimized code directly
instead of interpreting the code again. This increases the performance and
speed of the execution.
11. Can you tell the difference between equals() method and
equality operator (==) in Java?
equals() ==
Not e:
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.
for (;;) {
} // Business logic
// Any break logic
while(true){
// Business logic
// Any break logic
}
do{
// Business logic
// Any break logic
}while(true);
class Hospital {
int variable1, variable2;
double variable3;
public Hospital(int doctors, int nurses){
variable1 = doctors;
variable2 = nurses;
}
public Hospital(int doctors) {
variable1 = doctors;
}
public Hospital(double salaries) {
variable3 = salaries
}
}
Three constructors are defined here but they differ on the basis of parameter type
and their numbers.
14. Define Copy constructor in java.
Copy Constructor is the constructor used when we want to initialize the value to the
new object from the old object of the same class.
classInterviewBit{
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.
15. Can the main method be Overloaded?
Yes, It is possible to overload the main method. We can create as many overloaded
main methods we want. However, JVM has a predefined calling method that JVM will
only call the main method with the definition of -
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 int main(double[] args){
System.out.println("Overloaded Double array Main Method");
}
public static void main(float args){
System.out.println("Overloaded float Main Method");
}
}
classOverloadingHelp {
publicint findarea (int l, int b) {
int var1;
var1 = l * b;
return var1;
}
publicint 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 {
publicintwalk(intdistance,int time){
intspeed=distance/time;
return speed;
}
}
class Athlete extends HumanBeing {
publicintwalk(intdistance,int time) {
intspeed=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
Here, the second catch block will be executed because of division by 0 (i / x). In case x
was greater than 0 then the first catch block will execute because for loop runs till i =
n and array index are till n-1.
18. Explain the use of final keyword in variable, method and
c lass.
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.
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:
21. Identify the output of the java program and state the
reason.
The above code will generate a compile-time error at Line 7 saying - [error: variable i
might already have been initialized]. It is because variable ‘i’ is the final variable.
And final variables are allowed to be initialized only once, and that was already done
on line no 5.
22. When can you use super keyword?
The super keyword is used to access hidden fields and overridden methods or
attributes of the parent class.
Following are the cases when this keyword can be used:
Accessing data members of parent class when the member names of the
class and its child subclasses are same.
To call the default and parameterized constructor of the parent class inside
the child class.
Accessing the parent class methods when the child classes have overridden
them.
The following example demonstrates all 3 cases when a super keyword is used.
System.out.println(num);
System.out.println(super.num); //prints the value of num of parent class
}
@Override
public void foo(){
The main method is always static because static members are those methods that
belong to the classes, not to an individual object. So if the main method will not be
static then for every object, It is available. And that is not acceptable by JVM. JVM
calls the main method based on the class name itself. Not by creating the object.
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.
25. Can the static methods be overridden?
No! Declaration of static methods having the same signature can be done in the
subclass but run time polymorphism can not take place in such cases. Overriding
or dynamic polymorphism occurs during the runtime, but the static methods are
loaded and looked up at the compile time statically. Hence, these methods cant
be overridden.
The main objective of this process is to free up the memory space occupied by the
unnecessary and unreachable objects during the Java program execution by deleting
those unreachable objects.
This ensures that the memory resource is used efficiently, but it provides no
guarantee that there would be sufficient memory for the program execution.
class Rectangle{
int length = 5;
int breadth = 3;
}
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 -
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; System.out.println("BeforeChanging the value of object 1, the object2
will System.out.println("Object2Length = "+obj2.length+", Object2 Breadth = "+o
//Changingthevaluesforobject1. obj1.length = 10; obj1.breadth = 20;
System.out.println("\nAfterChanging the value of object 1, the object2 wil
System.out.println("Object2Length = "+obj2.length+", Object2 Breadth = "+o
}
}
Output -
We can see that in the above code, if we change the values of object1, then the
object2 values also get changed. It is because of the reference.
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
Rectangleobj2=newRectangle(); obj2.length = obj1.length; obj2.breadth = obj1.breadth;
System.out.println("BeforeChanging the value of object 1, the object2 will
System.out.println("Object2Length = "+obj2.length+", Object2 Breadth = "+o
//Changingthevaluesforobject1. obj1.length = 10; obj1.breadth = 20;
System.out.println("\nAfterChanging the value of object 1, the object2 wil
System.out.println("Object2Length = "+obj2.length+", Object2 Breadth = "+o
}
}
The above snippet will not affect the object2 values. It has its separate values. The
output will be
Now we see that we need to write the number of codes for this deep copy. So to
reduce this, In java, there is a method called clone().
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();
Java Intermediate Interview Questions
31. Apart from the security aspect, what are the reasons behind
making strings immutable in Java?
A String is made immutable due to the following reasons:
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.
class WaterJug{
privateintwaterQuantity=500;
private WaterJug(){}
privateWaterJugobject=null;
//Methodtoprovidetheservice of Giving Water.
publicintgetWater(intquantity){
waterQuantity-=quantity;
return quantity;
}
//Methodtoreturntheobject to the user.
publicstaticWaterjuggetInstance(){
//WillCreateanewobject if the object is not already created and return the
if(object == null){
object=newWaterJug();
}
return object;
}
}
In the above class, the Constructor is private so we cannot create the object of the
class. But we can get the object by calling the method getInstance(). And the
getInstance is static so it can be called without creating the object. And it returns the
object. Now with that object, we can call getWater() to get the water.
We can get the single object using this getInstance(). And it is static, so it is a thread-
safe singleton class. Although there are many ways to create a thread-safe singleton
class. So thread-safe classes can also be:
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
enum s.
Storage area: In string, the String pool serves as the storage area. For
StringBuilder and StringBuffer, heap memory is the storage area.
Mutability: A String is immutable, whereas both the StringBuilder and
StringBuffer are mutable.
Efficiency: It is quite slow to work with a String. However, StringBuilder is the
fastest in performing operations. The speed of a StringBuffer is more than a
String and less than a StringBuilder. (For example appending a character is
fastest in StringBuilder and very slow in String because a new memory is
required for the new String with appended character.)
Thread-safe: In the case of a threaded environment, StringBuilder and
StringBuffer are used whereas a String is not used. However, StringBuilder is
suitable for an environment with a single thread, and a StringBuffer is suitable
for multiple threads.
Synt a x:
// String
String first = "InterviewBit";
String second = new String("InterviewBit");
// StringBuffer
StringBuffer third = new StringBuffer("InterviewBit");
// StringBuilder
StringBuilder fourth = new StringBuilder("InterviewBit");
Interface example:
abstractfinalclass InterviewBit{
2. publicabstract void printMessage();
3.}
4.classScalarAcademy extends InterviewBit{
5. 6.publicvoid
7. 8.}
printMessage(){
9.classScalarTopics extends
ScalarAcademy{
System.out.println("Welcome to Scalar Academy By InterviewBit");
}
10. 11.publicvoid
12. printMessage(){
13.}
publicclassMain{
System.out.println("Welcome to Scalar Topics By Scalar Academy");
}
The above program will give a compile-time error. The compiler will throw 2 errors in
this.
[Illegal Combination of modifiers: abstract and final] at line 1.
[Cannot inherit from final ‘InterviewBit’] at line 4.
It is because abstract classes are incomplete classes that need to be inherited for
making their concrete classes. And on the other hand, the final keywords in class are
used for avoiding inheritance. So these combinations are not allowed in java.
Consider the example where we have an ArrayList of employees like( EId, Ename,
Salary), etc. Now if we want to sort this list of employees based on the names of
employees. Then that is not possible to sort using the Collections.sort() method. We
need to provide something to the sort() function depending on what values we have
to perform sorting. Then in that case a comparator is used.
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.
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?
JDK- For making java programs, we need some tools that are provided by JDK
(Java Development Kit). JDK is the package that contains various tools,
Compiler, Java Runtime Environment, etc.
JRE - To execute the java program we need an environment. (Java Runtime
Environment) JRE contains a library of Java classes + JVM. What are JAVA
Classes? It contains some predefined methods that help Java programs to use
that feature, build and execute. For example - there is a system class in java that
contains the print-stream method, and with the help of this, we can print
something on the console.
JVM - (Java Virtual Machine) JVM is a part of JRE that executes the Java
program at the end. Actually, it is part of JRE, but it is so ware that converts
bytecode into machine-executable code to execute on hardware.
42. What are the differences between JVM, JRE and JDK in Java?
Definition JVM is a
platform-
dependent,
abstract
machine
JDK is a comprising of 3
complete JRE is a specifications -
so ware so ware document
development package describing the
kit for providing JVM
developing Java class implementatio
Java libraries, requirements,
applications. JVM and all computer
It comprises the required program
JRE, components meeting the JV
J avaDo c, to run the requirements
compiler, Java and instance
debuggers, applications. object for
etc. executing the
Java byte code
and provide the
runtime
environment fo
execution.
Ha s hMa p Ha s hTa bl e
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.
Example -
class Main {
publicstaticinttestExceptionDivide(int a, int b) throws ArithmeticException{
if(a==0||b==0)
thrownewArithmeticException();
return a/b;
}
publicstaticvoidmain(String args[]) {
try{
testExceptionDivide(10, 0);
}
catch(ArithmeticException e){
//Handletheexception
}
}
}
Method should
have a return
Constructor has no return type. type. Even if it
does not return
anything, return
type is void.
Method has to be
Constructor gets invoked implicitly. invoked on the
object explicitly.
If a method is not
If the constructor is not defined, then a defined, then the
default constructor is provided by the compiler does not
java compiler. provide it.
The name of the
method can have
The constructor name should be equal any name or have
to the class name. a class name too.
50. Identify the output of the below java program and Justify
your answer.
classMain {
public static void main(String args[]) {
Scaler s = new Scaler(5);
}
} classInterviewBit{
InterviewBit(){
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
Java?
In order to achieve this, the attribute can be declared along with the usage of
transient keyword as shown below:
In the above example, all the fields except someInfo can be serialized.
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.
57. Can we make the main() thread a daemon thread?
In java multithreading, the main() threads are always non-daemon threads. And there
is no way we can change the nature of the non-daemon thread to the daemon
thread.
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:
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.
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?
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.
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.
It is because the 0 index array avoids the extra arithmetic operation to calculate the
memory address.
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-
[Base Address + (index * no_of_bytes)]. So according to this. The starting address of
the index 4 will be - [100 + (4*4)] = 116. And exactly that's what the address is
calculated.
Now consider the same with 1 index Array -
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
69. How does the size of ArrayList grow dynamically? And also
state how it is implemented internally.
ArrayList is implemented in such a way that it can grow dynamically. We don't need
to specify the size of ArrayList. For adding the values in it, the methodology it uses is -
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, 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. A er searching the element, it needs to shi 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).
Java Advanced Interview Questions
70. Although inheritance is a popular OOPs concept, it is less
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.
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:
If the new implementation of the Top class is followed, a compile-time error is bound
to occur in the Bottom class. Incompatible return type is there for the Top.stop()
function. Changes have to be made to either the Top or the Bottom class to ensure
compatibility. However, the composition technique can be utilized to solve the given
problem:
class Bottom {
Top par = new Top();
public int stop(){
par.start();
par.stop();
return 0;
}
}
difference.
Composition, and Aggregation help to build (Has - A - Relationship) between classes
and objects. But both are not the same in the end. Let’s understand with the help of
an example.
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
C ompos i t i on.
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.
The checking() function will return true as the same content is referenced by both the
variables.
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.
The checking() function will return false as the same content is not referenced by
both the variables.
packageanonymous;
publicclassCounting {
privateint increase_counter;
publicint increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
packageanonymous;
publicclassCounting {
privateint increase_counter;
publicsynchronized 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.
fooBarMethod("foo", "bar");
fooBarMethod("foo", "bar", "boo");
fooBarMethod(new String[]{"foo", "var", "boo"});
public void myMethod(String... variables){
for(String variable : variables){
// business logic
}
}
78. What will be the output of the below java program and
define the steps of Execution of the java program with the
help of the below code?
class InterviewBit{
int i; static int j; {
} static{
j = 10;
}
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
public static void main(String[] args){
InterviewBit ib = new InterviewBit();
}
public void method_1(){
System.out.println(" Instance method. ");
}
static{
System.out.println(" Static Block 2. Value of j = "+j);
}{
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.
A er 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.
4. Identify the instance variables and blocks from top to bottom.
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 a er 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.
This is how the java program gets executed.
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, a er 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.
import java.util.HashSet;
import java.util.Set;
public class IBDoubleBraceDemo{
In the above example, we see that the stringSets were initialized by using double
braces.
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
expect ed.
In other words, if there is 1 supplementary character of 2 units, the length of that
SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the
java documentation, it is expected, but as per the real logic, it is inaccurate.
88. What is the output of the below code and why?
“bit” would have been the result printed if the letters were used in double-quotes (or
the string literals). But the question has the character literals (single quotes) being
used which is why concatenation wouldn't occur. The corresponding ASCII values of
each character would be added and the result of that sum would be printed.
The ASCII values of ‘b’, ‘i’, ‘t’ are:
‘b’ = 98
‘i’ = 105
‘t’ = 116
98 + 105 + 116 = 319
publicclassIBGarbageCollect {
publicstaticvoidmain (String [] args){
Strings1="Some String";
//s1referencing String object - not yet eligible for GC
s1=null;//now s1 is eligible for GC
}
}
Second Approach: Point the reference variable to another object. Doing this, the
object which the reference variable was referencing before becomes eligible for GC.
publicclassIBGarbageCollect {
publicstaticvoidmain(String [] args){
Strings1="ToGarbage Collect";
Strings2="AnotherObject";
System.out.println(s1); // s1 is not yet eligible for GC
s1=s2;//Points1to other object pointed by s2
/*Here,thestringobject having the content "To Garbage Collect" is not referre
}
}
}
}
90. In the below Java Program, how many objects are eligible
for garbage collection?
class Main{
publicstaticvoidmain(String[] args){
int[][]num=new int[3][];
num[0]=newint[5];
num[1]=newint[2];
num[2]=newint[3];
num[2]=newint[5];
num[0]=newint[4];
num[1]=newint[3]; num=newint[2]
[];
}
}
In the above program, a total of 7 objects will be eligible for garbage collection. Let’s
visually understand what's happening in the code.
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
Adapter
B ridge
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
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.
Some common causes of Memory leaks are -
When there are Unbounded caches.
Excessive page swapping is done by the operating system.
Improper written custom data structures.
Inserting into a collection object without first deleting it.
etc.
95. Assume a thread has a lock on it, calling the sleep() method
on that thread will release the lock?
A thread that has a lock won't be released even a er it calls sleep(). Despite the
thread sleeping for a specified period of time, the lock will not be released.
/*
* Javaprogramtocheckifagiven inputted string is palindrome or not using recursion
*/
import java.util.*;
public class InterviewBit {
publicstaticvoidmain(String args[]) {
Scanners=newScanner(System.in);
Stringword=s.nextLine();
System.out.println("Is"+word+" palindrome? - "+isWordPalindrome(word));
}
publicstaticbooleanisWordPalindrome(String word){
StringreverseWord=getReverseWord(word);
//ifwordequalsitsreverse, then it is a palindrome
if(word.equals(reverseWord)){
return true;
}
return false;
}
publicstaticStringgetReverseWord(String word){
if(word==null||word.isEmpty()){
return word;
}
returnword.charAt(word.length()- 1) + getReverseWord(word.substring(0, word.len
}
}
classInterviewBit {
publicstatic void printFibonacci(int val_1, int val_2, int num){
//Base Case
if(num == 0)
return;
}
publicstatic void main(String args[]) {
System.out.println(" *** Fibonacci Series *** ");
//Printing the first two values
System.out.print("0 1 ");
//Calling Method to print the fibonacci for length 10
printFibonacci(0, 1, 10);
}
}
In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then
based on the length of Fibonacci to be printed, we are using the helper function to
print that.
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.
importjava.util.Arrays;
importjava.util.Scanner;
publicclassInterviewBit {
publicstaticvoidmain(String[] args) {
Scanners=newScanner(System.in);
//Inputfromtwostrings
System.out.print("First String: ");
Stringstring1=s.nextLine();
System.out.print("Second String: ");
Stringstring2=s.nextLine();
//checkforthelength
if(string1.length() == string2.length()) {
//convertstrings to char array char[]characterArray1 = string1.toCharArray();
char[]characterArray2 = string2.toCharArray(); //sortthearrays
Arrays.sort(characterArray1); Arrays.sort(characterArray2); //checkforequality, if found
equal then anagram, else not an anagram booleanisAnagram =
Arrays.equals(characterArray1, characterArray2); System.out.println("Anagram: "+
isAnagram);
}
}
publicclassFindFactorial {
publicstaticvoidmain(String[] args) {
int num = 10; longfactorialResult = 1l; for(inti=1;i<= num; ++i) {
} System.out.println("Factorial: "+factorialResult);
factorialResult *= i;
}
}
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.
publicclassIBMissingNumberProblem {
publicstaticvoidmain(String[] args) {
int[]array={4,3,8,7,5,2,6};
intmissingNumber=findMissingNum(array);
System.out.println("Missing Number is "+ missingNumber);
}
publicstaticintfindMissingNum(int[] array) {
int n=array.length+1;
intsumOfFirstNNums=n*(n+1)/2;
int actualSumOfArr=0;
for(inti=0;i<array.length; i++) {
actualSumOfArr+=array[i];
}
returnsumOfFirstNNums-actualSumOfArr;
}
}
System.out.println("Magic number");
}else {
System.out.println("Notmagicnumber");
}
}
}
class InterviewBit {
public static void main(String args[]) throws CustomException{
We have created the exception class named with CustomException and called the
base exception constructor with the error message that we want to print. And to
avoid handling exceptions in the main method, we have used the throws keyword in
the method declaration.
103. Write a Java program to reverse a string.
class InterviewBit{
publicstaticvoidmain(String[] args){
//Input String
Stringstr="Welcome to InterviewBit";
//Pointers.
inti=0,j=str.length()-1;
//Resultcharacterarray to store the reversed string.
char[]revString=new char[j+1];
//Loopingandreversing the string.
while(i < j){
revString[j]=str.charAt(i);
revString[i]=str.charAt(j); i++; j--;
}
//Printingthereversed String.
System.out.println("Reversed String = " + String.valueOf(revString));
}
}
In the above code, we are storing the last character from the string to the first and
the first value to the last in the output character array. And doing the same thing in
the loop for the remaining 2nd to n-1 characters. This is how the string will be
reversed.
104. Write a Java program to rotate arrays 90 degree clockwise
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+"ElementArray : ");
int l, j;
for(j = 0, l = no -1; j < l; j++){
int temp = a[i][j];
a[i][j] = a[i][l];
a[i][l] = temp;
l--;
}
}
System.out.println("ArrayAfterRotation-\n");
for(int i = 0; i<no; i++){
In the above code, for rotating the matrix to 90 degrees we are first transposing the
matrix so the row becomes the column. And a er that, we are reversing each row in
the matrix. So this is how the matrix got rotated.
105. Write a java program to check if any number given as input
return 1;
}
// Method to get print the prime sum
private static void find(int num){
for(int i = 2; i <= num/2; i++){
if(check_prime(i) == 0){
if(check_prime(num-i) == 0)
System.out.println(num + " = "+ (num-i) + " "+ i);
}
}
}
public static void main(String[] args) {
find(18);
}
}
In the above code, for any number n, we find all the 2 pairs of numbers that are
added together resulting in n. And each checking number if it is prime. If it is prime
then we are printing that.
106. Write a Java program for solving the Tower of Hanoi
Problem.
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.
107. Implement Binary Search in Java using recursion.
//Calculating Mid.
int mid = (low + high)/2;
//Base Case.
if(low > high)
return false;
//Checkingifthekeyisfoundinthe middle.
if(arr[mid] == key)
return true;
//Searchingontheotherhalfotherwise.
returnbinarySearch(arr,mid+1,high, key);
}
public static void main(String[] args) {
In the above code, we are finding the middle element each time and checking if the
element is in the middle or not. If it is not, then we check on which side from the
middle it exists. And Recursively searching on the particular subarray. So this way we
are reducing the search space by 2 every time. So the search time is very low.
Conclusion
108. C onc lusion
Java is one of the simple high-level languages that provides powerful tools and
impressive standards required for application development. It was also one of the
first languages to provide amazing threading support for tackling concurrency-based
problems. The easy-to-use syntax and the built-in features of Java combined with the
stability it provides to applications are the main reasons for this language to have
ever-growing usage in the so ware community.
Join our community and share your java interview experiences.