Top 50 Java Interview Questions with Expert Answers

Whether you’re new to coding or a seasoned pro, facing Java interview questions can feel exciting and a bit scary. Java is a big deal in the tech world, so being ready is super important.

From basic ideas to really hard stuff, we’ll cover everything you need to know. So, whether you’re getting ready for your first Java interview or want to get better at it, join us! Let’s get started!

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

JDK stands for Java Development Kit. It is a software development kit that includes tools for developing Java applications. JRE stands for Java Runtime Environment. It is the environment in which Java programs run. JVM stands for Java Virtual Machin. It is the virtual machine that executes Java bytecode.

2. What is the method?

•  Collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.

• A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method’s name. Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name

3. What is the Constructor?

• A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created.
• Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.

4.Difference between a Constructor and a Method

Constructor doesn’t have a return type and constructor’s name must be same as the class name. 
Constructor is called automatically when a new object is created. Constructor is invoked implicitly.
• The Java compiler provides a default constructor if we don’t have any constructor. o Constructors are not inherited by child classes.

Method have a return and the method’s name may or not be same as the class name. 
•  Method is invoked explicitly.
• Method is not provided by compiler in any case.
• Methods are inherited by child classes.

5. What is the difference between a local variable and an instance variable?

• A local variable is typically used inside a method, constructor, or a block and has only local scope. Thus, this variable can be used only within the scope of a block. The best benefit of having a local variable is that other methods in the class won’t be even aware of that variable.

•An instance variable in Java, is a variable which is bounded to its object itself. These variables are declared within a class, but outside a method. Every object of that class will create its own copy of the variable while using it. Thus, any changes made to the variable won’t reflect in any other instances of that class and will be bound to that particular instance only.

6. What is Object Oriented Programming (OOP)?

• OOP is a programming language model organized around object rather than actions (logic and functions).
• In other words, OOP mainly focuses on the objects that are required to be manipulated instead of logic. This approach is ideal for the programs large and complex codes and needs to be actively updated or maintained.;
• It makes development and maintenance easier – It provides data hiding – It provides ability to simulate real-world.

7. What are the most commonly used OOPs?

Encapsulation : We can hide direct access to data by using private key and we can access private data by using getter and setter method. 

Abstraction : It is a process of hiding implementation details and showing only functionality to the user. Abstraction lets you focus on what the object does instead of how it does it.

Inheritance : It is used to define the relationship between two classes. When a child class acquires all properties and behaviors of parent class known as inheritance. Child class can reuse all the codes written in parent class. It provides the code reusability.

Polymorphism : It is an ability of object to behave in multiple form. The most common use of polymorphism in Java is when a parent class reference type of variable is used to refer to a child class object.

8. What is the difference between Abstraction and Encapsulation

• Abstraction lets you focus on what the object does instead of how it does it.
• Abstraction is used for hiding the unwanted data and giving relevant data.
•Abstraction can achieved by using Abstract class and Interfaces

Encapsulation means hiding the internal details of how the object does something.
•  Encapsulation means hiding the code and data, and to protect the data from outside.

• Encapsulation can achieved by using “private” keyword.

9. What is Polymorphism

Polymorphism is an ability of object to behave in multiple form. and it occurs when we have many classes that are related to each other by inheritance. Polymorphism is implemented using the concept of Method overloading and method overriding. This can only happen when the classes are under the parent and child relationship using inheritance.

10. What is the difference between Abstract Class and Interface

Abstract Class can have instance methods that implements a default behavior. A class that is declared with abstract keyword, is known as abstract class . It can have abstract and non–abstract methods. It can have abstract and non–abstract methods. When we want to use Abstract class, we use “extend” keyword.

Interface is implicitly abstract and cannot have implementations. Interface is a blueprint of a class. It is a template and it is declared with interface keyword. It can have abstract methods, default methods, static methods and public final static variables. When we want to use Interface, we use “implement” keyword.

