Top Java Interview Questions (and Answers)

java-interview-questions

Java is among the most widely used programming languages. The scope of this language is increasing at a constant pace. Companies are demanding more from individuals who are well-versed in Java programming language.

Being well-versed in Java means that you should have advanced knowledge of the programming language. Many companies hire Java developers on the basis of how well they know Java fundamentals.

If you are willing to work in the IT industry as a professional Java developer, you need to learn Java. For that, you can go for Java books or courses; whatever feels more suitable to you.

Once you have the recommended knowledge of Java, the next step is to apply for Java developer jobs and crack interviews to get a high-paying job. However, it’s important to prepare yourself effectively for a Java interview so that your chances of getting hired increase.

Well, in this blog, you will know some of the basic Java interview questions and answers that you can come across while appearing for an entry-level Java developer job interview. So, let’s take a look at all of them.

Top Java Interview Questions and Answers

1. What files does a Java downloaded file contain? Mention them.

Java downloaded file consists of JDK (Java Development Kit) and JRE (Java Runtime Environment)

JDK: 

    • It is a special kit intended only for software development.
    • An installer file will be included with the JDK package.
    • The JDK package provides a collection of development and debugging tools.
    • It is platform-dependent in contrast to JVM.

JRE:

  • It is a collection of programs and libraries used to run Java programs.
  • It is platform dependent, unlike JVM.
  • JRE Package is one that solely supports runtime environment files and libraries.
  • The JRE Package just includes a runtime environment and lacks an installer.

2. What is the reason for the absence of pointers in Java, unlike C or C++?

Java focuses on writing simple code, therefore it avoids the use of pointers. In general, potential faults can be caused by pointer usage. Furthermore, the use of pointers compromises security since they allow users to access memory directly. Thus, the absence of pointers in Java provides a certain level of abstraction.

Furthermore, the use of pointers may result in a delayed and inaccurate garbage collection process. Java uses references because, unlike pointers, they cannot be changed.

3. What are wrapper classes?

Java primitives are converted into reference types through wrapper classes. There is a class for each primitive data type. Integer, boolean, and other primitive data types can be used as objects by using wrapper classes. They “wrap” the primitive data type into an object of that class.

Since you have to deal with objects, you have access to a variety of methods for learning more about a given object.

To obtain the value associated with the corresponding wrapper object, for instance, twe use these methods: intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), and booleanValue ().

Example:

public class Main {
  public static void main(String[] args) {
    Integer myInt = 10;
    Double myDouble = 7.65;
    System.out.println(myInt);
    System.out.println(myDouble);
  }
}

4. What are constructors in Java? Why do we need them?

In Java, the object’s state is initialized using constructors. Constructors, like methods, encapsulate a collection of statements or instructions that should be carried out while an object is being formed. 

There are mainly two types of constructors:

  1. Default Constructor: A default constructor does not require any input. These constructors do not need arguments, and Java creates these constructors by default in case the user does not create any constructor explicitly. The main objective of the default constructor is to initialize the instance variables with the default values. Also, it is majorly used for object creation.
  2. Parameterized Constructor: A parameterized constructor is used when you need to initialize the instance variables with some values. In other words, parameterized constructors are the ones that take arguments.

If you consider an example of a class Student, several variables, including roll no, name, and class, may be present. The Student class will not have any defined values for an object’s dimensions when it is created.

The constructors give values to the class’s variables when generating new objects. Values can either be directly assigned using the arguments given by the programmer or implicitly by using Java’s default constructors.

For example:

import java.io.*;
class Techstrot{
Techstrot() { super(); }
public static void main(String[] args)
{
Techstrot tech = new Techstrot();
}
}

5. What variations exist between stack and heap memory in Java?

The memory allotted to each distinct program is known as stack memory. It is a static area of memory. Contrarily, heap memory is the area that was not allotted to the Java code but will be accessible to it when needed, which is often during the course of the program’s runtime.

6. What are copy constructors in Java, also list some of their advantages.

When you need to initialize the value of a new object from an existing object of the same class, you can use the copy constructors. The main benefit of using copy constructor is that any modifications made to the copy will not affect the original, and vice versa.

Here’s an example of copy constructor:

public class Student  
{  
    private double marks;  
    private String name;  
    //constructor to initialize name and marks  
    Student(double Marks, String Name)  
    {  
        marks = Marks;  
        name = Name;  
    }  
    //copy constructor  
    Student(Student stu)  
    {  
        System.out.println("\nAfter invoking the Copy Constructor:\n");  
        marks = stu.marks;  
        name = stu.name;  
    }  
    //creating a method that returns the marks  
    double showMarks()  
    {  
        return marks;  
    }  
    //creating a method that returns name
    String showName()  
    {  
        return name;  
    }  
    //main method
    public static void main(String args[])  
    {  
        Student s1 = new Student(99, "John");  
        System.out.println("Name of the first student: "+ s1.showName());  
        System.out.println("Marks of the first student: "+ s1.showMarks());  
        //passing params to the copy constructor  
        Student s2 = new Student(s1);  
        System.out.println("Name of the second student: "+ s2.showName());  
        System.out.println("Marks of the second student: "+ s2.showMarks());  
    }  
}

Output:

Name of the first student: John
Marks of the first student: 99.0
After invoking the Copy Constructor
Name of the second student: John
Marks of the second student: 99.0

Following are some of the advantages of copy constructor:

  • A field that has been marked as final may be modified by the copy constructor.
  • Typecasting is not necessary.
  • The more fields an item contains, the easier it is to use. Because of this, adding a field to the class is simple. You only need to make modifications to the copy constructor.

7. Why Java is known as a platform-independent language?

As Java programs can operate on numerous systems without having to be individually rewritten for each platform. The programming language follows “Write Once, Run Anywhere” (WORA), which makes it platform-independent.

Java compiler, in contrast to other compilers, does not create native executable files or platform-specific code. Instead, Java’s compilation process creates byte code, a unique format. A.class file is another name for this created file.

The Java Virtual Machine’s Byte Code is a collection of machine instructions for the Java processor chip. Machine language and Java Byte Code are quite similar, yet Java Byte Code is completely consistent across all platforms.

8. What is the use of the Super keyword in Java, also provide an example.

Superclass (parent) objects are referred to by the Super keyword. It is used to access the superclass constructors as well as call methods from superclasses.

When the names of data members and member functions of a superclass and a subclass (child class) are identical, the Java Virtual Machine has a high likelihood of producing ambiguity.

We utilize the super keyword to directly access members of superclasses in order to eliminate this misunderstanding caused by members with the same name in two classes.

Example:

class SuperClass
{
    int x;
    SuperClass()
    {
        x=5;
    }
}
class SubClass extends SuperClass
{
    int x;
    SubClass()
    {
        //a call to superclass variable
        x = super.x * 2;
    }
 
    void setSubClass()
    {
        System.out.println("The value of variable a in superclass: " +super.x);
        System.out.println("The value of variable a in subclass: " +x);
    }
}
 
class Main
{
    public static void main(String[] args)
    {
        SubClass obj = new SubClass();
        obj.setSubClass();
    }
}

9. Explain the usage of the “this” keyword in Java.

We use the “this” keyword in Java to refer to the object that is currently being used inside a method or constructor.

Following is the list of uses of the “this” keyword:

  • It may be provided as a constructor call argument.
  • You can use it to call or start the current class constructor.
  • It may be supplied in the method called an argument.
  • It can be used to refer to a current class’s instance variables.
  • You can return the current class instance using “this”.

10. What is a JIT compiler in Java?

In Java, JIT stands for the just-in-time compiler. It is a program that assists in converting Java bytecode into machine-level instructions for the processor. The JIT compiler is enabled by default in Java and is launched each time a Java method is called.

The invoked method’s bytecode is next translated into native machine code by the JIT compiler, which does this “just in time” for execution. Once the method has been compiled, the JVM directly invokes the method’s compiled code as opposed to interpreting it. Because of this, it is frequently responsible for runtime performance optimization for Java programs.

11. Define exceptions and the type of exceptions in Java.

An exception is a type of error that might occur while a program is being executed and obstruct the regular course of events.

There are two types of exceptions in Java:

  1. Checked Exception

The exceptions that are checked at compile time are known as checked exceptions. Checked exceptions directly inherit Throwable class except RuntimeException and Error. For e.g. IOException, SQLException, ClassNotFoundException, InvocationTargetException, FileNotfound Exception.

The compiler also checks to see if the method is specified with the throws keyword if there is no code to handle them. Additionally, the compiler reports a compilation error if neither of the two situations exists.

  1. Unchecked Exception

