Java Interview Questions

Here are the top 50 commonly asked questions in Java interviews. Whether you’re just starting your preparation or need a quick refresher, these questions and answers will help you tackle your interview with confidence.

Basic Java Interview Questions with Answers

1. What is Java?

Java is a high-level, object-oriented programming language developed by Sun Microsystems. It is known for its platform independence and write-once-run-anywhere capability.

2. What are the main features of Java?

Main features of Java include platform independence, object-oriented, robustness, security, multithreading, and portability.

3. What is the difference between JDK, JRE, and JVM?

JDK (Java Development Kit) is a software development kit used to develop Java applications. JRE (Java Runtime Environment) is the environment required to run Java applications. JVM (Java Virtual Machine) is an abstract machine that provides the runtime environment in which Java bytecode can be executed.

4. What is the difference between == and .equals() method in Java?

‘==’ is used to compare the memory addresses of two objects, while .equals() method is used to compare the content of two objects.

5. What is a constructor in Java?

Constructor is a special type of method that is called when an object is instantiated. It initializes the newly created object.

6. What is method overloading and method overriding in Java?

Method overloading is defining multiple methods in a class with the same name but different parameters. Method overriding is providing a specific implementation of a method that is already provided by its superclass.

advertisement
advertisement

7. What is the use of the ‘static’ keyword in Java?

The ‘static‘ keyword is used to create variables and methods that belong to the class rather than to any instance of the class. Static members can be accessed without creating an instance of the class.

8. What is the purpose of the ‘final’ keyword in Java?

The ‘final‘ keyword in Java is used to restrict the user from changing the value of a variable, prevent method overriding, or prevent inheritance of a class.

9. What is method chaining in Java?

Method chaining is a programming technique where multiple method calls are chained together in a single statement, typically by returning the current object from each method call.

10. Why is Java a platform independent language?

Java works on any computer because it uses a special system called the Java Virtual Machine. This system translates Java code into a format that any computer can understand. So, Java programs can run on different types of computers without needing to be rewritten for each one.

11. What is the purpose of the ‘this’ keyword in Java?

The ‘this’ keyword refers to the current instance of the class. It is used to differentiate between instance variables and parameters with the same name, and to call constructors from other constructors in the same class.

12. What is a Java package?

A Java package is a mechanism for organizing classes into namespaces. It helps in resolving naming conflicts and controlling access to classes and interfaces.

13. What is the purpose of the ‘super’ keyword in Java?

The ‘super‘ keyword is used to refer to the superclass of the current object. It can be used to call the superclass constructor, access superclass methods and variables, and differentiate between superclass and subclass members with the same name.

14. What is the ‘instanceof’ operator used for in Java?

The ‘instanceof‘ operator is used to test whether an object is an instance of a particular class or interface. It returns true if the object is an instance of the specified type, otherwise false.

15. What is the difference between ‘==’, ‘equals()’, and ‘compareTo()’ methods in Java?

==‘ is used for reference comparison, ‘equals()‘ is used for content comparison, and ‘compareTo()‘ is used to compare objects for ordering.

advertisement

16. What is a Java thread?

A thread in Java represents a separate path of execution within a program. It allows concurrent execution of tasks and helps in achieving multitasking.

17. What is inheritance in Java?

Inheritance is a mechanism in Java where a class (subclass) inherits properties and behaviors from another class (superclass). It promotes code reusability and supports the concept of hierarchy in object-oriented programming.

18. What is synchronization in Java?

Synchronization in Java is the process of controlling the access of multiple threads to shared resources. It prevents race conditions and ensures data consistency by allowing only one thread to access the synchronized block of code at a time.

19. What is a class in Java?

A class in Java is a blueprint for creating objects. It defines the properties (fields) and behaviors (methods) that objects of that type will have.

20. What is an object in Java?

An object in Java is an instance of a class. It has state (fields) and behavior (methods) defined by its class.

advertisement

Intermediate Java Interview Questions with Answers

21. What is polymorphism in Java?