11. What is Inheritance?

Inheritance represents the IS-A relationship which is also known as a parent-child relationship. It is the mechanism in java by which one class is allowed to inherit the features (fields and methods) of another class.  The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.

12. What is the difference between SuperClass and SubClass ?

SuperClass is a class that is being inherited from. It’s also known as a parent class or a base class. It contains common properties and behaviors that are shared by one or more subclasses.

Subclass is a class that inherits from another class. It’s also known as a child class or a derived class. Subclasses inherit fields and methods from their superclass.

13. What is the difference between Polymorphism and Inheritance ?

Inheritance is used to define the relationship between two classes. It is similar to Father-Son relationship. In Java, we have Parent class (also known as super class) and child class (also known as subclass). Similar to the real-world, Child inherits Parents qualities, methods and codes.

Polymorphism is an ability of object to behave in multiple form. It is classified as overloading and overriding. They are actually related to each other, because its inheritance which makes Polymorphism possible, without any relationship between two class. It is not possible to write polymorphic code.

14. What is the difference between method Overloading and method Overriding?

In overloading , method name must be the same, but the parameters must be different;
•  We can overload static, final and private method in Java.
Overloading happens in the same class;
Return type can be same or different;

In Overriding, method name and parameters must be same;
Overriding occurs in two classes that have inheritance relationship.
We cannot override static, final and private method in Java
Return type must be same or covariant
type.

15. What is immutable

Immutable means that once the constructor for an object has completed execution that instance can’t be altered. This is useful as it means you can pass references to the object around, without worrying that someone else is going to change its contents.

16. What are the different access modifiers?

Java provides a 4 types of access modifiers to set access levels for classes, variables, methods, and constructors:
Default: Visible to the package, the default. No modifiers are needed.
Private: Visible to the class only.
Public: Visible to the world.
Protected: Visible to the package and all subclasses.

17. What are  Java Collections?

Java Collections Framework provides a set of interfaces and classes to work with collections of objects. It includes interfaces like List, Set, and Map, along with classes like ArrayList, HashSet, and HashMap. These collections offer different functionalities, such as storing elements in a specific order, ensuring uniqueness, or mapping keys to values. They are used to store, manipulate, and retrieve groups of objects efficiently in Java programs.

18. What is the difference between Set, List and Map in Java? 

They are three important interface of Java collection framework: 
List provides ordered and indexed collection which may contain duplication . 
Set provides un-ordered collection of unique objects. Set doesn’t allowed duplication. List and Set are both extend collection interface.
Map provides a data structure based on Key Value. Key is always unique, value can be duplicate.

19. When do you use List, Set and Map?

Use a list when you need an ordered collection with duplicates.
Use a set when you need a collection of unique elements.
Use a map when you need to associate keys with values.

20. What is Array?

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

21. What are the advantages and disadvantages of Array ?

Advantages:
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
 Random access: We can get any data located at any index position.

Disadvantages:
Size Limit: We can store only fixed size of elements in the array. It doesn’t grow its size at runtime. To solve this problem, collection framework is used in java.
No Built-in Methods: Arrays have no built-in methods for common operations like adding or removing elements.

22. What is ArrayList?

It is a dynamic array-like data structure that can dynamically grow and shrink in size. Unlike Arrays, ArrayList can automatically resize itself when elements are added or removed, making it more flexible and convenient to work with.

23. What is the difference between Arrays and ArrayList?

• Array is a part of core Java programming and has special syntax.
Array is a fixed length data structure, so we can’t change length of Array one created.
Array can contain both primitives and objects.
We use “length” method  to find length for an
Array.

• ArrayList is part of collection framework and implement List interface.
ArrayList is resizable.
ArrayList can only contain objects. It cannot contain primitive types.
We use size() method to find length for an ArrayList. 

24. What is Thread Safe?

