Java Interview Questions

In this article, we will see some of the top frequently asked Java Interview Questions. Let’s start!!

Java Interview Questions

1. List down a few differences between Java and C++.  

Java C++
It is a compiled and interpreted language. Only compilation takes place in C++.
It runs on any machine with JDK once it is compiled. Therefore, it is machine-independent. It runs only the machine where it is compiled. Therefore, it is machine-dependent. 
Usage of pointers is not allowed. Pointers are allowed.
It does not support multiple inheritance. It supports multiple inheritance.
The system takes care of the memory management. Manual memory management is required.

2. What features of Java do you think to make it outstanding among the other programming languages:

First and the foremost reason is that java is an easy programming language to learn. Programmers with prior knowledge of C++ tend to learn Java even more easily. 

It is an object-oriented programming language and considers everything in it as an object. 

The concept of multi-threading, allows it to tackle multiple client requests simultaneously.

3. Why do you think handling exceptions is important in Java?

If we leave the exceptions unhandled, the program ends abruptly and the following lines after the error will not run. 

With the help of exception handling concepts, we can control the flow of the program when it meets with unexpected disruptions.

4. Why does java’s index always start from 0 and not 1?

This is because the array’s first element gets placed at the pointer’s memory location, which makes the offset zero. And thus, the indexing in java always starts from 0. 

5. What does the JDK contain?

The JDK or the Java Development Kit consists of the Java Runtime Environment, a compiler, an interpreter, Javadoc which is a documentation generator, an archiver, and various other tools for Java development. 

6. What does the System.out.println() method do?

Any argument that we need to print, is sent via the System.out.println() method. The println() displays the output statement on the system in a new line. 

7. How do you think stack memory differs from heap memory?

Stack memory is a fixed memory that is allocated for every program by the system. Whereas, heap memory is not assigned to the java code but we can use that memory space whenever the Java code requires it during its runtime. 

8. How do you think association differs from aggregation?

In association, the relationship exists in such a manner that there’s no ownership over the other. It denotes the “HAS-A” relationship, “has a” that exists between two classes. And aggregation denotes the “HAS A” relationship that paves way for the ownership of one class over the other.   

9. Why doesn’t Java use pointers?

Memory management in java takes place implicitly. To avoid complexity, java has avoided the feature of accessing the memory directly using pointers. 

10. What error is thrown if the main() method is not declared as static?

If we do not declare the main() method, the NoSuchMethodError will be thrown. In this case, the program might be compiled, but the absence of the keyword static throws the run time error.

11. Why do we use the Wrapper class in Java?

In Java, we use a wrapper class to convert the primitive data types to reference types. These reference types are also known as objects. 

12. What makes Java a platform-independent language?

Java is well known as a program that supports the “Write Once, Run Anywhere”(WORA) concept. When it comes to this programming language, we need not worry about rewriting the program for every platform. The presence of JVM and Java Bytecode supports platform independence. Therefore, any operating system that supports the JVM runs the java bytecode. 

13. How would you call a constructor that is present inside another constructor?

We must use the this() keyword to call the constructor that is present in the same class. If the constructor is present inside another constructor in the base class, we must use the super() keyword. This process is known as constructor chaining. 

14. Are there any differences between the ‘new’ operator and the ‘newinstance()’ operator in Java?

Be it the ‘new’ operator or the ‘newInstance()’ method, they are used to create an object in Java. If we have a clear picture of the type of object we need to create, the ‘new’ operator is preferred. In the absence of the object’s type in advance, we can use the ‘newInstance’ method.

15. Imagine that you have already imported the java.io package into the program. What will happen if you try to import it again in the same program?

Importing the same package and class multiple times does not cause any discrepancies in the Java program. Though we import it multiple times, the JVM will load it only once. 

16. What do you think are some causes of memory leaks in Java?

To tell about memory leak, is the depletion of the system’s performance due to usage. The unnecessary objects present in the heap that are not removed by the garbage collector accumulate in the memory. This is the memory leak issue. 

Some of its causes include: 

  • Unwanted multiple-page swapping by the OS. 
  • Presence of unbounded caches.
  • Improper usage of data structures, etc. 

17. How many categories of constructors are present in Java?

The constructors in Java are of two types. 

  • Parameterized constructor
  • Default constructor

Parameterized constructor: When we use parameterized constructors, we can initialize the variables dynamically. 

Default constructor: We cannot use parameters here. The variables are initialized with their default values.

