In this article, we have covered almost 30+ most asked core Java interview questions for freshers and experienced candidates. This exhaustive collection of Java interview questions were asked by various recruiters during the technical interview rounds.
These Java interview questions will help you understand the basic concepts of Java required to crack a technical interview. So bookmark this page to quickly brush up your knowledge before the interview.
So here you go!
Here are some important differences to note between C++ & Java.
@@table::1@@
For a programming language to be purely object-oriented, it has to satisfy the following qualities:
But, Java fails to satisfy two of the above qualities (5 & 7).
Hence, Java is not a purely object-oriented programming language.
Before getting into the answer, let us see what is the use of declaring a method as static? Generally in Java, a method is invoked using an object created for the class (in which the same method is written). But when a method is declared as static, it can be invoked without the use of the object, i.e., directly using the class.
We all know that the execution of a Java program starts from a main() method. Since the main() method has to be invoked before invoking any other method, it is always declared as static in Java.
Yes, we can have multiple methods with the same name as main inside a single class. However, JVM will consider the method with the syntax public static void main(String args)
as the main()
method.
Both string builder and string buffer are two different classes used to create mutable strings in Java. However, they too have some differences.
@@table::2@@
JVM (Java Virtual Machine) is the heart of Java. It is used to convert byte code into machine-readable code. JVM is not platform-independent, that’s why we have different JVMs for different operating systems.
In Java, the IS-A relationship is based on either class inheritance or interface inheritance. A sub-class is said to have an IS-A relationship with its super-class. You can easily identify the IS-A relationship whenever you come across extends
keyword in the Java program.
Example: Consider a sub-class ‘Deer’ and super-class ‘Animal’. These two classes are said to have IS-A relationship, i.e., Deer IS-A Animal.
The composition in Java is a technique used to implement HAS-A relationship in classes. This is mainly used for code reuse. This relationship is achieved by using instance variables that are references to other objects.
Example: Consider a class ‘Horns’. If the class ‘Animal’ uses the method of the class ‘Horns’, then both the classes ‘Animal’ and ‘Horns’ are said to have HAS-A relationship, ie., Deer HAS-A Horns.
In Java, wrapper classes are used to convert primitive data types into wrapper class objects. Since Java is an object-oriented programming language, collections such as ArrayList, List, etc does not support primitive data types. In such cases, wrapper classes come in handy.
@@table::3@@
Both .equals() and == are used to compare objects to equality, but with some differences such as.
@@table::4@@
For example,
//program to compare two strings in Javanclass Main {n public static void main (String args[]) {n String s1 = new String("FACEPrep");n String s2 = new String("FACEPrep");n System.out.println("Result after comparing address: " + (s1 == s2));n System.out.println("Result after comparing values: " + s1.equals(s2));n }n}nnnOutput:nResult after comparing address: falsenResult after comparing values: truen
Note: Here, s1 and s2 are two different objects which are stored in two different memory locations.
Multiple Inheritance is a feature of Java, where one class can inherit the properties of more than one parent class.
Problem occurs when there exist methods with the same signature in both the super-class and sub-class. On calling the method, the compiler will not understand which class method to be called and even on calling it cannot decide the priority.
Here is an example to help you understand better
// First Parent class nclass Parent1 { n void meth() { n System.out.println("Parent1"); n } n} n// Second Parent Class nclass Parent2 { n void meth() { n System.out.println("Parent2"); n } n} n// child class which inherits both parent classesnclass Child extends Parent1, Parent2 { n public static void main(String args[]) { n Child c = new Child(); n c.meth(); n } n}nnnOutput:nprog.java:14: error: '{' expectednclass Child extends Parent1, Parent2 { n ^n
You can create an object without the use of new keyword using the below techniques.
We can use newInstance()
method to create an object for a class without the use of new
keyword as shown below.
class Flower {n void print() {n System.out.println("Flowers are beautiful");n }n}nclass Main {n public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException {n Class cls = Class.forName("Flower");n Flower f = (Flower) cls.newInstance();n f.print();n }n}n
Class.forName
just loads the class in Java. It doesn’t create any object. To create an object, you have to use the newInstance()method of the class named ‘Class’.
Both keywords are used to call methods or constructors. The super
keyword is used to call the immediate parent class method or constructor. Whereas this
keyword is used to call the current class constructor or method.
Here is how these keywords function.
class Flower {n int a = 30;n}nclass Rose extends Flower {n int a = 40;n void print() {n System.out.println("Super class value: " + super.a);n System.out.println("Child class value: " + this.a);n }n}nclass Main {n public static void main(String args[]) {n Rose r = new Rose();n r.print();n }n}nnnOutput:nSuper class value: 30nChild class value: 40n
It is a keyword used to apply restrictions on methods, variables, classes. Also, a class that is declared as final cannot be inherited, a variable that is declared as final cannot be changed and a method which is declared as final cannot be overridden.
It is a block related to exception handling. The statements written inside this block will be executed irrespective of whether an exception has been handled or not. The important code like closing connection can be written inside this block in Java.
Yes, Java constructors can be overloaded by changing the number or type of arguments. Constructor overloading is useful for initializing an object in different ways.
In Java, final
keyword can be applied to a variable, class or a method. It provides restrictions on the usage of the data. Let’s understand this through some examples.
If a variable is declared as final, then the value of that variable cannot be changed.
class Main { n final int a = 30; // final variable n void print() { n a = 20;n System.out.println(a);n } n public static void main(String args[]) { n Main m = new Main(); n m.print(); n } n}nnnOutput:nnprog.java:4: error: cannot assign a value to final variable an a = 20;n ^n
If you declare a method as final, then you cannot override it.
class Flower { n final void print() {n System.out.println("Flowers are beautiful");n } n} nclass Rose extends Flower { n void print() {n System.out.println("Rose is a beautiful flower");n } n public static void main(String args[]) { n Rose r = new Rose(); n r.print(); n } n}nnnOutputnprog.java:7: error: print() in Rose cannot override print() in Flowern void print() {n ^n overridden method is finaln
If you declare a class as final, then you cannot extend it. For instance,
final class Flower { n void print() {n System.out.println("Flowers are beautiful");n } n} nclass Rose extends Flower { n void print() {n System.out.println("Rose is a beautiful flower");n } n public static void main(String args[]) { n Rose r = new Rose(); n r.print(); n } n}nnnOutputnprog.java:6: error: cannot inherit from final Flowernclass Rose extends Flower { n ^n
In Java, both this ()
and super ()
are used to make constructor calls. this() is used to invoke the current class’s constructor and super() is used to invoke the parent class’s constructor. If we need to call the parent class’s constructor, then super() should be the first line of the method and if we need to call the current class’s constructor, then this() should be the first line of the method. Hence, both this() and super() cannot be used in the same method.
Garbage collection is the process of deleting unused memory created during the run time. The same is done using free() function in C and delete() function in C++. But in Java, a garbage collector (a part of JVM) automatically does this process.
It is a feature that allows a class to have more than one method with the same name, if their argument lists are different. It is an example of compile-time polymorphism. For instance, consider this example
class Main {n void print(int a, int b) { n System.out.println (a + b);n }n void print(int c, int d, int e) { n System.out.println (c + d + e);n }n public static void main(String args[]) {n Main m = new Main();n m.print(10, 20);n m.print(30, 40, 50);n }n}nnnOutputn30n120n
It is a feature where a method in the child class has the same name as that of the method in the parent class. Also, both methods should have the same number of arguments. It is an example of run time polymorphism. For example,
class Add {n void print(int a, int b) { n System.out.println(a + b);n }n}nclass Main extends Add {n void print(int c, int d) { n System.out.println(c * d);n }n public static void main(String args[]) {n Main m = new Main();n Add a = new Add();n m.print(10, 20);n a.print(10, 20);n }n}nnnOutputn200n30n
java.lang.object is the super-class for all the classes. We need not extend this class in our Java program.
No. Only one class can be public in a single Java file. The name of the class (declared as public) should be the same as that of the filename.
A package in Java is used to encapsulate a group of classes, sub-packages, and interfaces. Packages are used to prevent naming conflicts and for encapsulation. A package in Java contains a group of similar type of classes, interfaces, sub-packages. There are two types of packages in Java. They are built-in and user-defined packages. Some of the built-in packages are lang, io, util, etc.
Example: import java.util.Scanner; where ‘util’ is the package name and ‘Scanner’ is the class name.
In Java, java.lang package is imported by default and we don’t need to import any class from this package explicitly.
In Java, an interface is a blueprint of a class. It has static constants and abstract methods. It is a mechanism used to achieve abstraction and multiple inheritance in Java.
In other words, interfaces can have abstract methods and variables, but it cannot have a method body. Also, all the methods in an interface are implicitly public and abstract.
Any non-static nested class is called an inner class in Java. An inner class can access the variables and methods of the outer class.
For instance:
class Outer { n a = 30;n // nested inner class n class Inner { n public void print() { n System.out.println("FACEPrep"); n System.out.println(a);n }n } n} nnclass Main { n public static void main(String[] args) { n Outer.Inner in = new Outer().new Inner(); n in.print(); n } n}nnnOutputnFACEPrepn30n
Yes, we can have a try block without a catch block. But in such a case, the exception occurred in the program will not be handled. To handle an exception in the program, a catch block is mandatory. Also, a single try block can have one or more catch blocks.
This keyword is also called a type comparison operator.It is used to check if a particular object belongs to a particular class or not. For instance,
class Main { n public static void main(String args[]) { n Main m = new Main(); n System.out.println(m instanceof Main);n } n}nnnOutputntruen
A singleton class in Java is a class that has only one object at a time. This class is used when there is a limitation on the number of objects of a class.To create a singleton class,
Random numbers in Java can be generated in two ways.
import java.util.Random; npublic class GenerateRandom { n public static void main(String args[]) { n // creating object for the class Randomn Random rand = new Random(); n // Generate random integers in range from 0 to 9n int rand_int = rand.nextInt(10); n System.out.println("Random Integer: " + rand_int); n } n}n
This method is used to create numbers of double data type randomly.
import java.util.Random; npublic class generateRandom { n public static void main(String args[]) { n System.out.println("Random Integer: " + Math.random()); n } n}n
No. In Java, when we import a package, its sub-packages will not get imported automatically. We need to do it explicitly whenever required.
No, In java, the main() method should be public to run any application correctly. If the main() method is declared private, the program will not execute and results in runtime error.
The constructor of a class is invoked whenever an object is created for that class using the new
keyword.
public class Main {n Main() {n System.out.println("Inside constructor");n }n public static void main(String args[]) {n Main m1 = new Main();n Main m2 = new Main();n }n}nnnOutputnInside constructornIns