Making code thread-safe ensures that it behaves correctly and consistently in multi-threaded environments, reducing the risk of concurrency and data corruption. However, thread safety comes with a cost, a slow performance.

25. What is the Synchronized keyword? 

Synchronization is the easiest and most widely used tool for thread safety. Using the synchronized keyword to ensure that only one thread can execute a critical section of code at a time. This prevents multiple threads from accessing shared resources simultaneously and helps avoid race conditions.

26. What is difference between Hashtable and HashMap in Java?

Synchronization: Hashtable is synchronized, which means it is thread-safe. Multiple threads can access a Hashtable concurrently without any inconsistency. On the other hand, HashMap is not synchronized, so if multiple threads try to access a HashMap concurrently and at least one of these threads modifies the HashMap structurally (i.e., adding or removing elements), then it must be synchronized externally.
Performance: Due to synchronization, Hashtable may be slower than HashMap in a single-threaded environment. HashMap doesn’t have the overhead of synchronization, making it potentially faster in such scenarios.
Null values and keys: HashMap allows null values and one null key. Hashtable, on the other hand, does not allow null keys or values. If you try to insert a null key or value into a Hashtable, it will throw a NullPointerException.

27. How would you handle Exception?


Use try-catch blocks to catch exceptions that might occur within the code. This allows you to gracefully handle the exceptional situation without crashing the program.
• Use Multiple Catch Blocks: If different exceptions need to be handled differently, use multiple catch blocks to handle each type of exception separately.
Throw Exceptions : If your method cannot handle an exception locally and needs to propagate it to the caller, use the throws keyword in the method signature to declare the exception being thrown.

28. What are final vs finalize vs finally ?

final, finalize, and finally are three different concepts in Java:
final is a keyword and used to apply restrictions on class, method and variable:
–  final Class CAN’T be Inherited
–  final Method CAN’T be Overridden
–  final Variable value CAN’T be changed.
finally is a block and used to place important code, it will be executed whether exception handled or not
finalize is a method and used to perform clean-up processing before Object is Garbage collected.

29. What is the difference between Error and Exception in Java?

Both Error and Exception are subclasses of the Throwable class. Error typically indicates severe problems with the JVM or environment, while Exception represents exceptional conditions that are expected to be handled within the application code for error recovery.
Cause:
Error: Typically caused by serious problems with the JVM or the environment.
Exception: Arises due to exceptional conditions during the execution of the program, such as invalid input or resource unavailability.
Handling:
Error: Generally not meant to be caught or handled by application code; often indicates a severe issue that may require terminating the program.
Exception: Meant to be caught and handled by application code to ensure graceful error recovery and program stability.

30. What is difference between RuntimeException and CheckedException in Java?

Checked exceptions are checked by the compiler at compile-time and must be declared or handled by the programmer. Such as IOException, SQLException.
RuntimeExceptions are not checked by the compiler at compile-time and do not need to be declared or handled explicitly. Such as NullPointerException, ArrayIndexOutOfBoundsException.
Checked exceptions are typically used for conditions that a programmer can anticipate and recover from, while RuntimeExceptions often indicate programming errors or unexpected conditions.

31. What is Static in Java?

Static is a keyword that can be applied to variables, methods, and nested classes. When applied, it means that the particular member belongs to the class itself, rather than to instances of the class. The main advantage of using static members is that they can be accessed without the need to instantiate the class.

32. Explain the Main method?

In Java, the public static void main(String[] args) method is the entry point of a Java application. When you run a Java program, the Java Virtual Machine (JVM) looks for this method and starts executing your code from there.
public: This keyword denotes that the main method is accessible from outside the class. It means that the main method can be called by any other class.
static: The static keyword indicates that the main method belongs to the class itself, rather than to instances of the class. This means you can call the main method without creating an object of the class.
void: This indicates that the main method does not return any value. In Java, methods can return a value of a specific data type or void if they don’t return anything.
main: This is the name of the method. It’s a convention in Java to name the entry point method main.
String[] args: This is the parameter passed to the main method. It’s an array of strings that allows you to pass command-line arguments to your Java program when you run it. These arguments can be used to control or configure the behavior of the program.

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

