Browse Tutorials
Top 50 Java Interview Questions and Answers

Top 50 Java Interview Questions and Answers

05 Feb 2024
720 Views
43 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Java Interview Questions and Answers: An Overview

Java is a high-level versatile programming language. It has a wide range of applications. Almost all the big companies like Amazon and Google hire Java Developers. Though you have learned Java or you are a Certified Java Developer you need to be aware of Java Technical Interview Questions to crack the technical round of interview. Therefore the following article provides you with a comprehensive guide on Java Interview Questions and Answers to help you prepare for interviews.

Basic Java Interview Questions for Freshers

  1. Differentiate between Java and C++

The following differences are there:
  • C++ is only a compiled language, whereas Java is a compiled and interpreted language.
  • Java programs are machine-independent whereas a C++ program can run only on the machine on which it is compiled.
  • C++ allows users to use pointers in the program. Whereas it's not the case with Java. Java internally uses pointers.
  • C++ supports the concept of multiple inheritances while Java doesn't support this. It can be achieved by using interfaces in Java.

  1. Is Java a complete object-oriented programming language?

  • Everything in Java is under the classes. And we can access that by creating the objects. This makes it an object-oriented language.
  • But it has the support of primitive data types like int, float, char, boolean, double, etc. This is not a feature of object-oriented languages.
  • Therefore, Java is not a pure object-oriented programming language because the primitive data types it supports don't directly belong to the Integer classes.

  1. What is JVM?

JVM

JVM
stands for Java Virtual Machine. It is a Java interpreter. It is responsible for loading, verifying, and executing the bytecode created in Java. Its implementation is known as JRE. Although it is platform dependent which means the software of JVM is different for different Operating Systems it plays a vital role in making Java platform Independent.

  1. What do you mean by JIT?

Just-in-Time (JIT)

JIT stands for Just-in-Time compiler and is a part of JRE(Java Runtime Environment). It is used for better performance of the Java applications during run-time. The step-by-step working process of JIT is mentioned below:

  • Source code is compiled with Javac compiler to form bytecode
  • Bytecode is further passed on to JVM. 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 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 machine code at run time. It also ensures that the prioritized method calls are optimized.
  • The JVM then executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.

  1. What gives Java its 'write once and run anywhere' nature?

It is the bytecode. Java compiler converts the Java programs into the .class file known as the 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 machine.

  1. What is a ClassLoader?

Java Classloader is the program of JRE (Java Runtime Environment). The task of ClassLoader is to dynamically load the required Java classes and interfaces to the JVM during the execution of the bytecode or created .class file. Because of classloaders Java run time system does not need to know about files and file systems.

  1. Explain public static void main(String args[]) in Java.

  • public: the public is the access modifier responsible for mentioning who can access the element or the method and what is the limit. It is responsible for making the main function globally available. It is made public so that JVM can invoke it from outside the class as it is not present in the current class.
  • static: It is a keyword with which you can use the element without initiating the class to avoid the unnecessary allocation of the memory.
  • void: void is a keyword used to specify that a method doesn’t return anything. We use void with the main function because it doesn’t return anything.
  • main: main helps JVM to identify that the declared function is the main function.
  • String args[]: It stores Java command-line arguments and is an array of type java.lang.String class.

  1. Can the main method be overloaded?

Yes, the main method can be overloaded. We can create as many overloaded main methods as we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of
public static void main(string[] args)

Example


class Main {
 public static void main(String[] args) {
 System.out.println("This is the main method");
 }

 public static void main(int[] args) {
 System.out.println("Overloaded integer array main method");
 }

 public static void main(char[] args) {
 System.out.println("Overloaded character array main method");
 }

 public static void main(double[] args) {
 System.out.println("Overloaded double array main method");
 }

 public static void main(float args) {
 System.out.println("Overloaded float main method");
 }
}

Output

This is the main method

  1. What are the different data types in Java?