Polymorphism in Java allows objects of different classes to be treated as objects of a common superclass. It enables methods to be defined in a superclass and overridden in subclasses to provide different implementations.

22. What is encapsulation in Java?

Encapsulation in Java is the process of bundling data (fields) and methods that operate on that data within a single unit (class). It protects the data from unauthorized access and maintains the integrity of the object’s state.

23. What is abstraction in Java?

Abstraction in Java refers to the process of hiding the implementation details of a class and exposing only the essential features to the outside world. It allows complex systems to be represented in a simplified manner.

24. What is method overriding in Java?

Method overriding in Java is the process of providing a specific implementation of a method that is already defined in the superclass. It allows a subclass to provide its own implementation of a method inherited from its superclass.

25. What is method overloading in Java?

Method overloading in Java is the process of defining multiple methods in a class with the same name but different parameters. It enables the same method name to perform different tasks based on the number and type of parameters passed to it.

26. What is a static method in Java?

A static method in Java is a method that belongs to the class rather than to any instance of the class. It can be called directly using the class name and is commonly used for utility methods that perform generic operations.

27. What is a static variable in Java?

A static variable in Java is a variable that belongs to the class rather than to any instance of the class. It is shared among all instances of the class and can be accessed using the class name.

28. What is a final class in Java?

A final class in Java is a class that cannot be subclassed. It is used to prevent inheritance and ensure that the class’s implementation remains unchanged.

29. What is the purpose of the ‘extends’ keyword in Java?

The ‘extends‘ keyword in Java is used to establish a subclass-superclass relationship between classes. It allows a subclass to inherit properties and behaviors from its superclass.

30. What is the purpose of the ‘implements’ keyword in Java?

The ‘implements’ keyword in Java is used to indicate that a class implements one or more interfaces. It allows the class to provide implementations for the methods declared in the interface(s).

31. What is the purpose of the ‘break’ statement in Java?

The ‘break‘ statement in Java is used to exit a loop or switch statement prematurely. It terminates the current loop iteration or switch statement and transfers control to the statement immediately following the loop or switch.

32. What is the purpose of the ‘continue’ statement in Java?

The ‘continue‘ statement in Java is used to skip the rest of the current iteration of a loop and proceed to the next iteration. It is commonly used to skip certain iterations based on specific conditions.

33. What is synchronization in Java?

Synchronization in Java is the process of controlling the access of multiple threads to shared resources. It prevents race conditions and ensures data consistency by allowing only one thread to access the synchronized block of code at a time.

34. What is exception handling in Java?

Exception handling in Java is the process of handling runtime errors or exceptional conditions that occur during the execution of a program. It involves catching, handling, and/or propagating exceptions using try-catch blocks and other mechanisms provided by the Java language.

35. What are Java generics?

Java generics provide a way to create classes, interfaces, and methods that operate on specified types. They allow the use of type parameters to define classes and methods that can work with any data type, providing compile-time type safety and reducing the need for explicit type casting.

36. What are the access modifiers in Java?

Access modifiers in Java control the visibility and accessibility of classes, variables, methods, and constructors. The main access modifiers are ‘public’, ‘private’, ‘protected’, and ‘default’ (no modifier), each determining the level of access to members within the same class, subclass, package, or outside the package.

37. What is the purpose of the ‘volatile’ keyword in Java?

The ‘volatile‘ keyword in Java is used to indicate that a variable’s value may be modified by multiple threads concurrently. It ensures that changes to the variable are visible to all threads and prevents the compiler from performing certain optimizations that could affect the variable’s visibility.

38. What is the ‘transient’ keyword used for in Java?

The ‘transient‘ keyword in Java is used to indicate that a variable should not be serialized during object serialization. It is typically used for variables that do not need to be persisted or whose values can be derived or reconstructed upon deserialization.

39. What is the purpose of the ‘finalize()’ method in Java?

The ‘finalize()‘ method in Java is a special method that is called by the garbage collector before reclaiming the memory occupied by an object. It can be overridden to perform cleanup or resource release operations before the object is garbage collected.

