For Basic Java Interview Questions 1723574250
For Basic Java Interview Questions 1723574250
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.
You can download a PDF version of Java Interview Questions.
Download PDF
4. Can java be said to be the complete object-oriented programming language?
It is not wrong if we claim that java is the complete object-oriented programming language. Because Everything in Java is under the classes.
And we can access that by creating the objects.
But also if we say that java is not a completely object-oriented programming language because it has the support of primitive data types like
int, float, char, boolean, double, etc.
Now for the question: Is java a completely object-oriented programming language? We can say that - Java is not a pure object-oriented
programming language, because it has direct access to primitive data types. And these primitive data types don't directly belong to the
Integer classes.
5. How is Java different from C++?
• C++ is only a compiled language, whereas Java is compiled as well as an interpreted language.
• Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled.
• C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java internally uses pointers.
• C++ supports the concept of Multiple inheritances whereas Java doesn't support this. And it is due to avoiding the complexity of name
ambiguity that causes the diamond problem.
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.
Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of
garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.
7. What do you understand by an instance variable and a local 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:
classAthlete{
publicString athleteName;
publicdoubleathleteSpeed;
publicintathleteAge;
}
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:
publicvoidathlete(){
String athleteName;
doubleathleteSpeed;
intathleteAge;
}
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 -
String str1 = "InterviewBit";
String str2 = "InterviewBit";
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.
System.out.println(str1 == str2);
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 It cannot be modified. They always compare the HashCode.
our custom .equals() method in the custom class, for objects
comparison.
This method is used for checking the equality of contents between two This operator is used for comparing addresses (or references), i.e
objects as per the specified business logic. 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:
• Using For Loop:
for(;;)
{
// Business logic// Any break logic}
• Using while loop:
while(true){
// Business logic// Any break logic}
• Using do-while loop:
do{
// Business logic// Any break logic}while(true);
13. Briefly explain the concept of constructor overloading
Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the
constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of
constructors is done by the compiler.
classHospital{
intvariable1, variable2;
doublevariable3;
publicHospital(intdoctors, intnurses){
variable1 = doctors;
variable2 = nurses;
}
publicHospital(intdoctors){
variable1 = doctors;
}
publicHospital(doublesalaries){
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 -
publicstaticvoidmain(string[] args)
Consider the below code snippets:
classMain{
publicstaticvoidmain(String args[]){
System.out.println(" Main Method");
}
publicstaticvoidmain(int[] args){
System.out.println("Overloaded Integer array Main Method");
}
publicstaticvoidmain(char[] args){
System.out.println("Overloaded Character array Main Method");
}
publicstaticvoidmain(double[] args){
System.out.println("Overloaded Double array Main Method");
}
publicstaticvoidmain(floatargs){
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.
classOverloadingHelp{
publicintfindarea(intl, intb){
intvar1;
var1 = l * b;
returnvar1;
}
publicintfindarea(intl, intb, inth){
intvar2;
var2 = l * b * h;
returnvar2;
}
}
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:
classHumanBeing{
publicintwalk(intdistance, inttime){
intspeed = distance / time;
returnspeed;
}
}
classAthleteextendsHumanBeing{
publicintwalk(intdistance, inttime){
intspeed = distance / time;
speed = speed * 2;
returnspeed;
}
}
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:
publicclassMultipleCatch{
publicstaticvoidmain(String args[]){
try{
intn = 1000, x = 0;
intarr[] = newint[n];
for(inti = 0; i <= n; i++) {
arr[i] = i / x;
}
}
catch(ArrayIndexOutOfBoundsException exception) {
System.out.println("1st block = ArrayIndexOutOfBoundsException");
}
catch(ArithmeticException exception) {
System.out.println("2nd block = ArithmeticException");
}
catch(Exception exception) {
System.out.println("3rd block = Exception");
}
}
}
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 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:
finalinta=100;
a = 0; // error
The second statement will throw an error.
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{
intvariable = 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:
publicstaticvoidmain(String[] args){
String example = newString("InterviewBit");
example = null;
System.gc(); // Garbage collector called}
publicvoidfinalize(){
// Finalize called}
20. Is it possible that the ‘finally’ block will not be executed? If yes then list the case.
Yes. It is possible that the ‘finally’ block will not be executed. The cases are-
• Suppose we use System.exit() in the above statement.
• If there are fatal errors like Stack overflow, Memory access error, etc.
21. Identify the output of the java program and state the reason.
1.publicclassInterviewBit2. {
3.publicstaticvoidmain(String[] args){
4.finalinti;
5.i = 20;
6.intj = i+20;
7.i = j+30;
8.System.out.println(i + " "+ j);
9.}
10.}
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.
publicclassParent{
protectedintnum = 1;
Parent(){
System.out.println("Parent class default constructor.");
}
Parent(String x){
System.out.println("Parent class parameterised constructor.");
}
publicvoidfoo(){
System.out.println("Parent class foo!");
}
}
publicclassChildextendsParent{
privateintnum = 2;
Child(){
System.out.println("Child class default Constructor");
super("Call Parent"); // to call parameterised constructor.super(); // to call default parent constructor}
voidprintNum(){
System.out.println(num);
System.out.println(super.num); //prints the value of num of parent class}
@Overridepublicvoidfoo(){
System.out.println("Parent class foo!");
super.foo(); //Calls foo method of Parent class inside the Overriden foo method of Child class.}
}
23. Can the static methods be overloaded?
Yes! There can be two or more static methods in a class with the same name but differing input parameters.
24. Why is the main method static in Java?
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.
26. Difference between static methods, static variables, and static classes in java.
• Static Methods and Static variables are those methods and variables that belong to the class of the java program, not to the object of
the class. This gets memory where the class is loaded. And these can directly be called with the help of class names.
○ For example - We have used mathematical functions in the java program like - max(), min(), sqrt(), pow(), etc. And if we notice
that, then we will find that we call it directly with the class name. Like - Math.max(), Math.min(), etc. So that is a static
method. And Similarly static variables we have used like (length) for the array to get the length. So that is the static method.
• Static classes - A class in the java program cannot be static except if it is the inner class. If it is an inner static class, then it exactly works
like other static members of the class.
27. What is the main objective of garbage collection?
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.
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.
30. What are shallow copy and deep copy in java?
To copy the object's data, we have several methods like deep copy and shallow copy.
Example -
classRectangle{
intlength = 5;
intbreadth = 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 = newRectangle();
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 -
classRectangle{
intlength = 5;
intbreadth = 3;
}
publicclassMain{
publicstaticvoidmain(String[] args){
Rectangle obj1 = newRectangle();
//Shallow CopyRectangle obj2 = obj1;
System.out.println(" Before Changing the value of object 1, the object2 will be - ");
System.out.println(" Object2 Length = "+obj2.length+", Object2 Breadth = "+obj2.breadth);
System.out.println("\n After Changing the value of object 1, the object2 will be - ");
System.out.println(" Object2 Length = "+obj2.length+", Object2 Breadth = "+obj2.breadth);
}
}
Output -
Before Changing the value of object 1, the object2 will be -
Object2 Length = 5, Object2 Breadth = 3After Changing the value of object 1, the object2 will be -
Object2 Length = 10, Object2 Breadth = 20
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.
classRectangle{
intlength = 5;
intbreadth = 3;
}
publicclassMain{
publicstaticvoidmain(String[] args){
Rectangle obj1 = newRectangle();
//Shallow CopyRectangle obj2 = newRectangle();
obj2.length = obj1.length;
obj2.breadth = obj1.breadth;
System.out.println(" Before Changing the value of object 1, the object2 will be - ");
System.out.println(" Object2 Length = "+obj2.length+", Object2 Breadth = "+obj2.breadth);
System.out.println("\n After Changing the value of object 1, the object2 will be - ");
System.out.println(" Object2 Length = "+obj2.length+", Object2 Breadth = "+obj2.breadth);
}
}
The above snippet will not affect the object2 values. It has its separate values. The output will be
Before Changing the value of object 1, the object2 will be -
Object2 Length = 5, Object2 Breadth = 3After Changing the value of object 1, the object2 will be -
Object2 Length = 5, Object2 Breadth = 3
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.
• Multithreading: The safety of threads regarding the String objects is an important aspect in Java. No external synchronization is
required if the String objects are immutable. Thus, a cleaner code can be written for sharing the String objects across different threads.
The complex process of concurrency is facilitated by this method.
• Collections: In the case of Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get
modified during the period when it resides in the HashMaps. Consequently, the retrieval of the desired data is not possible. Such
changing states pose a lot of risks. Therefore, it is quite safe to make the string immutable.
32. What is a singleton class in Java? And How to implement a singleton class?
Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed.
Understand this with the help of an example-:
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 -
classWaterJug{
privateintwaterQuantity = 500;
privateWaterJug(){}
privateWaterJug object = null;
42. What are the differences between JVM, JRE and JDK in Java?
Criteria JDK JRE JVM
Abbrevia Java Development Kit Java Runtime Environment Java Virtual Machine
tion
Definitio JDK is a complete software JRE is a software package JVM is a platform-dependent, abstract machine comprising of 3
n development kit for developing providing Java class libraries, specifications - document describing the JVM implementation
Java applications. It comprises JVM and all the required requirements, computer program meeting the JVM
JRE, JavaDoc, compiler, components to run the Java requirements and instance object for executing the Java byte
debuggers, etc. applications. code and provide the runtime environment for execution.
Main JDK is mainly used for code JRE is mainly used for JVM provides specifications for all the implementations to JRE.
Purpose development and execution. environment creation to
execute the code.
Tools JDK provides tools like JRE provides libraries and JVM does not include any tools, but instead, it provides the
provided compiler, debuggers, etc for classes required by JVM to specification for implementation.
code development run the program.
Summar JDK = (JRE) + Development JRE = (JVM) + Libraries to JVM = Runtime environment to execute Java byte code.
y tools execute the application
43. What are the differences between HashMap and HashTable in Java?
HashMap HashTable
HashMap is not synchronized thereby making it better for non-threaded HashTable is synchronized and hence it is suitable for threaded
applications. 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 Order of insertion is not guaranteed in HashTable.
LinkedHashMap.
50. Identify the output of the below java program and Justify your answer.
classMain{
publicstaticvoidmain(String args[]){
Scaler s = newScaler(5);
}
}
classInterviewBit{
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
}
classScalerextendsInterviewBit{
Scaler(){
System.out.println(" Welcome to Scaler Academy ");
}
Scaler(intx){
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.
51. Java works as “pass by value” or “pass by reference” phenomenon?
Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java. However, when the object is passed in any
method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is
created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:
• 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:
classInterviewBitTest{
intnum;
InterviewBitTest(intx){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
classDriver{
publicstaticvoidmain(String[] args){
//create a referenceInterviewBitTest ibTestObj = newInterviewBitTest(20);
//Pass the reference to updateObject MethodupdateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in the object.System.out.println(ibTestObj.num);
}
publicstaticvoidupdateObject(InterviewBitTest ibObj){
// Point the object to new referenceibObj = newInterviewBitTest();
// 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:
classInterviewBitTest{
intnum;
InterviewBitTest(intx){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
classDriver{
publicstaticvoidmain(String[] args){
//create a referenceInterviewBitTest ibTestObj = newInterviewBitTest(20);
//Pass the reference to updateObject MethodupdateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in the object.System.out.println(ibTestObj.num);
}
publicstaticvoidupdateObject(InterviewBitTest ibObj){
// no changes are made to point the ibObj to new location// Update the value of numibObj.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.
So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ 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.
54. How to not allow serialization of attributes of a class in Java?
• In order to achieve this, the attribute can be declared along with the usage of transient keyword as shown below:
publicclassInterviewBitExample{
privatetransientString someInfo;
privateString name;
privateintid;
// :// Getters setters// :}
• In the above example, all the fields except someInfo can be serialized.
55. What happens if the static modifier is not included in the main method signature in Java?
There wouldn't be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws
“NoSuchMethodError” error at the runtime.
56. Consider the below program, identify the output, and also state the reason for that.
publicclassMain{
publicstaticvoidmain(String[] args){
System.out.println(" Hello. Main Method. ");
}
publicstaticvoidmain(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.
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:
protectedObject clone()throwsCloneNotSupportedException{
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.
61. How do exceptions affect the program if it doesn't handle them?
Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case
when the application tries to get the file from storage and the file doesn’t exist (This is the case of exception in java). And if this case is not
handled properly then the application will crash. This will be a bad experience for users. This is the type of error that cannot be controlled
by the programmer. But programmers can take some steps to avoid this so that the application won’t crash. The proper action can be taken
at this step.
62. Is it mandatory for a catch block to be followed after a try block?
No, it is not necessary for a catch block to be present after a try block. - A try block should be followed either by a catch block or by a finally
block. If the exceptions likelihood is more, then they should be declared using the throws clause of the 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?
publicintsomeMethod(inti){
try{
//some statementreturn1;
}catch(Exception e){
//some statementreturn999;
}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.
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.
Whereas in the ArrayList, internally it should work like this-
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.
Return Method Description
Type
boolean add(Element e): This method is used for adding the element at the end of the List. The Datatype of the element is of any type it
has been initially assigned with. It returns the boolean indicating successfully inserted or not.
void add(int index, Element e): This method is the overloaded version of add() method. In this, along with the element, the index is
also passed to the method for the specific index the value needs to be inserted.
boolean addAll(Collection <extends ? Element > c): This method helps to add all elements at the end of collections from the list received
in the parameter. It contains an iterator that helps to iterate the list and add the elements to the collection.
boolean addAll(int index, Collection <extends ? Element > c): This is the overloaded method for addAll() method. In this along with the
list, we can pass the specified index from which the list elements need to be added.
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. 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).
Java Interview Questions for Experienced
70. Although inheritance is a popular OOPs concept, it is less advantageous than composition.
Explain.
Inheritance lags behind composition in the following scenarios:
• 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:
packagecomparison;
publicclassTop{
publicintstart(){
return0;
}
}
classBottomextendsTop{
publicintstop(){
return0;
}
}
In the above example, inheritance is followed. Now, some modifications are done to the Top class like this:
publicclassTop{
publicintstart(){
return0;
}
publicvoidstop(){
}
}
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:
classBottom{
Top par = newTop();
publicintstop(){
par.start();
par.stop();
return0;
}
}
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.
So the binary form of these numbers are -
Num1 = 00000000 00000000 00000000 00001000
Num2 = 11111111 11111111 11111111 11111000
‘>>’ Operator : 8 >> 1 (Shift by one bit) :
Num1 = 00000000 00000000 00000000 00000100
Num2 = 11111111 11111111 11111111 11111100
‘>>>’ Operator : 8 >>> 1 (Shift by one bit) =
Num1 = 00000000 00000000 00000000 00000100
Num2 = 01111111 11111111 11111111 11111100
72. What are Composition and Aggregation? State the 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
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.
publicbool checking(){
String first = "InterviewBit";
String second = "InterviewBit";
if(first == second)
returntrue;
elsereturnfalse;
}
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.
publicbool checking(){
String first = newString("InterviewBit");
String second = newString("InterviewBit");
if(first == second)
returntrue;
elsereturnfalse;
}
The checking() function will return false as the same content is not referenced by both the variables.
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.
The ‘newInstance()’ keyword throws an exception that we need to handle. It is because there are chances that the class definition doesn’t
exist, and we get the class name from runtime. So it will throw an exception.
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.
In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of
memory required for creating a new object is not sufficient, then memory is released for those objects which are no longer in the scope with
the help of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new
objects.
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.
Let’s take a look at the following example:
List<String> example = newLinkedList<String>();
while(true){
example.add(newString("Memory Limit Exceeded"));
}
76. Why is synchronization necessary? Explain with the help of a relevant example.
Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many
threads, situations may arise in which multiple threads require the same shared resource.
Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let’s take an example to understand it
more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can
make the count erratic.
No synchronization:
packageanonymous;
publicclassCounting{
privateintincrease_counter;
publicintincrease(){
increase_counter = increase_counter + 1;
returnincrease_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it
will be increased by 1 to 11. Thus, inconsistency in count values takes place because the expected final value is 12 but the actual final value
we get will be 11.
Now, the function increase() is made synchronized so that simultaneous accessing cannot take place.
With synchronization:
packageanonymous;
publicclassCounting{
privateintincrease_counter;
publicsynchronizedintincrease(){
increase_counter = increase_counter + 1;
returnincrease_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.
77. In the given code below, what is the significance of ... ?
publicvoidfooBarMethod(String... variables){
// method code}
• Ability to provide ... is a feature called varargs (variable arguments) which was introduced as part of Java 5.
• The function having ... in the above example indicates that it can receive multiple arguments of the datatype String.
• For example, the fooBarMethod can be called in multiple ways and we can still have one method to process the data as shown below:
fooBarMethod("foo", "bar");
fooBarMethod("foo", "bar", "boo");
fooBarMethod(newString[]{"foo", "var", "boo"});
publicvoidmyMethod(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?
classInterviewBit{
inti;
staticintj;
{
System.out.println(" Instance Block 1. Value of i = "+i);
}
static{
System.out.println(" Static Block 1. Value of j = "+j);
method_2();
}
{
i = 5;
}
static{
j = 10;
}
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
publicstaticvoidmain(String[] args){
InterviewBit ib = newInterviewBit();
}
publicvoidmethod_1(){
System.out.println(" Instance method. ");
}
static{
System.out.println(" Static Block 2. Value of j = "+j);
}
{
System.out.println(" Instance Block 2. Value of i = "+i);
method_1();
}
publicstaticvoidmethod_2(){
System.out.println(" Static method. ");
}
}
The Output we get by executing this program will be
Static Block 1. Value of j = 0
Static method.
Static Block 2. Value of j = 10
Instance Block 1. Value of i = 0
Instance Block 2. Value of i = 5
Instance method.
Welcome to InterviewBit
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 -
• Identification of Static Members from top to bottom.
• Execution of Static variable assignment and a Static block from top to bottom.
• Execution of the main method.
• Identification of Instance Members from top to bottom.
• Execution of Instance variable assignment and Instance block from top to bottom.
• Execution of Constructor.
In above steps from 4 to 6, will be executed for every object creation. If we create multiple objects then for every object these steps will be
performed.
Now from the above code, the execution will happen like this -
1. In the step of identification of static members. It is found that -
• 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.
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 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.
This is how the java program gets executed.
79. Define System.out.println().
System.out.println() is used to print the message on the console. System - It is a class present in java.lang package. Out is the static variable
of type PrintStream class present in the System class. println() is the method present in the PrintStream class.
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.
80. Can you explain the Java thread lifecycle?
Java thread life cycle is as follows:
• 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.
85. What do you understand by marker interfaces in Java?
Marker interfaces, also known as tagging interfaces are those interfaces that have no methods and constants defined in them. They are
there for helping the compiler and JVM to get run time-related information regarding the objects.
86. Explain the term “Double Brace Initialisation” in Java?
This is a convenient means of initializing any collections in Java. Consider the below example.
importjava.util.HashSet;
importjava.util.Set;
publicclassIBDoubleBraceDemo{
publicstaticvoidmain(String[] args){
Set<String> stringSets = newHashSet<String>()
{
{
add("set1");
add("set2");
add("set3");
}
};
doSomething(stringSets);
}
privatestaticvoiddoSomething(Set<String> stringSets){
System.out.println(stringSets);
}
}
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 expected.
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?
publicclassInterviewBit{
publicstaticvoidmain(String[] args){
System.out.println('b'+ 'i'+ 't');
}
}
“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
Hence 319 would be printed.
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.
publicclassIBGarbageCollect{
publicstaticvoidmain(String [] args){
String s1 = "Some String";
// s1 referencing String object - not yet eligible for GCs1 = 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){
String s1 = "To Garbage Collect";
String s2 = "Another Object";
System.out.println(s1); // s1 is not yet eligible for GCs1 = s2; // Point s1 to other object pointed by s2/* Here, the string object having the
content "To Garbage Collect" is not referred by any reference variable. Therefore, it is eligible for GC */}
}
Third Approach: Island of Isolation Approach: When 2 reference variables pointing to instances of the same class, and these variables refer
to only each other and the objects pointed by these 2 variables don't have any other references, then it is said to have formed an “Island of
Isolation” and these 2 objects are eligible for GC.
publicclassIBGarbageCollect{
IBGarbageCollect ib;
publicstaticvoidmain(String [] str){
IBGarbageCollect ibgc1 = newIBGarbageCollect();
IBGarbageCollect ibgc2 = newIBGarbageCollect();
ibgc1.ib = ibgc2; //ibgc1 points to ibgc2ibgc2.ib = ibgc1; //ibgc2 points to ibgc1ibgc1 = null;
ibgc2 = null;
/*
* We see that ibgc1 and ibgc2 objects refer
* to only each other and have no valid
* references- these 2 objects for island of isolcation - eligible for GC
*/}
}
90. In the below Java Program, how many objects are eligible for garbage collection?
classMain{
publicstaticvoidmain(String[] args){
int[][] num = newint[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 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.
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 after it calls sleep(). Despite the thread sleeping for a specified period of time, the lock will
not be released.
Java Programming Interview Questions
96. Check if a given string is palindrome using recursion.
/*
* Java program to check if a given inputted string is palindrome or not using recursion.
*/importjava.util.*;
publicclassInterviewBit{
publicstaticvoidmain(String args[]){
Scanner s = newScanner(System.in);
String word = s.nextLine();
System.out.println("Is "+word+" palindrome? - "+isWordPalindrome(word));
}
publicstaticbooleanisWordPalindrome(String word){
String reverseWord = getReverseWord(word);
//if word equals its reverse, then it is a palindromeif(word.equals(reverseWord)){
returntrue;
}
returnfalse;
}
//Pointers.inti = 0, j = str.length()-1;
System.out.println("\n");
//Rotation//Transposefor(inti = 0; i < no; i++){
for(intj = i; j < no; j++){
inttemp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
//Searching on the left half if a key exists there. if(key < arr[mid])
returnbinarySearch(arr, low, mid-1, key);
intcalculate(inta, intb){
try{
returna-b;
}catch(Exception e){
returna+b;
}finally{
returna*b;
}
}
}
classDriver{
publicstaticvoidmain(String args[]){
InterviewBit obj1 = newInterviewBit();
intresult = obj1.calculate(2, 3);
System.out.println("Result: "+ result);
}
}
5
-1
6
Run time Error
From <https://www.interviewbit.com/java-interview-questions/>
Java Interview Questions from interview javatpoint
Monday, February 13, 2023 11:08 PM
1) What is Java?
Java is the high-level, object-oriented, robust, secure programming language, platform-independent,
high performance, Multithreaded, and portable programming language. It was developed by James
Gosling in June 1991. It can also be known as the platform as it provides its own JRE and API.
9) What are the main differences between the Java platform and
other platforms?
There are the following differences between the Java platform and other platforms.
• Java is the software-based platform whereas other platforms may be the hardware platforms or
software-based platforms.
• Java is executed on the top of other hardware platforms whereas other platforms can only have
the hardware components.
10) What gives Java its 'write once and run anywhere' nature?
The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the
intermediate language between source code and machine code. This bytecode is not platform specific
and can be executed on any computer.
14) If I don't provide any arguments on the command line, then what
will the value stored in the String array passed into the main()
method, empty or NULL?
It is empty, but not null.
15) What if I write static public void instead of public static void?
The program compiles and runs correctly because the order of specifiers doesn't matter in Java.
More Details.
30) Does constructor return any value?
Ans: yes, The constructor implicitly returns the current instance of the class (You can't use an explicit
return type with the constructor). More Details.
35) What are the differences between the constructors and methods?
There are many differences between constructors and methods. They are given below.
Java Constructor Java Method
A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default constructor if you don't The method is not provided by the
have any constructor in a class. compiler in any case.
The constructor name must be same as the class name. The method name may or may not be
same as class name.
36) What is the output of the following Java program?
1. public class Test
2. {
3. Test(int a, int b)
4. {
5. System.out.println("a = "+a+" b = "+b);
6. }
7. Test(int a, float b)
8. {
9. System.out.println("a = "+a+" b = "+b);
10. }
11. public static void main (String args[])
12. {
13. byte a = 10;
14. byte b = 15;
15. Test test = new Test(a,b);
16. }
17. }
The output of the following program is:
a = 10 b = 15
Here, the data type of the variables a and b, i.e., byte gets promoted to int, and the first parameterized
constructor with the two integer parameters is called.
More Details.
41) What are the restrictions that are applied to the Java static
methods?
Two main restrictions are applied to the static methods.
• The static method can not use non-static data member or call the non-static method directly.
• this and super cannot be used in static context as they are non-static.
46) What if the static modifier is removed from the signature of the
main method?
Program compiles. However, at runtime, It throws an error "NoSuchMethodError."
47) What is the difference between static (class) method and instance
method?
static or class method instance method
1)A method that is declared as static is known as the static A method that is not declared as
method. static is known as the instance
method.
2)We don't need to create the objects to call the static methods. The object is required to call the
instance methods.
3)Non-static (instance) members cannot be accessed in the Static and non-static variables both
static context (static method, static block, and static nested can be accessed in instance methods.
class) directly.
4)For example: public static int cube(int n){ return n*n*n;} For example: public void msg(){...}.
More Details.
56) What are the advantages of passing this into a method instead of
the current class object itself?
As we know, that this refers to the current class object, therefore, it must be similar to the current class
object. However, there can be two main advantages of passing this into a method instead of the current
class object.
• this is a final variable. Therefore, this cannot be assigned to any new value whereas the current
class object might not be final and can be changed.
• this can be used in the synchronized block.
68) What are the differences between this and super keyword?
There are the following differences between this and super keyword.
• The super keyword always points to the parent class contexts whereas this keyword always points
to the current class context.
• The super keyword is primarily used for initializing the base class variables within the derived class
constructor whereas this keyword primarily used to differentiate between local and instance
variables when passed in the class constructor.
• The super and this must be the first statement inside constructor otherwise the compiler will
throw an error.
85) Can we modify the throws clause of the superclass method while
overriding it in the subclass?
Yes, we can modify the throws clause of the superclass method while overriding it in the subclass.
However, there are some rules which are to be followed while overriding in case of exception handling.
• If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception, but it can declare the unchecked exception.
• If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
Output
Derived method called ...
Explanation
The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the reference
variable b (of type Base class) refers to the instance of the Derived class. Here, Runtime polymorphism is
achieved between class Base and Derived. At compile time, the presence of method baseMethod
checked in Base class, If it presence then the program compiled otherwise the compiler error will be
shown. In this case, baseMethod is present in Base class; therefore, it is compiled successfully. However,
at runtime, It checks whether the baseMethod has been overridden by Derived class, if so then the
Derived class method is called otherwise Base class method is called. In this case, the Derived class
overrides the baseMethod; therefore, the Derived class method is called.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error
More Details.
100) What is the difference between the final method and abstract
method?
The main difference between the final method and abstract method is that the abstract method cannot
be final as we need to override them in the subclass to give its definition.
From <https://www.javatpoint.com/corejava-interview-questions>
101) What is the difference between compile-time polymorphism and
runtime polymorphism?
There are the following differences between compile-time polymorphism and runtime polymorphism.
SN compile-time polymorphism Runtime polymorphism
1 In compile-time polymorphism, call In runtime polymorphism, call to an overridden method
to a method is resolved at compile- is resolved at runtime.
time.
2 It is also known as static binding, It is also known as dynamic binding, late binding,
early binding, or overloading. overriding, or dynamic method dispatch.
3 Overloading is a way to achieve Overriding is a way to achieve runtime polymorphism in
compile-time polymorphism in which, we can redefine some particular method or
which, we can define multiple variable in the derived class. By using overriding, we can
methods or constructors with give some specific implementation to the base class
different signatures. properties in the derived class.
4 It provides fast execution because It provides slower execution as compare to compile-time
the type of an object is determined because the type of an object is determined at run-time.
at compile-time.
5 Compile-time polymorphism Run-time polymorphism provides more flexibility
provides less flexibility because all because all the things are resolved at runtime.
the things are resolved at compile-
time.
An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object
of Dog can be referred by either Dog or Animal class.
111) Is the following program written correctly? If yes then what will
be the output of the program?
1. abstract class Calculate
2. {
3. abstract int multiply(int a, int b);
4. }
5.
6. public class Main
7. {
8. public static void main(String[] args)
9. {
10. int result = new Calculate()
11. {
12. @Override
13. int multiply(int a, int b)
14. {
15. return a*b;
16. }
17. }.multiply(12,32);
18. System.out.println("result = "+result);
19. }
20. }
Yes, the program is written correctly. The Main class provides the definition of abstract method multiply
declared in abstract class Calculation. The output of the program will be:
Output
384
112) Can you use abstract and final both with a method?
No, because we need to override the abstract method to provide its implementation, whereas we can't
override the final method.
118) What are the differences between abstract class and interface?
Abstract class Interface
An abstract class can have a method body (non-abstract The interface has only abstract methods.
methods).
An abstract class can have instance variables. An interface cannot have instance variables.
An abstract class can have the constructor. The interface cannot have the constructor.
An abstract class can have static methods. The interface cannot have static methods.
You can extend one abstract class. You can implement multiple interfaces.
The abstract class can provide the implementation of The Interface can't provide the
the interface. implementation of the abstract class.
The abstract keyword is used to declare an abstract The interface keyword is used to declare an
class. interface.
An abstract class can extend another Java class and An interface can extend another Java
implement multiple Java interfaces. interface only.
An abstract class can be extended using keyword An interface class can be implemented using
extends keyword implements
A Java abstract class can have class members like Members of a Java interface are public by
private, protected, etc. default.
Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
119) Can we define private and protected modifiers for the members
in interfaces?
No, they are implicitly public.
More details.
125) What are the advantages of defining packages in Java?
By defining packages, we can avoid the name conflicts between the same class names defined in
different packages. Packages also enable the developer to organize the similar classes more effectively.
For example, one can clearly understand that the classes present in java.io package are used to perform
io related operations.
129) Can I import same package/class twice? Will the JVM load the
package twice at runtime?
One can import the same package or the same class multiple times. Neither compiler nor JVM complains
about it. However, the JVM will internally load the class only once no matter how many times you
import the same class.
More details.
More details.
171) What are the types of inner classes (non-static nested class) used
in Java?
There are mainly three types of inner classes used in Java.
Type Description
Member Inner A class created within class and outside method.
Class
Anonymous Inner A class created for implementing an interface or extending class. Its name is
Class decided by the java compiler.
Local Inner Class A class created within the method.
172) Is there any difference between nested classes and inner classes?
Yes, inner classes are non-static nested classes. In other words, we can say that inner classes are the
part of nested classes.
More details.
173) Can we access the non-final local variable, inside the local inner
class?
No, the local variable must be constant if you want to access it in the local inner class.
More details.
174) How many class files are created on compiling the OuterClass in
the following program?
1. public class Person {
2. String name, age, address;
3. class Employee{
4. float salary=10000;
5. }
6. class BusinessMen{
7. final String gstin="£4433drt3$";
8. }
9. public static void main (String args[])
10. {
11. Person p = new Person();
12. }
13. }
3 class-files will be created named as Person.class, Person$BusinessMen.class, and Person
$Employee.class.
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
2) By assigning a reference to another:
1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
1. new Employee();
InputStream Hierarchy
192) What are the super most classes for all the streams?
All the stream classes can be divided into two types of classes that are ByteStream classes and
CharacterStream Classes. The ByteStream classes are further divided into InputStream classes and
OutputStream classes. CharacterStream classes are also divided into Reader classes and Writer classes.
The SuperMost classes for all the InputStream classes is java.io.InputStream and for all the output
stream classes is java.io.OutPutStream. Similarly, for all the reader classes, the super-most class is
java.io.Reader, and for all the writer classes, it is java.io.Writer.
198) In Java, How many ways you can take input from the console?
In Java, there are three ways by using which, we can take input from the console.
• Using BufferedReader class: we can take input from the console by wrapping System.in into an
InputStreamReader and passing it into the BufferedReader. It provides an efficient reading as the
input gets buffered. Consider the following example.
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. public class Person
5. {
6. public static void main(String[] args) throws IOException
7. {
8. System.out.println("Enter the name of the person");
9. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
10. String name = reader.readLine();
11. System.out.println(name);
12. }
13. }
• Using Scanner class: The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace by default. It provides many methods to read and parse various primitive values. Java
Scanner class is widely used to parse text for string and primitive types using a regular expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
Consider the following example.
1. import java.util.*;
2. public class ScannerClassExample2 {
3. public static void main(String args[]){
4. String str = "Hello/This is JavaTpoint/My name is Abhishek.";
5. //Create scanner with the specified String Object
6. Scanner scanner = new Scanner(str);
7. System.out.println("Boolean Result: "+scanner.hasNextBoolean());
8. //Change the delimiter of this scanner
9. scanner.useDelimiter("/");
10. //Printing the tokenized Strings
11. System.out.println("---Tokenizes String---");
12. while(scanner.hasNext()){
13. System.out.println(scanner.next());
14. }
15. //Display the new delimiter
16. System.out.println("Delimiter used: " +scanner.delimiter());
17. scanner.close();
18. }
19. }
20.
• Using Console class: The Java Console class is used to get input from the console. It provides
methods to read texts and passwords. If you read the password using the Console class, it will not
be displayed to the user. The java.io.Console class is attached to the system console internally.
The Console class is introduced since 1.5. Consider the following example.
1. import java.io.Console;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }
More details.
201) How can you avoid serialization in child class if the base class is
implementing the Serializable interface?
It is very tricky to prevent serialization of child class if the base class is intended to implement the
Serializable interface. However, we cannot do it directly, but the serialization can be avoided by
implementing the writeObject() or readObject() methods in the subclass and throw
NotSerializableException from these methods. Consider the following example.
1. import java.io.FileInputStream;
2. import java.io.FileOutputStream;
3. import java.io.IOException;
4. import java.io.NotSerializableException;
5. import java.io.ObjectInputStream;
6. import java.io.ObjectOutputStream;
7. import java.io.Serializable;
8. class Person implements Serializable
9. {
10. String name = " ";
11. public Person(String name)
12. {
13. this.name = name;
14. }
15. }
16. class Employee extends Person
17. {
18. float salary;
19. public Employee(String name, float salary)
20. {
21. super(name);
22. this.salary = salary;
23. }
24. private void writeObject(ObjectOutputStream out) throws IOException
25. {
26. throw new NotSerializableException();
27. }
28. private void readObject(ObjectInputStream in) throws IOException
29. {
30. throw new NotSerializableException();
31. }
32.
33. }
34. public class Test
35. {
36. public static void main(String[] args)
37. throws Exception
38. {
39. Employee emp = new Employee("Sharma", 10000);
40.
41. System.out.println("name = " + emp.name);
42. System.out.println("salary = " + emp.salary);
43.
44. FileOutputStream fos = new FileOutputStream("abc.ser");
45. ObjectOutputStream oos = new ObjectOutputStream(fos);
46.
47. oos.writeObject(emp);
48.
49. oos.close();
50. fos.close();
51.
52. System.out.println("Object has been serialized");
53.
54. FileInputStream f = new FileInputStream("ab.txt");
55. ObjectInputStream o = new ObjectInputStream(f);
56.
57. Employee emp1 = (Employee)o.readObject();
58.
59. o.close();
60. f.close();
61.
62. System.out.println("Object has been deserialized");
63.
64. System.out.println("name = " + emp1.name);
65. System.out.println("salary = " + emp1.salary);
66. }
67. }
202) Can a Serialized object be transferred via network?
Yes, we can transfer a serialized object via network because the serialized object is stored in the
memory in the form of bytes and can be transmitted over the network. We can also write the serialized
object to the disk or the database.
209) What are the steps that are followed when two computers
connect through TCP?
There are the following steps that are performed when two computers connect through TCP.
• The ServerSocket object is instantiated by the server which denotes the port number to which, the
connection will be made.
• After instantiating the ServerSocket object, the server invokes accept() method of ServerSocket
class which makes server wait until the client attempts to connect to the server on the given port.
• Meanwhile, the server is waiting, a socket is created by the client by instantiating Socket class. The
socket class constructor accepts the server port number and server name.
• The Socket class constructor attempts to connect with the server on the specified name. If the
connection is established, the client will have a socket object that can communicate with the
server.
• The accept() method invoked by the server returns a reference to the new socket on the server
that is connected with the server.
217) Can you access the private method from outside the class?
Yes, by changing the runtime behavior of a class if the class is not secured.
More details.
228) Write a Java program that prints all the values given at
command-line.
Program
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
9. compile by > javac A.java
10. run by > java A sonoo jaiswal 1 3 abc
Output
sonoo
jaiswal
1
3
abc
236) Can you write a Java class that could be used both as an applet as
well as an application?
Yes. Add a main() method to the applet.
244) What are the steps involved to write RMI based programs?
There are 6 steps which are performed to write RMI based programs.
• Create the remote interface.
• Provide the implementation of the remote interface.
• Compile the implementation class and create the stub and skeleton objects using the rmic tool.
• Start the registry service by the rmiregistry tool.
• Create and start the remote application.
• Create and start the client application.
From <https://www.javatpoint.com/corejava-interview-questions-2>
• A Program in the execution is called the process whereas; A thread is a subset of the process
• Processes are independent whereas threads are the subset of process.
• Process have different address space in memory, while threads contain a shared address space.
• Context switching is faster between the threads as compared to processes.
• Inter-process communication is slower and expensive than inter-thread communication.
• Any change in Parent process doesn't affect the child process whereas changes in parent thread
can affect the child thread.
4) What do you understand by inter-thread communication?
• The process of communication between synchronized threads is termed as inter-thread
communication.
• Inter-thread communication is used to avoid thread polling in Java.
• The thread is paused running in its critical section, and another thread is allowed to enter (or lock)
in the same critical section to be executed.
• It can be obtained by wait(), notify(), and notifyAll() methods.
11) Differentiate between the Thread class and Runnable interface for
creating a Thread?
The Thread can be created by using two ways.
• By extending the Thread class
• By implementing the Runnable interface
However, the primary differences between both the ways are given below:
• By extending the Thread class, we cannot extend any other class, as Java does not allow multiple
inheritances while implementing the Runnable interface; we can also extend other base class(if
required).
• By extending the Thread class, each of thread creates the unique object and associates with it
while implementing the Runnable interface; multiple threads share the same object
• Thread class provides various inbuilt methods such as getPriority(), isAlive and many more while
the Runnable interface provides a single method, i.e., run().
1. Collection interface: Collection (java.util.Collection) is the primary interface, and every collection
must implement this interface.
Syntax:
1. public interface Collection<E>extends Iterable
Where <E> represents that this interface is of Generic type
2. List interface: List interface extends the Collection interface, and it is an ordered collection of objects.
It contains duplicate elements. It also allows random access of elements.
Syntax:
1. public interface List<E> extends Collection<E>
3. Set interface: Set (java.util.Set) interface is a collection which cannot contain duplicate elements. It
can only include inherited methods of Collection interface
Syntax:
1. public interface Set<E> extends Collection<E>
Queue interface: Queue (java.util.Queue) interface defines queue data structure, which stores the
elements in the form FIFO (first in first out).
Syntax:
1. public interface Queue<E> extends Collection<E>
4. Dequeue interface: it is a double-ended-queue. It allows the insertion and removal of elements from
both ends. It implants the properties of both Stack and queue so it can perform LIFO (Last in first out)
stack and FIFO (first in first out) queue, operations.
Syntax:
1. public interface Dequeue<E> extends Queue<E>
5. Map interface: A Map (java.util.Map) represents a key, value pair storage of elements. Map interface
does not implement the Collection interface. It can only contain a unique key but can have duplicate
elements. There are two interfaces which implement Map in java that are Map interface and Sorted
Map.
24) What is the default size of load factor in hashing based collection?
The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor.
For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
27) What is the difference between the length of an Array and size of
ArrayList?
The length of an array can be obtained using the property of length whereas ArrayList does not support
length property, but we can use size() method to get the number of objects in the list.
Finding the length of the array
1. Int [] array = new int[4];
2. System.out.println("The size of the array is " + array.length);
3.
Finding the size of the ArrayList
1. ArrayList<String> list=new ArrayList<String>();
2. list.add("ankit");
3. list.add("nippun");
4. System.out.println(list.size());
5.
From <https://www.javatpoint.com/java-collections-interview-questions>
From <https://www.javatpoint.com/java-multithreading-interview-questions>
Java Interview Questions from simplilern
Monday, February 13, 2023 11:23 PM
3. What do you get in the Java download file? How do they differ from
one another?
We get two major things along with the Java Download file.
JDK - Java Development Kit
JRE - Java Runtime Environment
JDK JRE
Abbreviation for JavaDevelopment Kit Abbreviation for Java Runtime Environment
JDK is a dedicated kit for solely software JRE is a set of software and library designed for executing
development Java Programs
Unlike JVM, JDK is Platform Dependent Unlike JVM, JRE is also Platform Dependent
JDK package is a set of tools for debugging JRE Package is one that only supports files and libraries for
and Developing a runtime environment
JDK package will be provided with an JRE Package does not get an installer but has only a
installer file runtime environment
4. What is a ClassLoader?
A classloader in Java is a subsystem of Java Virtual Machine, dedicated to loading class files when a
program is executed; ClassLoader is the first to load the executable file.
Java has Bootstrap, Extension, and Application classloaders.
Also Read: What is Bootstrap and How to Embed Bootstrap into Angular?
5. What are the Memory Allocations available in JavaJava?
Java has five significant types of memory allocations.
• Class Memory
• Heap Memory
• Stack Memory
• Program Counter-Memory
• Native Method Stack Memory
6. What are the differences between Heap and Stack Memory in Java?
Stack memory in data structures is the amount of memory allocated to each individual programme. It is
a fixed memory space. Heap memory, in contrast, is the portion that was not assigned to the Java code
but will be available for use by the Java code when it is required, which is generally during the program's
runtime.
7. Will the program run if we write static public void main?
Yes, the program will successfully execute if written so. Because, in Java, there is no specific rule for the
order of specifiers
8. What is the default value stored in Local Variables?
Neither the Local Variables nor any primitives and Object references have any default value stored in
them.
9. Explain the expected output of the following code segment?
public class Simplilearn
{
public static void main (String args[])
{
System.out.println(100 + 100 +“Simplilearn");
System.out.println(“E-Learning Company" + 100 + 100);
}
}
The answers for the two print statements are as follows.
• 200Simplilearn
• E-Learning Company100100
Here's How to Land a Top Software Developer Job
Full Stack Development-MEANExplore Program
if (isPossible(n))
printf("%s", "Yes");
else
printf("%s", "No");
return 0;
}
73. Write a Java program for solving the Tower of Hanoi Problem.
// Java recursive program to solve tower of hanoi puzzle
class GFG
{
// Java recursive function to solve tower of hanoi puzzle
static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
System.out.println("Move disk 1 from rod " + from_rod + " to rod " +to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " +to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
// Driver method
public static void main(String args[])
{
int n = 4; // Number of disks
towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods
}
}
74. Implement Binary Search in Java using recursion.
// Java Program to Illustrate Recursive Binary Search
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Method 1
// Recursive binary search
// Returns index of x if it is present
// in arr[l..r], else return -1
int binarySearch(int arr[], int l, int r, int x)
{
// Restrict the boundary of right index
// and the left index to prevent
// overflow of indices
if (r >= l && l <= arr.length - 1) {
int mid = l + (r - l) / 2;
// If the element is present
// at the middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then it can
// only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Length of array
int n = arr.length;
// Custom element to be checked
// whether present or not
int x = 10;
// Calling above method
int result = ob.binarySearch(arr, 0, n - 1, x);
// Element present
if (result == -1)
// Print statement
System.out.println("Element not present");
From <https://www.simplilearn.com/tutorials/java-tutorial/java-interview-questions>
Java Interview Questions from sedureka
Monday, February 13, 2023 11:27 PM
Q12. What are the differences between HashMap and HashTable in Java?
HashMap Hashtable
It is non synchronized. It cannot be shared between many It is synchronized. It is thread-safe and can
threads without proper synchronization code. be shared with many threads.
It permits one null key and multiple null values. It does not permit any null key or value.
is a new class introduced in JDK 1.2. It was present in earlier versions of java as
well.
It is faster. It is slower.
It is traversed through the iterator. It is traversed through Enumerator and
Iterator.
It uses fail fast iterator. It uses an enumerator which is not fail
fast.
It inherits AbstractMap class. It inherits Dictionary class.
Q16. Contiguous memory locations are usually used for storing actual values in an array but not in
ArrayList. Explain.
An array generally contains elements of the primitive data types such as int, float, etc. In such cases, the
array directly stores these elements at contiguous memory locations. While an ArrayList does not
contain primitive data types. An arrayList contains the reference of the objects at different memory
locations instead of the object itself. That is why the objects are not stored at contiguous memory
locations.
Q17. How is the creation of a String using new() different from that of a literal?
When we create a string using new(), a new object is created. Whereas, if we create a string using the
string literal syntax, it may return an already existing object with the same name.
Q18. Why is synchronization necessary? Explain with the help of a relevant example.
Java allows multiple threads to execute. They may be accessing the same variable or object.
Synchronization helps to execute threads one after another.
It is important as it helps to execute all concurrent threads while being in sync. It prevents memory
consistency errors due to access to shared memory. An example of synchronization code is-
Programming & Frameworks Training
As we have synchronized this function, this thread can only use the object after the previous thread has
used it.
Q19. Explain the term “Double Brace Initialization” in Java?
Double Brace Initialization is a Java term that refers to the combination of two independent processes.
There are two braces used in this. The first brace creates an anonymous inner class. The second brace is
an initialization block. When these both are used together, it is known as Double Brace Initialization. The
inner class has a reference to the enclosing outer class, generally using the ‘this’ pointer. It is used to do
both creation and initialization in a single statement. It is generally used to initialize collections. It
reduces the code and also makes it more readable.
Q20. Why is it said that the length() method of String class doesn’t return accurate results?
The length() method of String class doesn’t return accurate results because
it simply takes into account the number of characters within in the String. In other words, code points
outside of the BMP (Basic Multilingual Plane), that is, code points having a value of U+10000 or above,
will be ignored.
The reason for this is historical. One of Java’s original goals was to consider all text as Unicode; yet,
Unicode did not define code points outside of the BMP at the time. It was too late to modify char by the
time Unicode specified such code points.
Q21. What are the differences between Heap and Stack Memory in Java?
The major difference between Heap and Stack memory are:
Features Stack Heap
Memory Stack memory is used only by one thread of Heap memory is used by all the parts of
execution. the application.
Access Stack memory can’t be accessed by other Objects stored in the heap are globally
threads. accessible.
Memory Follows LIFO manner to free memory. Memory management is based on the
Management generation associated with each object.
Lifetime Exists until the end of execution of the Heap memory lives from the start till
thread. the end of application execution.
Usage Stack memory only contains local primitive Whenever an object is created, it’s
and reference variables to objects in heap always stored in the Heap space.
space.
Want to upskill yourself to get ahead in Career? Check out this video
Core Java Interview Quesions And Answers for Freshers and Experienced
This 120+ core java interview question and answer will help freshers and experience to crack the
interview in 1st attempt.
If a child class inherits the property from multiple classes is known as multiple inheritance. Java does not
allow to extend multiple classes.
The problem with multiple inheritance is that if multiple parent classes have the same method name,
then at runtime it becomes difficult for the compiler to decide which method to execute from the child
class.
Therefore, Java doesn’t support multiple inheritance. The problem is commonly referred to as Diamond
Problem.
In case you are facing any challenges with these java interview questions, please comment on your
problems in the section below.
Q11. What is encapsulation in Java?
Encapsulation is a mechanism where you bind your data(variables) and code(methods) together as a
single unit. Here, the data is hidden from the outer world and can be accessed only via current class
methods. This helps in protecting the data from any unnecessary modification. We can achieve
encapsulation in Java by:
• Declaring the variables of a class as private.
• Providing public setter and getter methods to modify and view the values of the variables.
Q12. What is an association?
Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take
the example of Teacher and Student. Multiple students can associate with a single teacher and a single
student can associate with multiple teachers but there is no ownership between the objects and both
have their own lifecycle. These relationships can be one to one, one to many, many to one and many to
many.
Q13. What do you mean by aggregation?
An aggregation is a specialized form of Association where all object has their own lifecycle but there is
ownership and child object can not belong to another parent object. Let’s take an example of
Department and teacher. A single teacher can not belong to multiple departments, but if we delete the
department teacher object will not destroy.
Q14. What is composition in Java?
Composition is again a specialized form of Aggregation and we can call this as a “death” relationship. It is
a strong type of Aggregation. Child object does not have their lifecycle and if parent object deletes all
child object will also be deleted. Let’s take again an example of a relationship between House and
rooms. House can contain multiple rooms there is no independent life of room and any room can not
belongs to two different houses if we delete the house room will automatically delete.
Q15. What is a marker interface?
A Marker interface can be defined as the interface having no data member and member functions. In
simpler terms, an empty interface is called the Marker interface. The most common examples of Marker
interface in Java are Serializable, Cloneable etc. The marker interface can be declared as follows.
1 public interface Serializable{
2 }
Q16. What is object cloning in Java?
Object cloning in Java is the process of creating an exact copy of an object. It basically means the ability
to create an object with a similar state as the original object. To achieve this, Java provides a method
clone() to make use of this functionality. This method creates a new instance of the class of the current
object and then initializes all its fields with the exact same contents of corresponding fields. To object
clone(), the marker interface java.lang.Cloneable must be implemented to avoid any runtime
exceptions. One thing you must note is Object clone() is a protected method, thus you need to override
it.
Q17. What is a copy constructor in Java?
Copy constructor is a member function that is used to initialize an object using another object of the
same class. Though there is no need for copy constructor in Java since all objects are passed by
reference. Moreover, Java does not even support automatic pass-by-value.
Q18. What is a constructor overloading in Java?
In Java, constructor overloading is a technique of adding any number of constructors to a class each
having a different parameter list. The compiler uses the number of parameters and their types in the list
to differentiate the overloaded constructors.
1 class Demo
2 {
3 int i;
4 public Demo(int a)
5 {
6 i=k;
7 }
8 public Demo(int a, int b)
9 {
10 //body
11 }
12 }
In case you are facing any challenges with these java interview questions, please comment on your
problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained
from professionals on this technology, you can opt for a structured training from edureka!
Servlets – Java Interview Questions
Q1. What is a servlet?
• Java Servlet is server-side technologies to extend the capability of web servers by providing
support for dynamic response and data persistence.
• The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our
own servlets.
• All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle
methods. When implementing a generic service, we can extend the GenericServlet class provided
with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(),
for handling HTTP-specific services.
• Most of the times, web applications are accessed using HTTP protocol and thats why we mostly
extend HttpServlet class. Servlet API hierarchy is shown in below image.
Q2. What are the differences between Get and Post methods?
Get Post
Limited amount of data can be sent because data is Large amount of data can be sent because data is
sent in header. sent in body.
Not Secured because data is exposed in URL bar. Secured because data is not exposed in URL bar.
Can be bookmarked Cannot be bookmarked
Idempotent Non-Idempotent
It is more efficient and used than Post It is less efficient and used
1. Servlet is loaded
2. Servlet is instantiated
3. Servlet is initialized
4. Service the request
5. Servlet is destroyed
Q6. How does cookies work in Servlets?
• Cookies are text data sent by server to the client and it gets saved at the client local machine.
• Servlet API provides cookies support through javax.servlet.http.Cookie class that implements
Serializable and Cloneable interfaces.
• HttpServletRequest getCookies() method is provided to get the array of Cookies from request,
since there is no point of adding Cookie to request, there are no methods to set or add cookie to
request.
• Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in
response header, there are no getter methods for cookie.
Q7. What are the differences between ServletContext vs
ServletConfig?
The difference between ServletContext and ServletConfig in Servlets JSP is in below tabular format.
ServletConfig ServletContext
Servlet config object represent single servlet It represent whole web application running on
particular JVM and common for all the servlet
Its like local parameter associated with Its like global parameter associated with whole
particular servlet application
It’s a name value pair defined inside the servlet ServletContext has application wide scope so define
section of web.xml file so it has servlet wide outside of servlet tag in web.xml file.
scope
getServletConfig() method is used to get the getServletContext() method is used to get the
config object context object.
for example shopping cart of a user is a specific To get the MIME type of a file or application session
to particular user so here we can use servlet related information is stored using servlet context
config object.
In case you are facing any challenges with these java interview questions, please comment on your
problems in the section below.
6. What is the purpose of JDBC ResultSet interface?
The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the
information from the database.
7. What is JDBC ResultSetMetaData interface?
The ResultSetMetaData interface returns the information of table such as total number of columns,
column name, column type etc.
8. What is JDBC DatabaseMetaData interface?
The DatabaseMetaData interface returns the information of the database such as username, driver
name, driver version, number of tables, number of views etc.
9. What do you mean by batch processing in JDBC?
Batch processing helps you to group related SQL statements into a batch and execute them instead of
executing a single query. By using batch processing technique in JDBC, you can execute multiple queries
which makes the performance faster.
10. What is the difference between execute, executeQuery,
executeUpdate?
Statement execute(String query) is used to execute any SQL query and it returns TRUE if the result is an
ResultSet such as running Select queries. The output is FALSE when there is no ResultSet object such as
running Insert or Update queries. We can use getResultSet() to get the ResultSet and getUpdateCount()
method to retrieve the update count.
Statement executeQuery(String query) is used to execute Select queries and returns the ResultSet.
ResultSet returned is never null even if there are no records matching the query. When executing select
queries we should use executeQuery method so that if someone tries to execute insert/update
statement it will throw java.sql.SQLException with message “executeQuery method can not be used for
update”.
Statement executeUpdate(String query) is used to execute Insert/Update/Delete (DML) statements or
DDL statements that returns nothing. The output is int and equals to the row count for SQL Data
Manipulation Language (DML) statements. For DDL statements, the output is 0.
You should use execute() method only when you are not sure about the type of statement else use
executeQuery or executeUpdate method.
Q11. What do you understand by JDBC Statements?
JDBC statements are basically the statements which are used to send SQL commands to the database
and retrieve data back from the database. Various methods like execute(), executeUpdate(),
executeQuery, etc. are provided by JDBC to interact with the database.
JDBC supports 3 types of statements:
1. Statement: Used for general purpose access to the database and executes a static SQL query at
runtime.
2. PreparedStatement: Used to provide input parameters to the query during execution.
3. CallableStatement: Used to access the database stored procedures and helps in accepting runtime
parameters.
In case you are facing any challenges with these java interview questions, please comment your
problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained
from professionals on this technology, you can opt for a structured training from edureka!
Spring Framework – Java Interview Questions
Q1. What is Spring?
Wikipedia defines the Spring framework as “an application framework and inversion of control container
for the Java platform. The framework’s core features can be used by any Java application, but there are
extensions for building web applications on top of the Java EE platform.” Spring is essentially a
lightweight, integrated framework that can be used for developing enterprise applications in java.
Q2. Name the different modules of the Spring framework.
Some of the important Spring Framework modules are:
• Spring Context – for dependency injection.
• Spring AOP – for aspect oriented programming.
• Spring DAO – for database operations using DAO pattern
• Spring JDBC – for JDBC and DataSource support.
• Spring ORM – for ORM tools support such as Hibernate
• Spring Web Module – for creating web applications.
• Spring MVC – Model-View-Controller implementation for creating web applications, web services
etc.
Q3. List some of the important annotations in annotation-based
Spring configuration.
The important annotations are:
• @Required
• @Autowired
• @Qualifier
• @Resource
• @PostConstruct
• @PreDestroy
Q4. Explain Bean in Spring and List the different Scopes of Spring
bean.
Beans are objects that form the backbone of a Spring application. They are managed by the Spring IoC
container. In other words, a bean is an object that is instantiated, assembled, and managed by a Spring
IoC container.
There are five Scopes defined in Spring beans.
• Singleton: Only one instance of the bean will be created for each container. This is the default
scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared
instance variables otherwise it might lead to data inconsistency issues because it’s not thread-
safe.
• Prototype: A new instance will be created every time the bean is requested.
• Request: This is same as prototype scope, however it’s meant to be used for web applications. A
new instance of the bean will be created for each HTTP request.
• Session: A new bean will be created for each HTTP session by the container.
• Global-session: This is used to create global session beans for Portlet applications.
In case you are facing any challenges with these java interview questions, please comment on your
problems in the section below.
Q5. Explain the role of DispatcherServlet and ContextLoaderListener.
DispatcherServlet is basically the front controller in the Spring MVC application as it loads the spring
bean configuration file and initializes all the beans that have been configured. If annotations are
enabled, it also scans the packages to configure any bean annotated with @Component, @Controller,
@Repository or @Service annotations.
ContextLoaderListener, on the other hand, is the listener to start up and shut down the
WebApplicationContext in Spring root. Some of its important functions includes tying up the lifecycle of
Application Context to the lifecycle of the ServletContext and automating the creation of
ApplicationContext.
Q14. What is a finally block? Is there a case when finally will not
execute?
Finally block is a block which always executes a set of statements. It is always associated with a try block
regardless of any exception that occurs or not.
Yes, finally will not be executed if the program exits either by calling System.exit() or by causing a fatal
error that causes the process to abort.
Q15. What is synchronization?
Synchronization refers to multi-threading. A synchronized block of code can be executed by only one
thread at a time. As Java supports execution of multiple threads, two or more threads may access the
same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to
be in sync. Synchronization avoids memory consistency errors caused due to inconsistent view of shared
memory. When a method is declared as synchronized the thread holds the monitor for that method’s
object. If another thread is executing the synchronized method the thread is blocked until that thread
releases the monitor.
Q16. Can we write multiple catch blocks under single try block?
Yes we can have multiple catch blocks under single try block but the approach should be from specific to
general. Let’s understand this with a programmatic example.
1 public class Example {
2 public static void main(String args[]) {
3 try {
4 int a[]= new int[10];
5 a[10]= 10/0;
6 }
7 catch(ArithmeticException e)
8 {
9 System.out.println("Arithmetic exception in first catch block");
10 }
11 catch(ArrayIndexOutOfBoundsException e)
12 {
13 System.out.println("Array index out of bounds in second catch block");
14 }
15 catch(Exception e)
16 {
17 System.out.println("Any exception in third catch block");
18 }
19 }
Q17. What are the important methods of Java Exception Class?
Methods are defined in the base class Throwable. Some of the important methods of Java exception
class are stated below.
1. String getMessage() – This method returns the message String about the exception. The message
can be provided through its constructor.
2. public StackTraceElement[] getStackTrace() – This method returns an array containing each
element on the stack trace. The element at index 0 represents the top of the call stack whereas
the last element in the array represents the method at the bottom of the call stack.
3. Synchronized Throwable getCause() – This method returns the cause of the exception or null id as
represented by a Throwable object.
4. String toString() – This method returns the information in String format. The returned String
contains the name of Throwable class and localized message.
5. void printStackTrace() – This method prints the stack trace information to the standard error
stream.
Q18. What is OutOfMemoryError in Java?
OutOfMemoryError is the subclass of java.lang.Error which generally occurs when our JVM runs out of
memory.
Q19. What is a Thread?
A thread is the smallest piece of programmed instructions which can be executed independently by a
scheduler. In Java, all the programs will have at least one thread which is known as the main thread. This
main thread is created by the JVM when the program starts its execution. The main thread is used to
invoke the main() of the program.
Q20. What are the two ways to create a thread?
In Java, threads can be created in the following two ways:-
• By implementing the Runnable interface.
• By extending the Thread
Q21. What are the different types of garbage collectors in Java?
Garbage collection in Java a program which helps in implicit memory management. Since in Java, using
the new keyword you can create objects dynamically, which once created will consume some memory.
Once the job is done and there are no more references left to the object, Java using garbage collection
destroys the object and relieves the memory occupied by it. Java provides four types of garbage
collectors:
• Serial Garbage Collector
• Parallel Garbage Collector
• CMS Garbage Collector
• G1 Garbage Collector
From <https://www.edureka.co/blog/interview-questions/java-interview-questions/>
Sunday, March 13, 2022 9:57 PM
Thursday, February 10, 2022 5:42 PM