18. In what ways does the equals() method differ from the equality operator(==)?

equals() ==
We define this method in the Object class. This symbol is used as a binary operator.
It helps in checking the equality of the values between the two objects. It compares the addresses of two objects to find if both are pointing at the same memory location.
We can override this method to compare the objects. No modification is possible. The HashCode comparison always takes place. 

19. Can you override a static method?     

Overriding a static method is not allowed. This process takes place during the runtime. Whereas, the static methods are loaded during the compile time itself. Therefore, these methods cannot be overridden. 

20. Elucidate on JIT compiler:

The abbreviation of JIT compiler is Just in Time Compiler. It improves the performance of the java code by compiling bytecodes into the native machine code during the run time. Being a part of JVM, it also optimizes the performance of the application.

21. Is delete, true, false, or null a keyword in Java?

Delete, true, false, null, and other words like main, next, exit, and so on are not java keywords. But they fall under the category of literal or reserved words. Which means, we cannot use them as identifiers.

22. What are the various states in a Java thread life cycle?

The java thread life cycle happens in five states:

  • Newborn state: This is the stage when the thread is first created. 
  • Active state: It calls the start() method. it is inclusive of the runnable state and the running state.
  • Blocked or Waiting: When the thread is inactive for some time, it is said to be in the blocked or waiting state. 
  • Timed Waiting: With the help of the sleep() function, we can denote the time duration in milliseconds until which the thread should wait. 
  • Termination: When the thread is not active for a longer duration, it is destroyed. This state is known as the termination state. 

23. Write a Java program to create a user-defined exception.

public class MyException1  
{    
    static void validate (int age) throws InvalidAgeException{    
       if(age < 18){  
        throw new InvalidAgeException("The given age is not valid to vote");   
    }  
       else {  
        System.out.println("You can vote");   
        }  
     }    
    public static void main(String args[])  
    {  
        try 
        {  
            validate(13);  
        } 
        catch (InvalidAgeException ex)  
        { 
            System.out.println("Exception caught");  
            System.out.println("Exception occured: " + ex);  
        }  
    }  
}  

24. What do you understand about enumeration or enum in Java?

The enumeration or enum is an interface that is available in java. It is a special data type that consists of predefined constants. It allows access to the elements present in the array.

25. Is java a dynamic or static programming language?

Java is designed to evolve according to the current environment. The runtime information that it holds makes it a dynamic programming language. 

26. In what ways do you think JDBC helps in the java programming language?

With the help of JDBC, we can connect to a database or a data source. 

The queries let us achieve the result in just a single line. 

Data retrieval is easy.

JBC is easy to learn and deploy when we need to work with large sizes of data in Java. 

27. Which platform is essential in java to implement the features like encryption and decryption?

The Java Cryptography Architecture or the JCA is available in java to implement the encryption and decryption features. We can execute third-party security rules and regulations in applications that require security. This is achieved via a hash table, encryption message digest, and so on.

28. Write a Java program that results in finding the second largest number from an array.

public class SecondHighest {
public static void main(String[] args)
    {
        int array[] = { 1,5,8,23,45,11,67,21};
        int high = 0;
        int nextHigh = 0;
        System.out.println("Given array:");
        for (int i = 0; i < array.length; i++)
        {
            System.out.print(array[i] + "\t");
        }
        for (int i = 0; i < array.length; i++)
        {
            if (array[i] > high)
            {
                nextHigh = high;
                high = array[i];
            }
            else if (array[i] > nextHigh)
            {
                nextHigh = array[i];
            }
        }
        System.out.println("Second Highest value:" + nextHigh);
        System.out.println("Highest value: " +high);
    }
}

Output:

Given array:

1 5 8 23 45 11 67 21

Second Highest value: 45

Highest value: 67

29. How would you differentiate a HashSet from a TreeSet?

HashSet implements the Set interface that is unsorted, whereas TreeSet implements the sorted Set. A HashSet is executed using a hashmap, and a TreeSet is executed using a TreeMap.

30. If you create a variable or an object and do not assign any values to it, what will be the default values assigned to them in Java?

When we do not provide a particular value to the variables or objects, the default values will be assigned to them. In Java, the default integer value assigned to a variable is 0, for a boolean value it is false and for objects it is NULL.  

Summary

Hope you enjoyed the Java Interview Questions. Do not miss to check the other parts of Java Interview Questions for more learning.

Leave a Reply

Your email address will not be published. Required fields are marked *