throw: Used to explicitly throw an exception within a method to indicate that an exceptional condition has occurred.
throw: Followed by the “new” keyword and an instance of an exception class.
throw: Used within the method body to indicate exceptional conditions.
throw: Immediately terminates the execution of the method and passes the thrown exception to the nearest enclosing try-catch block or to the caller if not caught within the method.

throws: Used in the method declaration to specify the types of exceptions that the method may throw during its execution.
throws: Follows the method signature and lists the exception types separated by commas.
throws: Used in the method declaration to declare the types of exceptions that may be thrown by the method.
throws: Does not alter the flow of execution within the method; it only specifies the types of exceptions that may be thrown

34. What is the difference between Object and Class?

Class:
•  A class is a blueprint or template for creating objects.
•  It defines the properties (attributes) and behaviors (methods) that objects of that class will have.
•  It acts as a blueprint from which individual objects are created.
•  Classes are defined using the class keyword followed by the class name.

Object:
• An object is an instance of a class. 
• Objects have state (attributes) and behavior (methods) as defined by their class.
• When you create an object of a class, you are instantiating that class. You can create multiple objects from the same class, and each object will have its own set of instance variables.
• Objects are created using the new keyword followed by the class name and constructor arguments (if any).

35. What is the difference between StringBuffer and StringBuilder?

StringBuffer:
• StringBuffer is synchronized, meaning it is thread-safe.
• Because of its synchronized nature, StringBuffer might be slower in performance compared to StringBuilder.

StringBuilder:
• StringBuilder is not synchronized, making it faster in single-threaded scenarios. 
• Because of its unsynchronized nature, StringBuilder is faster in performance compared to StringBuffer.

36. What’s the difference between IS-A and HAS-A relationship?

In summary, “IS-A” represents inheritance, where a class is derived from another class, while “HAS-A” represents composition, where a class contains another class as a part of its structure.

37. What is Iterators?

Iterator allows going through a collection (such as lists, sets, or maps) in a sequential manner, enabling you to access each element of the collection one by one without needing to know their internal details. The iterator provides methods like hasNext() to check if there’s more to see, next() to move to the next element, and remove() to optionally remove elements.

38. What is the difference between Iterators and Loops?

Loops
offer more control and flexibility in going through collections, but may require more code for complex logic and can be less safe when modifying collections.
Iterators, on the other hand, provide a standardized and safer approach to iterating over collections, ensuring forward going through and enhancing readability, particularly for complex data structures or when modification is involved, but with less control compared to loops.


39. What is the difference between implicit casting and explicit casting?

Casting refers to the process of converting a value from one data type to another. There are two main types of casting:
Implicit casting occurs automatically when converting a smaller data type to a larger one.
Explicit casting requires manual intervention and is used to convert a larger data type to a smaller one.

40. What is the difference between Autoboxing and Unboxing?

Casting and auto boxing/unboxing are related but different concepts in Java. 
Auto boxing is the automatic conversion of a primitive data type to its corresponding wrapper class object. Example: Converting an int primitive to an Integer object.
Unboxing is the automatic conversion of a wrapper class object to its corresponding primitive data type.Example: Converting an Integer object to an int primitive.

41.What is the difference between pass-by-value and pass-by-reference?

The difference between pass-by-value and pass-by-reference in Java lies in how arguments are passed to methods:

  • In pass-by-value, a copy of the actual value of the argument is passed to the method.
  • Any changes made to the parameter inside the method do not affect the original value of the argument outside the method.
  • Java uses pass-by-value for all primitive data types (such as int, double, char, etc.).
  • In pass-by-reference, a reference to the memory location of the argument is passed to the method.
  • Any changes made to the parameter inside the method directly affect the original value of the argument outside the method.
  • Java does not support pass-by-reference directly for objects; instead, it uses pass-by-value for object references. This means that the reference to the object is passed by value, not the actual object itself.