The data types in Java are categorized into two categories as mentioned below:
  1. Primitive Data Type
  2. Non-primitive data Type or Object Data type
  1. Primitive Data Type: Primitive data are single values with no special capabilities. There are 8 primitive data types in Java:
    1. boolean: stores value true or false
    2. byte: stores an 8-bit signed two’s complement integer
    3. char: stores a single 16-bit Unicode character
    4. short: stores a 16-bit signed two’s complement integer
    5. int: stores a 32-bit signed two’s complement integer
    6. long: stores a 64-bit two’s complement integer
    7. float: stores a single-precision 32-bit IEEE 754 floating-point
    8. double: stores a double-precision 64-bit IEEE 754 floating-point
  2. Non-Primitive Data Type: They are reference data types that contain a memory address of the variable’s values because it is not able to directly store the values in the memory. Types of Non-Primitive data types are:
    1. String
    2. Array
    3. Class
    4. Object
    5. Interface

  1. How many types of operators are there in Java?

There are multiple types of operators in Java. They are as follows:

  1. Arithmetic operators
  2. Relational operators
  3. Logical operators
  4. Assignment operators
  5. Unary operators
  6. Bitwise operators
  7. Ternary operator

  1. Differentiate between equals() method and equality operator == in Java

equals()equality operator (==)
This is a method defined in the Object class.It is a binary operator in Java.
As the .equals() method is present in the Object class, we can override our custom .equals() method in the custom class, for object comparison.It cannot be modified. They always compare the HashCode.
This method is used for checking the equality of contents between two objects as per the specified business logic.This operator is used for comparing addresses (or references), i.e. checks if both the objects are pointing to the same memory location.

  1. What are the main concepts of OOPs in Java?

The four main OOPs concepts in Java are:
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

  1. What is a Class Variable?

In Java, a class variable is also known as a static variable. It is a variable that is declared within a class but outside of any method, constructor, or block. Class variables are declared with the static keyword, and they are shared by all instances (objects) of the class and by the class itself. No matter how many objects are derived from a class, each class variable would only exist once.

class Example {
 public static int ctr = 0;

 public Example() {
 ctr++;
 }

 public static void main(String[] args) {
 Example obj1 = new Example();
 Example obj2 = new Example();
 Example obj3 = new Example();

 System.out.println("Number of objects created are " + Example.ctr);
 }
}

Output

Number of objects created are 3

Read more: Variables in Java

  1. How is an infinite loop declared in Java?

An infinite loop is a sequence of instructions that is executed endlessly without termination. This occurs when the loop condition remains true, or when the programmer forgets to apply a terminating statement within the loop body.

We will see how to make all three loops in Java an infinite one.

  1. for Loop
    for (;;)
    {
     //body of the for loop... 
    }
    
  2. while loop
    while(true) 
    { 
     // body of the loop...
    } 
    
  3. do...while loop
    do 
    { 
     // body of the loop... 
    }while(true);

  1. What if I write static public void instead of public static void?

In Java, the order of specifiers doesn't matter and hence the program compiles and runs correctly.

  1. What are the key differences between Java constructors and Java methods?

Java ConstructorJava Method
A constructor is used to initialize the state of an object.A method is used to expose the behaviour 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 have any constructor in a class.The method is not provided by the compiler in any case.
The constructor name must be the same as the class name.The method name may or may not be the same as the class name.

  1. When a byte datatype is used?

A byte is an 8-bit signed two-complement integer. The minimum value supported by bytes is -128 and 127 is the maximum value. It is used in conditions where we need to save memory and the limit of numbers needed is between -128 to 127.

  1. What is method overloading?

Method overloading is the compile time polymorphism technique that allows us to create multiple methods with the same name but with different signatures. We can achieve method overloading in two ways.
  1. By Changing the number of arguments
  2. By Changing the data type of arguments
Method overloading increases the readability of the program. Method overloading is performed to figure out the program quickly.

  1. What are the various access specifiers in Java?

There are four access specifiers/access modifiers in Java given below:

Access Modifiers
  1. Public: The classes, methods, or variables which are defined as public, can be accessed by any class or method.
  2. Protected: The protected methods and members can be accessed by the class of the same package, by the sub-class of this class, or within the same class.
  3. Default: these methods and classes are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
  4. Private: The private class, methods, or variables can be accessed within the class only.

  1. What is a dot operator in Java?