The exceptions that are checked at runtime and not in compile time are unchecked exceptions. Unchecked exceptions inherit RuntimeException. For e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, InputMismatchException, IllegalStateException, Missing Resource Exception, etc.

During compilation, the compiler typically disregards unchecked exceptions. Runtime checks are made on unchecked exceptions. As a result, the compiler does not verify if the user program has the necessary handling code.

12. What is garbage collection in Java, and how does it work?

The act of scanning through heap memory and determining which objects are being used and which are not, along with eliminating the latter, is known as garbage collection.

A referenced object, also known as an in-use object, indicates that some portion of your software still keeps a pointer to it. Any portion of your software that no longer references to an unused object is often known as an unreferenced object. Consequently, memory that was consumed by an unreferenced object can be freed up.

The primary benefit of garbage collection is that it frees us from having to manually allocate and deallocate memory, allowing us to concentrate on the issue at hand.

13. How can you implement garbage collection through code?

Java garbage collection cannot be forced; it only occurs if the JVM determines that it is necessary based on the size of the Java heap. The finalise() method of an object is called by the garbage collection thread before that object is removed from memory, giving the time to do any necessary cleanup.

You can also call this method of an object code, but doing so does not ensure that trash collection will take place. Furthermore, there are methods like System.gc() and Runtime.gc() that are used to request garbage collection from the JVM, but this is not a guarantee that it will occur.

14. Differentiate between throw and throws keywords in Java.

The throw keyword is used to interrupt program execution and forward the exception object to runtime for handling. Checked exceptions cannot be propagated via the throw keyword. Only unchecked exceptions that are not checked using the throws keyword are propagated using the throw keyword. 

The throws is used with method signatures to declare potential exceptions that the function might throw. Only checked Exceptions can be propagated using the throws keyword.

15. What are local variables and instance variables in Java?

Instance Variables

If all methods in the class can access variables that those variables are known as instance variables. They are stated both inside the class and outside the methods. These are the variables, which are inextricably linked to an object, and are bound to it at any cost.

Each class object will have a copy of the variables available for use. All other instances of the class continue to be untouched if any changes are made to these variables; just that instance will be affected.

class Techstrot {
    public String name;   //instance variables for testMethod2
    public double trafficPercent;
    public int users;
}

Local Variables

Local variables are variables that can only be accessed inside a block, function, or constructor. The variable can only be used within the block scope, and it is not even recognized by other methods in the class.

If a local variable is declared, it should be initialized within the block before being used.

class Techstrot{
    public void testMethod() {
        String name;  //local variables for testMethod2
        double trafficPercent;
        int users;
        ........
    }  
    public void testMethod2(){
        String name2;  //local variables for testMethod2
        double trafficPercent2;
        int users2;
        ......
    }
}

16. Is it possible to have an empty catch block?

An empty catch block is possible, but it’s a poor programming practice to do so. Never leave the catch block empty because if the exception is caught there, we won’t know what caused it and it will be difficult to troubleshoot. To log the exception information in the console or log files, at the very least, a logging statement must be included.

17. Can a static method be overloaded?

No, overloading a static method is not supported by Java. An error stating “static method cannot be referenced” would be thrown by the process.

18. What do you mean by threads in Java?

The lowest and lightest processing unit that a scheduler can control independently is a thread. Threads are components of a process that only enable the concurrent, efficient execution of programs with other components or threads of the process.

The simplest approach to complete challenging tasks is by using threads. It is thought to be the simplest method for utilizing a machine’s numerous CPUs. They are separated from one another yet share the same address space.

19. Differentiate between a thread and a process.

ThreadProcess
It simply refers to the tiniest components of a process. It is possible to run multiple threads or sections of a program simultaneously.This term simply denotes an active program that is currently running. PCB can be used to manage a process (Process Control Block).
The process of creation, termination, and context change takes less time.The process of creation, termination, and context switching takes more time.
Although each thread runs separately, they are all dependent on one another because they are members of a process.There is no interdependence between processes.
Synchronization across threads is necessary to prevent unforeseen events or issues.Each process does not need to be synchronized.

Conclusion

Java developers are among the most sought-after professionals in the IT sector. Therefore, having a solid foundation is essential if you want to advance your career as a Java Developer.

We have discussed some of the most significant Java interview questions that you can review before appearing for a Java interview. By going through them, you would be able to prepare yourself effectively for your upcoming interviews and boost your chances of cracking them.

All the best!

Share Your Thoughts, Queries and Suggestions!