40. What is the difference between ‘StringBuilder’ and ‘StringBuffer’ in Java?

StringBuilder‘ and ‘StringBuffer‘ are both used to manipulate string data, but ‘StringBuilder’ is not thread-safe, while ‘StringBuffer’ is thread-safe. ‘StringBuilder’ provides better performance in single-threaded.

41. What are the differences between C++ and Java?

Here’s the comparison between C++ and Java.

Feature C++ Java
Platform Dependency Platform-dependent (compiled to native machine code) Platform-independent (compiled to bytecode)
Memory Management Manual (programmer manages memory allocation and deallocation using new and delete) Automatic (garbage collection mechanism handles memory management)
Type System Supports pointers and multiple inheritance Does not support pointers and restricts multiple inheritance to interfaces
Exception Handling Uses try-catch blocks for exception handling Uses try-catch-finally blocks for exception handling
Standard Libraries Provides the Standard Template Library (STL) for data structures and algorithms Offers the Java API for extensive pre-built classes and methods
Compilation and Execution Compiled directly to machine code Compiled to bytecode (requires JVM for execution)

42. What are the primitive data types in Java?

Java has eight primitive data types: byte, short, int, long, float, double, char, and boolean. These data types represent basic values and are not objects.

43. What is the Java Virtual Machine (JVM), and why is it important?

The Java Virtual Machine (JVM) is an abstract computing machine that enables Java bytecode to be executed on any platform. It provides platform independence by translating bytecode into machine code specific to the host system. The JVM serves as the runtime environment for Java applications, ensuring portability and compatibility across different platforms.

44. Can a subclass inherit constructors from its superclass in Java?

No, a subclass cannot inherit constructors from its superclass in Java. However, the subclass can call the constructor of the superclass using the ‘super()’ keyword to initialize inherited members.

45. How do you create and manipulate strings in Java?

Strings in Java can be created using the ‘String’ class. You can manipulate strings using various methods such as concatenation (+ operator), substring(), length(), indexOf(), replace(), toUpperCase(), toLowerCase(), etc.

46. What are sockets in Java networking?

Sockets in Java networking are endpoints for communication between two machines over a network. They enable bidirectional data transfer between client and server applications. Java provides classes like Socket and ServerSocket in the java.net package to implement socket-based communication.

47. What is the Java Collections Framework, and why is it important?

The Java Collections Framework is a set of classes and interfaces that provide a standardized way to store and manipulate collections of objects in Java. It offers high-performance, reusable data structures and algorithms for common tasks such as searching, sorting, and iteration. The framework promotes code reuse, efficiency, and type safety in Java applications.

48. What are I/O streams in Java, and what are their types?

I/O streams in Java are channels through which data flows between a program and an external source or destination, such as files, network connections, or devices. Java I/O streams are classified into two types: byte streams (used for handling raw binary data) and character streams (used for handling text data).

49. What is event handling, and why is it important in Java GUI programming?

Event handling in Java refers to the process of responding to user actions or system events, such as mouse clicks, keyboard inputs, or window events. It is crucial in GUI programming to create interactive and responsive user interfaces. Java provides event-driven programming mechanisms such as event listeners and event handlers to manage and process various types of events.

50. What is an interface in Java?

An interface in Java is a reference type that defines a set of abstract methods and constants. It represents a contract for classes to implement, specifying the behavior that implementing classes must adhere to. Interfaces allow for abstraction, multiple inheritance, and polymorphism in Java.

51. How do you create and use JavaBeans in Java applications?

JavaBeans are reusable software components that adhere to certain naming conventions and design patterns. To create a JavaBean, you typically define private fields, public getter and setter methods (also known as accessors and mutators), and implement the Serializable interface for serialization. JavaBeans are commonly used in graphical user interface (GUI) development, database programming, and other software applications for encapsulating data and functionality.

Java Programming Interview Questions with Answers

52. What is the output of the following code snippet?

public class Main
{
    public static void main(String[] args)
    {
        int a = 10;
        int b = 0;
        System.out.println(a / b);
    }
}