The dot operator . in Java is used to access the instance variables and methods of class objects. It is also used to access classes and sub-packages from the package.

Example

System.out.println("This is the main method");
import java.io.*; 

Intermediate Java Interview Questions and Answers

  1. In how many ways can you take input from the console?

We can do this in four ways in Java:

  1. Using Command line argument
    
    class ScholarHat {
     public static void main(String[] args) {
     // Check if the length of the args array is greater than 0
     if (args.length > 0) {
     System.out.println("The command line arguments are:");
     // Iterating the args array and printing the command line arguments
     for (String value : args)
     System.out.println(value);
     } else
     System.out.println("No command line arguments found.");
     }
    }
    
    • Compile the code in cmd using the below command
      javac ScholarHat.java
      
    • Run the program with command line arguments
      java ScholarHat WelcometoScholarHat
      

    Output

    The command line arguments are:
    WelcometoScholarHat
    
  2. Using Buffered Reader Class
    
    import java.io.*;
    
    class ScholarHat {
     public static void main(String[] args) throws IOException {
     // Enter data using BufferedReader
     BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    
     System.out.println("Please enter some text:");
    
     // Reading data using readLine
     String input = reader.readLine();
     
     // Printing the read line
     System.out.println("You entered: " + input);
     }
    }
    

    Output

    Please enter some text:
    Hello, ScholarHat
    You entered: Hello, ScholarHat
    
  3. Using Console Class
    
    public class ScholarHat { 
     public static void main(String[] args) 
     { 
     // Using Console to input data from the user 
     String x = System.console().readLine(); 
     System.out.println("You entered string " + x); 
     } 
    }
    

    Output

    You entered string Hello, ScholarHat!
    
  4. Using Scanner Class
    
    import java.util.Scanner;
    
    public class ScholarHat {
     public static void main(String[] args) {
     Scanner in = new Scanner(System.in);
     System.out.print("Enter a string: ");
     String str = in.nextLine();
     System.out.println("You entered string " + str);
     }
    }
    

    Output

    Enter a string:
    Hello, ScholarHat
    You entered string Hello, ScholarHat
    

  1. What do we get in the JDK file?

JDK (Java Development Kit) is a package that contains various tools, Compilers, Java Runtime Environment, etc.

JDK

  1. What is the difference between the throw and throws keywords in Java?

  • The throw keyword in Java is used to manually throw the exception to the calling method.
  • The throws keyword in Java is used in the function definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.

class Main {
 public static int divideByZero(int a, int b) throws ArithmeticException {
 if (a == 0 || b == 0)
 throw new ArithmeticException("Division by zero is not allowed");
 return a / b;
 }

 public static void main(String[] args) {
 try {
 int result = divideByZero(10, 0);
 System.out.println("Result: " + result);
 } catch (ArithmeticException e) {
 System.out.println("Exception caught: " + e.getMessage());
 }
 }
}

In the above Java code, the divideByZero() method checks for division by zero and throws an ArithmeticException if either a or b is zero. In the main method, we catch the exception and print a message indicating that division by zero is not allowed.

Output

Enter a string:
Exception caught: Division by zero is not allowed

  1. What is the Is-A relationship in OOPs in Java?

Inheritance in Java signifies an "is-a" relationship between classes. In the picture below, the Car class can inherit properties and behaviors, like "speed" and "startEngine," from the "Vehicle" class. We can say that "a car is a vehicle".

  1. What do you understand by the term Vector in Java?

A vector is like a dynamic array that can store n number of elements in it as there is no size limit.

Syntax

Vector vector = new Vector<>();
  • Vector can be imported using Java.util.Vector.
  • Elements of the Vector can be accessed using index numbers.
  • Vectors are synchronized in nature means they only use a single thread ( only one process is performed at a particular time ).
  • The vector contains many methods that are not part of the collections framework.

  1. What do you understand by constructor overloading in Java?