42. Name me the most common 5 Exceptions in Java?

NullPointerException: This exception occurs when you try to access or call methods on an object reference that is null, meaning it doesn’t point to any object in memory.
ArrayIndexOutOfBoundsException: This exception occurs when you try to access an index of an array that is outside the valid range. For example, accessing an element at index -1 or beyond the length of the array. ArithmeticException: This exception occurs when an arithmetic operation is attempted but cannot be performed, such as dividing by zero.
ClassNotFoundException: This exception occurs when the JVM tries to load a class at runtime using Class.forName() method but the specified class is not found in the classpath.
FileNotFoundException: This exception occurs when attempting to access a file that does not exist or cannot be found by the JVM.

43. What is the difference between == and .equals() ?

The == operator checks for reference equality, while the .equals() method (typically overridden from Object class) checks for content equality.

44.What is the difference between “” and null ?

“” represents an empty string literal. It is a valid instance of the String class, meaning it is an object. While it contains no characters, it occupies memory space and is considered a valid string object. Operations like concatenation, length checking, and accessing its methods are valid and won’t result in exceptions.

null is a special literal in Java that represents the absence of an instance or a reference to an object. It indicates that a reference variable does not refer to any object. Using null typically means the absence of a value or the uninitialized state of an object reference. Operations like calling methods on a null reference will result in a NullPointerException.

45. What is the difference between static block and instance block?

Static blocks initialize static variables and are executed once when the class is loaded into memory. Static blocks use the static keyword.
Instance blocks initialize instance variables and are executed each time an object of the class is created. stance blocks are enclosed within braces {} without any keyword.

46. What is the sequence of execution of static block, instance block, static variable, constructor and method?

  1. Static Block (if any)
  2. Static Variable Initialization
  3. Instance Block (for each object creation)
  4. Constructor
  5. Method Execution
 

 

47. What is the difference between List and ArrayList?

List is an interface that defines the behavior of ordered collections, while ArrayList is one of the implementations of that interface, utilizing a dynamically resizable array to store its elements.

48. What is the significance of the Map interface in Java Collections Framework?

Map interface represents a mapping between keys and values, where each key is associated with exactly one value. It provides methods to add, remove, and retrieve elements based on keys.
Common implementations of Map include HashMap, TreeMap, LinkedHashMap, etc. Maps are widely used in various scenarios such as caching, data storage, and building data structures like hash tables.

49. 
What is the difference between checked and unchecked exceptions in Java?

Checked exceptions are checked at compile-time, meaning the compiler requires you to handle them using try-catch or declare them in the method signature using throws. Examples of checked exceptions include IOException, SQLException, etc.
Unchecked exceptions (also known as runtime exceptions) are not checked at compile-time, and the compiler does not force you to handle them explicitly. Examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, etc. 

50. What are the the super and this keywords in Java?

super: The super keyword in Java is used to refer to the superclass of the current object instance. It is primarily used to access superclass members (fields and methods) that are hidden or overridden by the subclass.
super() is also used to call the superclass constructor from the subclass constructor. When used without parameters, super() invokes the superclass’s no-argument constructor. When used with parameters, it calls a specific superclass constructor. If super() or super(parameters) is not explicitly written in a constructor, Java automatically inserts a call to the no-argument constructor of the superclass.
this: The this keyword in Java is used to refer to the current object instance within its own class. It is primarily used to differentiate between instance variables and parameters with the same name, or to invoke constructors from other constructors within the same class.
this() is used to invoke one constructor from another constructor within the same class. It must be the first statement in the constructor. this can also be used to pass the current object as a parameter to other methods or constructors, or to return the current object from a method.

administrator

Leave A Comment