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.
List the features of Java Programming language.
“There are the following features in Java Programming Language.
Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.
Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.
Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on which its code is executed. Java doesn’t depend upon the operating system to be executed.
Secured: Java is secured because it doesn’t use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.
Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn’t exist in Java.
Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is “”close”” to native code. It is still a little bit slower than a compiled language (e.g., C++).
Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn’t occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.
Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.”
What do you understand by Java virtual machine?
Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.
Java Interview Questions
What is the difference between JDK, JRE, and JVM?
“JVM
JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.
JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
JDK
JDK is an acronym for Java Development Kit. It is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform”
How many types of memory areas are allocated by JVM?
“Many types:
Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data, and the code for methods.
Heap: It is the runtime data area in which the memory is allocated to the objects
Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
Program Counter Register: PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
Native Method Stack: It contains all the native methods used in the application.”
What is JIT compiler?
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
Advance Java Interview Questions
What is the platform?
A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides the software-based platform.
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.”
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.
Java Interview Questions
What is class loader?
“Class loader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the class loader. There are three built-in class loaders in Java.
Bootstrap Class Loader: This is the first class loader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes, etc.
Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using “”-cp”” or “”-classpath”” switch. It is also known as Application classloader.”
Is Empty .java file name a valid source file name?
“Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classname Let’s take a simple example:
//save by .java only
class A{
public static void main(String args[]){
System.out.println(“”Hello java””);
}
}
//compile by javac .java
//run by java A
compile it by javac .java
run it by java A”
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.
Advance Java Interview Questions
What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references.
What are the various access specifiers in Java?
“In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. In Java, there are four access specifiers given below.
Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
Private The private class, methods, or variables defined as private can be accessed within the class only.”
What is the purpose of static methods and variables?
“The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object. The static variables are stored in the class area, and we do not need to create the object to access such variables. Therefore, static is used in the case, where we need to define variables or methods which are common to all the objects of the class.
For example, In the class simulating the collection of the students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static.”
Java Interview Questions
What are the advantages of Packages in Java?
“There are various advantages of defining packages in Java.
Packages avoid the name clashes.
The Package provides easier access control.
We can also have the hidden classes that are not visible outside and used by the package.
It is easier to locate the related classes.”
What is the output of the following Java program?
“class Test
{
public static void main (String args[])
{
System.out.println(10 * 20 + “”Javatpoint””);
System.out.println(“”Javatpoint”” + 10 * 20);
}
}
The output of the above code will be
200Javatpoint
Javatpoint200
Explanation
In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as the string and concatenated with the string Java point to produce the output 200Javatpoint.
In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence of the multiplication is higher than addition. The result 200 will be treated as the string and concatenated with the string Java point to produce the output as Javatpoint200.”
What is the output of the following Java program?
“class Test
{
public static void main (String args[])
{
for(int i=0; 0; i++)
{
System.out.println(“”Hello Javatpoint””);
}
}
}
The above code will give the compile-time error because the for loop demands a boolean value in the second part and we are providing an integer value, i.e., 0.”
Advance Java Interview Questions
What is object-oriented paradigm?
“It is a programming paradigm based on objects having data and methods defined in the class to which it belongs. Object-oriented paradigm aims to incorporate the advantages of modularity and reusability. Objects are the instances of classes which interacts with one another to design applications and programs. There are the following features of the object-oriented paradigm.
Follows the bottom-up approach in program design.
Focus on data with methods to operate upon the object’s data
Includes the concept like Encapsulation and abstraction which hides the complexities from the user and show only functionality.
Implements the real-time approach like inheritance, abstraction, etc.
The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.”
What is an object?
The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword.
What is the constructor?
The constructor can be defined as the special type of method that is used to initialize the state of an object. It is invoked when the class is instantiated, and the memory is allocated for the object. Every time, an object is created using the new keyword, the default constructor of the class is called. The name of the constructor must be similar to the class name. The constructor must not have an explicit return type.
Java Interview Questions
How many types of constructors are used in Java?
“Based on the parameters passed in the constructors, there are two types of constructors in Java.
Default Constructor: default constructor is the one which does not accept any value. The default constructor is mainly used to initialize the instance variable with the default values. It can also be used for performing some useful task on object creation. A default constructor is invoked implicitly by the compiler if there is no constructor defined in the class.
Parameterized Constructor: The parameterized constructor is the one which can initialize the instance variables with the given values. In other words, we can say that the constructors which can accept the arguments are called parameterized constructors.”
What is the purpose of a default constructor?
“The purpose of the default constructor is to assign the default value to the objects. The java compiler creates a default constructor implicitly if there is no constructor in the class.
class Student3{
int id;
String name;
void display(){System.out.println(id+”” “”+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Test it Now
Output:
0 null
0 null
Explanation: In the above class, you are not creating any constructor, so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.
Does constructor return any value?
yes, The constructor implicitly returns the current instance of the class (You can’t use an explicit return type with the constructor).
Advance Java Interview Questions
Is constructor inherited?
No, The constructor is not inherited.
Can you make a constructor final?
No, the constructor can’t be final.
Can we overload the constructors?
“Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters. Consider the following example.
class Test
{
int i;
public Test(int k)
{
i=k;
}
public Test(int k, int m)
{
System.out.println(“”Hi I am assigning the value max(k, m) to i””);
if(k>m)
{
i=k;
}
else
{
i=m;
}
}
}
public class Main
{
public static void main (String args[])
{
Test test1 = new Test(10);
Test test2 = new Test(12, 15);
System.out.println(test1.i);
System.out.println(test2.i);
}
} “
Java Interview Questions
What do you understand by copy constructor in Java?
“There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.
//Java program to initialize the values from one object to another
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+”” “”+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,""Karan"");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
What is the output of the following Java program?
“public class Test
{
Test(int a, int b)
{
System.out.println(“”a = “”+a+”” b = “”+b);
}
Test(int a, float b)
{
System.out.println(“”a = “”+a+”” b = “”+b);
}
public static void main (String args[])
{
byte a = 10;
byte b = 15;
Test test = new Test(a,b);
}
}
The output of the following program is:
a = 10 b = 15″
What is the output of the following Java program?
“class Test
{
int i;
}
public class Main
{
public static void main (String args[])
{
Test test = new Test();
System.out.println(test.i);
}
}
The output of the program is 0 because the variable i is initialized to 0 internally. As we know that a default constructor is invoked implicitly if there is no constructor in the class, the variable i is initialized to 0 since there is no constructor in the class.”
Advance Java Interview Questions
What is the output of the following Java program?
“class Test
{
int test_a, test_b;
Test(int a, int b)
{
test_a = a;
test_b = b;
}
public static void main (String args[])
{
Test test = new Test();
System.out.println(test.test_a+”” “”+test.test_b);
}
}
There is a compiler error in the program because there is a call to the default constructor in the main method which is not present in the class. However, there is only one parameterized constructor in the class Test. Therefore, no default constructor is invoked by the constructor implicitly.”
What is the static variable?
“The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.
//Program of static variable
class Student8{
int rollno;
String name;
static String college =””ITS””;
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+”” “”+name+”” “”+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,””Karan””);
Student8 s2 = new Student8(222,””Aryan””);
s1.display();
s2.display();
}
}
What is the static method?
“A static method belongs to the class rather than the object.
There is no need to create the object to call the static methods.
A static method can access and change the value of the static variable.”
Java Interview Questions
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.”
Why is the main method static?
Because the object is not required to call the static method. If we make the main method non-static, JVM will have to create its object first and then call main() method which will lead to the extra memory allocation.
What is the static block?
“Static block is used to initialize the static data member. It is executed before the main method, at the time of class loading.
class A2{
static{System.out.println(“”static block is invoked””);}
public static void main(String args[]){
System.out.println(“”Hello main””);
}
}
Test it Now
Output: static block is invoked
Hello main”
Advance Java Interview Questions
Can we execute a program without main() method?
No, It was possible before JDK 1.7 using the static block. Since JDK 1.7, it is not possible.
Can we make constructors static?
As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error.
Can we make the abstract methods static in Java?
In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is unnecessary. Calling an undefined method is completely useless therefore it is not allowed.
Java Interview Questions
Can we declare the static variables and methods in an abstract class?
“Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to make the object to access the static context, therefore, we can access the static context declared inside the abstract class by using the name of the abstract class. Consider the following example.
abstract class Test
{
static int i = 102;
static void TestMethod()
{
System.out.println(“”hi !! I am good !!””);
}
}
public class TestClass extends Test
{
public static void main (String args[])
{
Test.TestMethod();
System.out.println(“”i = “”+Test.i);
}
}
Output
hi !! I am good !!
i = 102″
What are the main uses of this keyword?
“There are the following uses of this keyword.
this can be used to refer to the current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke the current class constructor.
this can be passed as an argument in the method call.
this can be passed as an argument in the constructor call.
this can be used to return the current class instance from the method.”
Can we assign the reference to this variable?
“No, this cannot be assigned to any value because it always points to the current class object and this is the final reference in Java. However, if we try to do so, the compiler error will be shown. Consider the following example.
public class Test
{
public Test()
{
this = null;
System.out.println(“”Test class constructor called””);
}
public static void main (String args[])
{
Test t = new Test();
}
}
Output
Test.java:5: error: cannot assign a value to final variable this
this = null;
^
1 error”
Advance Java Interview Questions
Can this keyword be used to refer static members?
“Yes, It is possible to use this keyword to refer static members because this is just a reference variable which refers to the current class object. However, as we know that, it is unnecessary to access static variables through objects, therefore, it is not the best practice to use this to refer static members. Consider the following example.
public class Test
{
static int i = 10;
public Test ()
{
System.out.println(this.i);
}
public static void main (String args[])
{
Test t = new Test();
}
}
Output
10″
How can constructor chaining be done using this keyword?
“Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how can we use this keyword to achieve constructor chaining.
public class Employee
{
int id,age;
String name, address;
public Employee (int age)
{
this.age = age;
}
public Employee(int id, int age)
{
this(age);
this.id = id;
}
public Employee(int id, int age, String name, String address)
{
this(id, age);
this.name = name;
this.address = address;
}
public static void main (String args[])
{
Employee emp = new Employee(105, 22, “”Vikas””, “”Delhi””);
System.out.println(“”ID: “”+emp.id+”” Name:””+emp.name+”” age:””+emp.age+”” address: “”+emp.address);
}
} “
What is the Inheritance?
“Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
There are five types of inheritance in Java.
Single-level inheritance
Multi-level inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance”
Java Interview Questions
Why is Inheritance used in Java?
“There are various advantages of using inheritance in Java that is given below.
Inheritance provides code reusability. The derived class does not need to redefine the method of base class unless it needs to provide the specific implementation of the method.
Runtime polymorphism cannot be achieved without using inheritance.
We can simulate the inheritance of classes with the real-time objects which makes OOPs more realistic.
Inheritance provides data hiding. The base class can hide some data from the derived class by making it private.
Method overriding cannot be achieved without inheritance. By method overriding, we can give a specific implementation of some basic method contained by the base class.”
Why is multiple inheritance not supported in java?
“To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.
Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have the same method or different, there will be a compile time error.
class A{
void msg(){System.out.println(“”Hello””);}
}
class B{
void msg(){System.out.println(“”Welcome””);}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
} “
What is aggregation?
“Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the class it owns. Aggregation is best described as a has-a relationship. For example, The aggregate class Employee having various fields such as age, name, and salary also contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class. Consider the following example.
Address.java
public class Address {
String city,state,country;
public Address(String city, String state, String country) {
this.city = city;
this.state = state;
this.country = country;
}
}
Employee.java
public class Emp {
int id;
String name;
Address address;
public Emp(int id, String name,Address address) {
this.id = id;
this.name = name;
this.address=address;
}
void display(){
System.out.println(id+”” “”+name);
System.out.println(address.city+”” “”+address.state+”” “”+address.country);
}
public static void main(String[] args) {
Address address1=new Address(“”gzb””,””UP””,””india””);
Address address2=new Address(“”gno””,””UP””,””india””);
Emp e=new Emp(111,””varun””,address1);
Emp e2=new Emp(112,””arun””,address2);
e.display();
e2.display();
}
}
Output
111 varun
gzb UP india
112 arun
gno UP india “
Advance Java Interview Questions
What is composition?
Holding the reference of a class within some other class is known as composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. In other words, we can say that composition is the particular case of aggregation which represents a stronger relationship between two objects. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.
What is the difference between aggregation and composition?
Aggregation represents the weak relationship whereas composition represents the strong relationship. For example, the bike has an indicator (aggregation), but the bike has an engine (composition).
What do you mean by data encapsulation?
Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviors 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.
Java Interview Questions
Tell us something about JIT compiler.
- JIT stands for Just-In-Time and it is used for improving the performance during run time. It does the task of compiling parts of byte code having similar functionality at the same time thereby reducing the amount of compilation time for the code to run.
- The compiler is nothing but a translator of source code to machine-executable code. But what is special about the JIT compiler? Let us see how it works:
- First, the Java source code (.java) conversion to byte code (.class) occurs with the help of the javac compiler.
- Then, the .class files are loaded at run time by JVM and with the help of an interpreter, these are converted to machine understandable code.
- JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the method calls in the .class files and compiles them to get more efficient and native code. It also ensures that the prioritized method calls are optimized.
- Once the above step is done, the JVM executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.
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);
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:
public class MultipleCatch {
public static void main(String args[]) {
try {
int n = 1000, x = 0;
int arr[] = new int[n];
for (int i = 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.
Advance Java Interview Questions
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.
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:
final int a=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 {
int variable = 5;
}
catch (Exception exception) {
System.out.println("Exception occurred");
}
finally {
System.out.println("Execution of finally block");
}
Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented. Example:
public static void main(String[] args) {
String example = new String("InterviewBit");
example = null;
System.gc(); // Garbage collector called
}
public void finalize() {
// Finalize called
}
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.
Java Interview Questions
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.
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.
What part of memory – Stack or Heap – is cleaned in garbage collection process?
Heap.
Advance Java Interview Questions
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 Hash tables and Hash Maps, keys are String objects. If the String objects are not immutable, then it can get modified during the period when it resides in the Hash Maps. 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.
How would you differentiate between a String, String Buffer, and a String Builder?
- Storage area: In string, the String pool serves as the storage area. For String Builder and String Buffer, heap memory is the storage area.
- Mutability: A String is immutable, whereas both the String Builder and String Buffer are mutable.
- Efficiency: It is quite slow to work with a String. However, String Builder is the fastest in performing operations. The speed of a String Buffer is more than a String and less than a String Builder. (For example appending a character is fastest in String Builder and very slow in String because a new memory is required for the new String with appended character.)
- Thread-safe: In the case of a threaded environment, String Builder and String Buffer are used whereas a String is not used. However, String Builder is suitable for an environment with a single thread, and a String Buffer is suitable for multiple threads.
Syntax:
// String
String first = "InterviewBit";
String second = new String("InterviewBit");
// StringBuffer
StringBuffer third = new StringBuffer("InterviewBit");
// StringBuilder
StringBuilder fourth = new StringBuilder("InterviewBit");
Using relevant properties highlight the differences between interfaces and abstract classes.
- Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
- Variable types: Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
- Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
- Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
- Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;
Abstract class example:
public abstract class Athlete {
public abstract void walk();
}
Interface example:
public interface Walkable {
void walk();
}
Java Interview Questions
In Java, static as well as private method overriding is possible. Comment on the statement.
The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.
The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.
What makes a Hash Set different from a Tree Set?
Although both Hash Set and Tree Set are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a Hash Set from a Tree Set.
- Implementation: For a Hash Set, the hash table is utilized for storing the elements in an unordered manner. However, Tree Set makes use of the red-black tree to store the elements in a sorted manner.
- Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a Hash Set. The time complexity for performing the same operations is a bit higher for Tree Set and is equal to O(log n). Overall, the performance of Hash Set is faster in comparison to Tree Set.
- Methods: hash Code() and equals() are the methods utilized by Hash Set for making comparisons between the objects. Conversely, compare To() and compare() methods are utilized by Tree Set to facilitate object comparisons.
- Objects type: Heterogeneous and null objects can be stored with the help of Hash Set. In the case of a Tree Set, runtime exception occurs while inserting heterogeneous objects or null objects.
Why is the character array preferred over string for storing confidential information?
In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.
As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.
Advance Java Interview Questions
What are the differences between Hash Map and Hash Table in Java?
HashMap | HashTable |
---|---|
Hash Map is not synchronized thereby making it better for non-threaded applications. | HashTable is synchronized and hence it is suitable for threaded applications. |
Allows only one null key but any number of null in the values. | This does not allow null in both keys or values. |
Supports order of insertion by making use of its subclass LinkedHashMap. | Order of insertion is not guaranteed in HashTable. |
What is the importance of reflection in Java?
- The term
reflection
is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime. - Consider an example where we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. The static typing system of Java doesn’t allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to scan the object and identify if it has any method called “foo Bar()” and only then call the method if needed.
Method methodOfFoo = fooObject.getClass().getMethod("fooBar", null);
methodOfFoo.invoke(fooObject, null);
- Using reflection has its own cons:
- Speed — Method invocations due to reflection are about three times slower than the direct method calls.
- Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
- Traceability — Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. One has to deep dive into the invoke() and proxy() method logs to identify the root cause.
- Hence, it is advisable to follow solutions that don’t involve reflection and use this method as a last resort.
What are the different ways of threads usage?
- We can define and implement a thread in java using two ways:
- Extending the Thread class
class InterviewBitThreadExample extends Thread{
public void run(){
System.out.println("Thread runs...");
}
public static void main(String args[]){
InterviewBitThreadExample ib = new InterviewBitThreadExample();
ib.start();
}
}
- Implementing the Runnable interface
class InterviewBitThreadExample implements Runnable{
public void run(){
System.out.println("Thread runs...");
}
public static void main(String args[]){
Thread ib = new Thread(new InterviewBitThreadExample());
ib.start();
}
}
- Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
start()
method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls therun()
method for executing the thread in that call stack.
Java Interview Questions
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:
class InterviewBitTest{
int num;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
class Driver {
public static void main(String[] args)
{
//create a reference
InterviewBitTest ibTestObj = new InterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in the object.
System.out.println(ibTestObj.num);
}
public static void updateObject(InterviewBitTest ibObj)
{
// Point the object to new reference
ibObj = new InterviewBitTest();
// Update the value
ibObj.num = 50;
}
}
Output:
20
- Case 2: When object references are not modified: In this case, since we have the copy of reference the main object pointing to the same memory location, any changes in the content of the object get reflected in the original object.
For example:
class InterviewBitTest{
int num;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
class Driver{
public static void main(String[] args)
{
//create a reference
InterviewBitTest ibTestObj = new InterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in the object.
System.out.println(ibTestObj.num);
}
public static void updateObject(InterviewBitTest ibObj)
{
// no changes are made to point the ibObj to new location
// Update the value of num
ibObj.num = 50;
}
}
Output:
50
Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?
String Buffer is mutable and dynamic in nature whereas String is immutable. Every update / 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 String Buffer as it will reduce the overhead of the creation of multiple String objects in the string pool.
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:
public class InterviewBitExample {
private transient String someInfo;
private String name;
private int id;
// :
// Getters setters
// :
}
- In the above example, all the fields except
someInfo
can be serialized.
Advance Java Interview Questions
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 “No Such Method Error” error at the runtime.
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.
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.
Java Interview Questions
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.
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:
package comparison;
public class Top {
public int start() {
return 0;
}
}
class Bottom extends Top {
public int stop() {
return 0;
}
}
In the above example, inheritance is followed. Now, some modifications are done to the Top class like this:
public class Top {
public int start() {
return 0;
}
public void stop() {
}
}
If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top. Stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem:
class Bottom {
Top par = new Top();
public int stop() {
par.start();
par.stop();
return 0;
}
}
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 = new LinkedList<String>();
while(true){
example.add(new String("Memory Limit Exceeded"));
}
Advance Java Interview Questions
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:
package anonymous;
public class Counting {
private int increase_counter;
public int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
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.
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 isO(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.
Java Interview Questions
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.
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.
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.
Advance Java Interview Questions
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.
Explain the term “Double Brace Initialization” in Java?
This is a convenient means of initializing any collections in Java. Consider the below example.
import java.util.HashSet;
import java.util.Set;
public class IBDoubleBraceDemo{
public static void main(String[] args){
Set<String> stringSets = new HashSet<String>()
{
{
add("set1");
add("set2");
add("set3");
}
};
doSomething(stringSets);
}
private static void doSomething(Set<String> stringSets){
System.out.println(stringSets);
}
}
In the above example, we see that the string Sets 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 Hash Set so that it can use the add() method of Hash Set.
- 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.
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.
Java Interview Questions
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.
public class IBGarbageCollect {
public static void main (String [] args){
String s1 = "Some String";
// s1 referencing String object - not yet eligible for GC
s1 = null; // now s1 is eligible for GC
}
}
Second Approach: Point the reference variable to another object. Doing this, the object which the reference variable was referencing before becomes eligible for GC.
public class IBGarbageCollect {
public static void main(String [] args){
String s1 = "To Garbage Collect";
String s2 = "Another Object";
System.out.println(s1); // s1 is not yet eligible for GC
s1 = 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.
public class IBGarbageCollect {
IBGarbageCollect ib;
public static void main(String [] str){
IBGarbageCollect ibgc1 = new IBGarbageCollect();
IBGarbageCollect ibgc2 = new IBGarbageCollect();
ibgc1.ib = ibgc2; //ibgc1 points to ibgc2
ibgc2.ib = ibgc1; //ibgc2 points to ibgc1
ibgc1 = 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
*/
}
}
Write a Java program to check if the two strings are anagrams.
The main idea is to validate the length of strings and then if found equal, convert the string to char array and then sort the arrays and check if both are equal.
import java.util.Arrays;
import java.util.Scanner;
public class InterviewBit {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//Input from two strings
System.out.print("First String: ");
String string1 = s.nextLine();
System.out.print("Second String: ");
String string2 = s.nextLine();
// check for the length
if(string1.length() == string2.length()) {
// convert strings to char array
char[] characterArray1 = string1.toCharArray();
char[] characterArray2 = string2.toCharArray();
// sort the arrays
Arrays.sort(characterArray1);
Arrays.sort(characterArray2);
// check for equality, if found equal then anagram, else not an anagram
boolean isAnagram = Arrays.equals(characterArray1, characterArray2);
System.out.println("Anagram: "+ isAnagram);
}
}
Write a Java Program to find the factorial of a given number.
public class FindFactorial {
public static void main(String[] args) {
int num = 10;
long factorialResult = 1l;
for(int i = 1; i <= num; ++i)
{
factorialResult *= i;
}
System.out.println("Factorial: "+factorialResult);
}
}
Advance Java Interview Questions
Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.
Idea is to find the sum of n natural numbers using the formula and then finding the sum of numbers in the given array. Subtracting these two sums results in the number that is the actual missing number. This results in O(n) time complexity and O(1) space complexity.
public class IBMissingNumberProblem {
public static void main(String[] args) {
int[] array={4,3,8,7,5,2,6};
int missingNumber = findMissingNum(array);
System.out.println("Missing Number is "+ missingNumber);
}
public static int findMissingNum(int[] array) {
int n=array.length+1;
int sumOfFirstNNums=n*(n+1)/2;
int actualSumOfArr=0;
for (int i = 0; i < array.length; i++) {
actualSumOfArr+=array[i];
}
return sumOfFirstNNums-actualSumOfArr;
}
}
Why Java is platform independent?
Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying operating system.
What are wrapper classes in Java?
Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the below image which displays different primitive type, wrapper class and constructor argument.
Java Interview Questions
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 execution. | Heap memory is used by all the parts of the application. |
Access | Stack memory can’t be accessed by other threads. | Objects stored in the heap are globally accessible. |
Memory Management | Follows LIFO manner to free memory. | Memory management is based on the generation associated with each object. |
Lifetime | Exists until the end of execution of the thread. | Heap memory lives from the start till the end of application execution. |
Usage | Stack memory only contains local primitive and reference variables to objects in heap space. | Whenever an object is created, it’s always stored in the Heap space. |
Define a Java Class.
A class in Java is a blueprint which includes all your data. A class contains fields (variables) and methods to describe the behavior of an object. Let’s have a look at the syntax of a class.
class Abc {
member variables // class body
methods}
What is a Map in Java?
In Java, Map is an interface of Until package which maps unique keys to values. The Map interface is not a subset of the main Collection interface and thus it behaves little different from the other collection types. Below are a few of the characteristics of Map interface:
- Map doesn’t contain duplicate keys.
- Each key can map at max one value.
Advance Java Interview Questions
What is Polymorphism?

Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more than one form. There are two types of polymorphism:
- Compile time polymorphism
- Run time polymorphism
Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.
What is runtime polymorphism or dynamic method dispatch?
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. Let’s take a look at the example below to understand it better.
class Car {
void run()
{
System.out.println(“car is running”);
}
}
class Audi extends Car {
void run()
{
System.out.prinltn(“Audi is running safely with 100km”);
}
public static void main(String args[])
{
Car b= new Audi(); //upcasting
b.run();
}
}
What are the different types of inheritance in Java?
Java supports four types of inheritance which are:
- Single Inheritance: In single inheritance, one class inherits the properties of another i.e there will be only one parent as well as one child class.
- Multilevel Inheritance: When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance.
- Hierarchical Inheritance: When a class has more than one child classes (subclasses) or in other words, more than one child classes have the same parent class, then such kind of inheritance is known as hierarchical.
- Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance
Java Interview Questions
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.