Constructor overloading in Java 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 the different types of constructors is done by the compiler.

  1. Is it necessary that each try block must be followed by a catch block?

No, it is not necessary to use catch block after try block in Java as we can create another combination with finally block. Finally is the block which runs even though the exception is thrown or not.

Read more: Exception handling in Java

  1. What is the difference between a program and a process?

  • A program can be defined as lines of code written to accomplish a particular task. Whereas the process can be defined as the programs which are under execution.
  • A program doesn't execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.

  1. Differentiate between an object-oriented programming language and an object-based programming language.

Object-Oriented Programming Language Object-Based Programming Language
It covers concepts like inheritance, polymorphism, abstraction, etc.The scope of object-based programming is limited to the usage of objects and encapsulation.
It supports all the built-in objectsIt doesn’t support all the built-in objects
Examples: Java, C#, etc.Examples: JavaScript, visual basics, etc.

  1. Write a Java program to create and throw custom exceptions.


class ScholarHat {
 public static void main(String[] args) throws CustomException {
 // Throwing the custom exception by passing the message
 throw new CustomException("This is an example of custom exception");
 }
}

// Creating Custom Exception Class
class CustomException extends Exception {
 // Defining Constructor to throw exception message
 public CustomException(String message) {
 super(message);
 }
}

  1. 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.

  1. How is the creation of a string using new() different from that of a literal?

When we declare a string in Java it stores the elements inside the stack memory whereas when it is declared using new() it allocates a dynamic memory in the heap memory. The object gets created in the heap memory even if the same content object is present.

For more information, click on Strings in Java

  1. Is it possible to call a constructor of a class inside another constructor?

Yes, it is possible using the this keyword in Java. The whole process to do this is known as constructor chaining in Java.

  1. Are int array[] and int[] array different or the same?

Both int array[] and int[] array are the same in terms of functionality. They are used to declare an array of integers in Java. The only difference is in their syntax.
int arr[] //C-Style syntax to declare an array.
int[] arr //Java-Style syntax to declare an array.
However, it is generally recommended to use Java-style syntax to declare an array. It is easy to read and understand, also it is more consistent with other Java language constructs.

  1. What are the different ways to create objects in Java?

We can create objects in Java in the following ways:
  1. Using new keyword
  2. Using new instance
  3. Using clone() method
  4. Using deserialization
  5. Using the newInstance() method of the constructor class

To get detailed insights on all these methods refer to Classes and Objects in Java OOPs

Advanced Java Interview Questions and Answers

  1. What are the differences between abstract class and interface?

Abstract Class Interface
Both abstract and non-abstract methods may be found in an abstract class. The interface contains only abstract methods.
abstract class supports final methods. An interface does not support final methods.
Multiple inheritance is not supported by the abstract class. Multiple inheritance is supported by the interface.
abstract keyword is used to declare an abstract class. interface keyword is used to declare an interface.
extend keyword is used to extend an abstract Class.interface keyword is used to implement an interface.
abstract class has members like protected, private, etc. All class members are public by default.

  1. Explain 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.
Therefore, we can say that if we want to print anything on the console, 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.

  1. Can this keyword be used to refer to static members?

Yes, this keyword can be used to refer to static members because it is just a reference variable that refers to the current class object. However, as we know, it is unnecessary to access static variables through objects, therefore, it is not the best practice to use this to refer to static members.

Example


public class ScholarHat {
 static int i = 50;

 public ScholarHat() {
 System.out.println(this.i);
 }

 public static void main(String[] args) {
 ScholarHat t = new ScholarHat();
 }
}

Output

50

  1. Explain super in Java

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you create the instance of the subclass, an instance of the parent class is created implicitly which is referred to by the super reference variable. The super() is called in the class constructor implicitly by the compiler if there is no super or this.

Example


class ScholarHat {
 ScholarHat() {
 System.out.println("ScholarHat class is created");
 }
}

class Student extends ScholarHat {
 Student() {
 System.out.println("Student class is created");
 }
}

public class Test {
 public static void main(String[] args) {
 Student s = new Student();
 }
}
 