Answer: Error: Division by zero

Explanation: The code attempts to divide an integer by zero, which is an illegal arithmetic operation in Java. This results in a runtime error called ArithmeticException.

53. What is the output of the following code snippet?

public class Main
{
    public static void main(String[] args)
    {
        int x = 128;
        byte b = (byte) x;
        System.out.println(b);
    }
}

Answer: -128

Explanation: When an integer value like 128 is cast to a byte, it exceeds the byte’s range (-128 to 127). So, it wraps around and becomes -128 due to overflow.

54. What is the output of the following code snippet?

public class Main
{
    public static void main(String[] args)
    {
        int x = 10;
        int y = 5;
        int z = (x >= y) ? (x - y) : (y - x);
        System.out.println(z);
    }
}

Answer: 5

Explanation:

  • In this code, the conditional (ternary) operator ? : is used to determine the value of z.
  • If the condition (x >= y) evaluates to true, then the expression (x – y) is assigned to z. Otherwise, the expression (y – x) is assigned to z.
  • Since x is greater than or equal to y (10 is greater than 5), the expression (x – y) is evaluated, resulting in z having the value of 10 – 5 = 5.
  • Therefore, when z is printed, it outputs 5.

55. What is the output of the following code snippet?

public class Main
{
    public static void main(String[] args)
    {
        String str = "Hello";
        str.concat(" World");
        System.out.println(str);
    }
}

Answer: Hello

Explanation: The concat method is used to concatenate strings, but it doesn’t modify the original string; it returns a new string. Since the return value isn’t assigned to str, printing str still gives “Hello”.

56. What is the output of the following code snippet?

import java.util.ArrayList;
import java.util.List;
 
public class Main
{
    public static void main(String[] args)
    {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.remove(1);
        System.out.println(numbers.get(1));
    }
}

Answer: The code will throw an IndexOutOfBoundsException at runtime.

Explanation: After removing the element at index 1 (which contains the value 20), the list only has one element left. When trying to access index 1 using numbers.get(1), it goes out of bounds since there is only one element in the list, causing the exception.

57. What is the output of the following code snippet?

public class Main
{
    static int x = 5;
 
    static
    {
        x += 5;
    }
 
    public static void main(String[] args)
    {
        System.out.println(x);
    }
}

Answer: 10

Explanation: The static block increments the static variable x by 5 before the main method is executed. Therefore, x becomes 10 when printed in the main method.

58. What is the output of the following code snippet?

class Parent
{
    Parent()
    {
        System.out.println("Parent constructor");
    }
}
 
class Child extends Parent
{
    Child()
    {
        super();
        System.out.println("Child constructor");
    }
 
    public static void main(String[] args)
    {
        new Child();
    }
}

Answer:

Parent constructor
Child constructor

Explanation: hen an object of the Child class is created, it triggers the constructor of its superclass Parent first due to the super() call in the Child constructor. Then, the Child constructor executes.

59. What is the output of the following code snippet?

public class Main
{
    public static void main(String[] args)
    {
        final int x;
        x = 20;
        System.out.println("x = " + x);
    }
}

Answer: 20

Explanation: In this code, a final variable x is declared without initialization. Then, it is assigned the value 20. Since x is declared as final, it can only be assigned a value once.
Therefore, when x is printed using System.out.println(), it outputs x = 20.

60. What is the output of the following code snippet?

public class MyClass
{
    public int add(int a, int b)
    {
        return a + b;
    }
 
    public double add(double a, double b)
    {
        return a + b;
    }
 
    public static void main(String[] args)
    {
        MyClass obj = new MyClass();
        System.out.println(obj.add(2, 3));
        System.out.println(obj.add(2.5, 3.5));
    }
}

Answer:

5
6.0

Explanation: The code calls two different overloaded add methods: one with integer parameters and one with double parameters. The first call returns the sum of integers 2 and 3, which is 5. The second call returns the sum of doubles 2.5 and 3.5, which is 6.0.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.