Output

ScholarHat class is created
Student class is created

Read more about the super keyword in Constructors in Java

  1. What is runtime polymorphism or dynamic method dispatch?

  • Dynamic method dispatch is a resolving mechanism for method overriding during the run time.
  • Method overriding is the one where the method in a subclass has the same name, parameters, and return type as a method in the superclass.
  • When the over-ridden method is called through a superclass reference, java determines which version (superclass or subclass) of that method is to be executed based upon the type of an object being referred to at the time the call occurs.
  • Thus the decision is made at run time. This is referred to as dynamic method dispatch.

If you want to go in-depth about runtime polymorphism and method overriding, read more: Polymorphism in Java

  1. How is the new operator different from the newInstance() operator in Java?

Both new and newInstance() operators are used to create 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. If we don’t know the class name for which we need to create the object, we get the class name from the command line argument, or the database, or the file. In all such cases, 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.

  1. Explain the Java thread lifecycle

The following stages are in the Java thread lifecycle
  • 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 and before the run() method is called by JVM, the thread is said to be in a RUNNABLE (ready to run) state. This state can also be entered from the Waiting or Sleeping state of the thread.
  • Run – When the run() method has been invoked and the thread starts its execution, the thread is said to be RUNNING.
  • Blocked/Waiting – When the thread is not able to run despite being alive, the thread is said to be in a NON-RUNNABLE state. Ideally, after some time, 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 waiting 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 run() method execution is completed, the thread is said to enter the TERMINATED stage and is considered dead.

  1. State the differences between method overloading and overriding.

Method OverloadingMethod Overriding
Method overloading increases the readability of the program.Method overriding provides the specific implementation of the method that is already provided by its superclass.
Method overloading occurs within the class.Method overriding occurs in two classes that have an Is-A relationship between them.
The parameters must be different here.the parameters must be the same.

  1. When can an object reference be cast to an interface reference?

An object reference can be cast to an interface reference when the object implements the referenced interface.

  1. What do you understand by the jagged array?

A jagged array in Java is a 2D array in which each row of the array can have a different length. Since all the rows in a 2D array have the same length a jagged array allows more flexibility in the size of each row. This feature is very useful in conditions where the data has varying lengths or when memory usage needs to be optimized.

Example


int[][] arr = new int[][] {
 {1, 2, 3}, 
 {4, 5}, 
 {6, 7, 8, 9}
};
 

Learn more about arrays in Java in Java Arrays

  1. Will the finally block be executed if the code System.exit(0) is written at the end of try block?

No, it won't happen. The control of the program post System.exit(0) is immediately gone and the program gets terminated and thus the finally block never gets executed.

  1. What if we import the same package/class twice? Will the JVM load the package twice at runtime?

In Java, we 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.

  1. What are the differences between StringBuffer and StringBuilder?

StringBufferStringBuilder
StringBuffer is synchronized, i.e., thread-safe. It means two threads can't call the methods of StringBuffer simultaneously.StringBuilder is non-synchronized,i.e., not thread-safe. It means two threads can call the methods of StringBuilder simultaneously.
The String class overrides the equals() method of the Object class. So you can compare the contents of two strings by the equals() method.StringBuilder is more efficient than StringBuffer.

  1. In what ways is inheritance in C++ different from Java?

Inheritance in C++

Inheritance in Java
There is multiple inheritance possible in C++Java doesn’t support multiple inheritances.
When a class is created in C++, it doesn’t inherit from the object class, instead exists on its own.Java is always said to have a single inheritance as all the classes inherit in one or the other way from the object class.

  1. Are virtual functions available in Java?

Yes, Java supports virtual functions. Functions are by default virtual and can be made non-virtual using the final keyword.
Related Interview Articles:
5. JQuery Interview Questions  
Summary
In this Java tutorial, we saw the most commonly asked Java Interview Questions and Answers from basic to advanced levels. Java development can lead you to many high-paying job profiles like full-stack developer, Software Developer, etc. So, to become a trained Java developer, consider our Java Certification Program.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this