Hello friends, in this article we have compiled a list of the top 100 core Java interview questions. These questions are designed for both fresher and experienced professionals of software development as well as automation testing profiles. We will start with the questions related to the basics of Java and then move to more complex interview questions.
Ques. 1. What is Java?
Ans. Java is an object-oriented programming language, developed in 1995 by Sun Microsystems. It is known for its “write once, run anywhere” capability, meaning code can run on any device with a Java Virtual Machine (JVM). It’s widely used for web development, Android apps, and enterprise software due to its reliability and ease of use.
Ques. 2. What are some features of Java?
Ans. Some of the major features of Java are-
- Platform Independent – Runs on any device with a JVM (Java Virtual Machine).
- Object-Oriented – Follows OOP concepts like classes, objects, and inheritance.
- Simple & Easy to Learn – Clean syntax similar to C++ but without complex features.
- Secure – Built-in safety features like bytecode verification (JVM verifies the bytecode before running it to ensure there is no malware, illegal memory access, etc) and no pointers.
- Multithreading Support – Allows running multiple tasks simultaneously for better performance.
- High Performance – Uses Just-In-Time (JIT) compilation for faster execution.
- Robust & Reliable – Strong memory management and exception handling.
- Distributed Computing – Supports networking and remote method invocation (RMI).
- Automatic Memory Management – Garbage collector removes unused objects.
- Rich Standard Library – Provides pre-built tools for I/O, networking, and data structures.
Ques. 4. What is JDK?
Ans. JDK means Java Development Kit. JDK is a complete software package used to develop, compile, and run Java applications. It includes everything a developer needs-
- JRE (Java Runtime Environment) – To execute Java programs (contains JVM + libraries).
- Java Compiler (
javac
) – Converts.java
files into.class
(bytecode). - Development Tools – Debugger (
jdb
), documentation generator (javadoc
), packaging tool (jar
), etc.

Ques. 5. What is Javac?
Ans. javac
(Java Compiler) is the official Java compiler that converts human-readable Java code (.java
files) into bytecode (.class
files) that the JVM (Java Virtual Machine) can execute.
- Platform Independence – Bytecode works on any device with a JVM (Write Once, Run Anywhere).
- Compilation Step –
javac HelloWorld.java
→ CreatesHelloWorld.class
(bytecode). - Part of JDK – Only available if you install the Java Development Kit (JDK).
- Error Checking – Detects syntax errors before runtime (e.g., missing semicolons, typos).
Ques. 6. What is JRE?
Ans. Java Runtime Environment JRE is a software package that lets you run Java programs (but not develop them). It includes-
- JVM (Java Virtual Machine) – Executes Java bytecode.
- Core Libraries – Pre-built code (e.g., for I/O, math, collections) that programs need to work.
- Other Tools – Like the
java
launcher (to start programs).
Bytecode Verification in JRE
Before the JVM runs any bytecode (.class
files), the JRE performs bytecode verification, a security check to ensure-
- The code doesn’t harm your computer (e.g., no viruses or memory corruption).
- It follows Java’s rules (e.g., no fake data types or illegal memory access).
- It’s structurally correct (e.g., no missing/weird instructions).
If a hacker modifies a .class
file to sneak in malicious code, the JRE’s verifier rejects it before it runs.
Ques. 7. What is JVM?
Ans. The Java Virtual Machine (JVM) is a software engine that runs Java programs by converting Java bytecode into machine code that your computer can understand. It allows Java applications to be platform-independent, meaning the same code can run on Windows, Linux, or macOS without modification. The JVM also handles memory management, security, and performance optimization through features like Garbage Collection and Just-In-Time (JIT) compilation.
Key Features of JVM-
- Platform Independence
JVM makes Java “write once, run anywhere” possible.
Java code runs on any OS where JVM is installed. - Class Loader
Loads.class
files (compiled Java code) into memory.
Handles loading from local files, JARs, or remote sources. - Bytecode Verifier
Checks the loaded code for security and structure.
Ensures no harmful or invalid code runs. - Interpreter + JIT Compiler
Interpreter: Executes code line by line.
JIT (Just-In-Time) Compiler: Converts frequently used code into fast machine code for better performance. - Garbage Collector (GC)
Automatically manages memory by removing unused objects.
Prevents memory leaks and crashes. - Execution Engine
Runs the bytecode.
Communicates with the OS and hardware. - Java Runtime Environment (JRE)
Includes JVM + core libraries needed to run Java apps.
JVM is part of the JRE. - Security Manager
Controls access to files, network, etc., especially in web or enterprise environments.
Ques. 8. Why is Java considered platform-independent?
Ans. Java is called platform-independent, as the code compiled in Java can run on all OS irrespective of on which it was created. The code created in Java is compiled into an intermediate language called the Bytecode, which is understood by the JVM and converted into a native machine-specific language based on which OS it is being run.
The programs of other languages like C are saved in .exe format and are compiled directly into machine-specific language according to the OS being used. This means a code compiled on a Microsoft OS cannot run on a Linux OS.
However, the code in Java is first converted into an intermediate Bytecode language; therefore, if the OS supports the JVM, the code can be executed easily (remember, Java is platform-independent, but the JVM is not).
Ques. 9. What do you mean by JIT?
Ans. JIT (Just-In-Time) is a feature of the JVM that makes Java programs run faster by converting bytecode into machine code while the program is running.
How JIT Works?
- First Run – JVM interprets bytecode (slow).
- Hotspot Detection – JIT identifies frequently used code (e.g., loops, methods).
- Compilation – Converts that bytecode into machine-specific code (fast).
- Execution – Reuses the compiled machine code for future calls (no reinterpretation needed).
Example–
for (int i = 0; i < 1000; i++) {
System.out.println("Hello"); // JIT compiles this loop after a few runs
}
With JIT → Converts loop to machine code → runs at CPU speed.
Without JIT → JVM reinterprets the loop 1000 times (slow).
Ques. 10. What is a classloader?
Ans. The ClassLoader is a core part of the JVM (Java Virtual Machine) that loads Java classes into memory when they’re needed for execution. It’s responsible for finding and loading .class
files (bytecode) so the JVM can run them.
How ClassLoader Works?
- Loading – Reads the
.class
file (from disk, network, etc.) into memory. - Linking–
Verification – Checks if the bytecode is valid/safe (no corruption or security violations).
Preparation – Allocates memory for static variables and default values.
Resolution – Converts symbolic references (like variable names) into direct memory addresses. - Initialization – Executes static blocks (
static { ... }
) and assigns real values to static variables.
TheClassLoader
class is part of thejava.lang
package, making it a core component of Java’s standard library.
Ques. 11. What are the different access modifiers in Java?
Ans. Access modifier is a frequently asked core Java interview question.
An access modifier defines the accessibility to a particular class, method, constructor, or field. There are 4 access modifiers in Java based on the type of access they provide. These are-
- Default – This modifier is applicable if no other modifier is specified. This means that the access level is within the current package and cannot be accessed outside the package.
- Private – Access is within the current class and not outside of it.
- Protected – The access within the current package unless a child class is created outside the package. It can be accessed through a child’s class.
- Public – As the name suggests, there is no restriction. It can be accessed from within the class/package or outside the class/package.
Ques. 12. What is OOPS?
Ans. OOPS stands for Object-Oriented Programming System. It is a programming paradigm (style) that organizes code into “objects” representing real-world entities.
Ques. 13. What are the four pillars of OOPS?
Ans. Abstraction, encapsulation, polymorphism, and inheritance are the 4 pillars of OOPS.
1. Encapsulation
Bundles data and methods into a class, restricting direct access to protect data integrity. Uses access modifiers like private/public.
2. Inheritance
Allows classes to inherit properties and behaviors from parent classes, enabling code reusability and hierarchy.
3. Polymorphism
Polymorphism in Java means the ability of an object to take many forms—specifically, the ability to use a single method name to represent different underlying types or behaviors.
4. Abstraction
Hides complex implementation details while exposing only essential features through interfaces/abstract classes.
Ques. 14. What is an Object in Java?
Ans. An Object is an instance of a class, created to store data and methods. An object has its identity, state/attribute, and behavior. For example, in a class named Animals, an object dog is created. It has attributes like its breed, color, etc. It has behavior barks, runs, eats, etc.
Ques. 15. Explain classes in Java.
Ans. A class is a blueprint or template for creating objects. It defines the properties (variables) and behaviors (methods) that the objects created from it will have.
public class Car {
String color;
void drive() {
System.out.println("Car is driving");
}
}
Here, Car
is a class. You can create objects like-
Car myCar = new Car();
myCar.color = "Red";
myCar.drive();
Ques. 16. Can we have an empty filename in Java?
Ans. Yes, a Java file can be kept empty. Just save it by ‘.java’ and compile by entering the command Javac ‘.java’.
Ques. 17. What are constructors in Java?
Ans. A constructor is a method that is invoked when a class is instantiated and memory is allocated to the instance. When the new keyword is used to create an object, the constructor is called. The constructor should have the same name as the class being instantiated.
Ques. 18. What are the different types of constructors?
Ans. There are two types of constructors-
- Default constructors – These constructors are created by the compiler itself when no constructor is defined in the program. These constructors have no parameters, so the instances are initialized with default values.
- Parameterized constructor – These constructors are used to pass certain values/arguments to the objects created.
Ques. 19. Can a constructor be overloaded?
Ans. Yes, a constructor can be overloaded. This works the similar way the overloading methods work, the number of arguments or the data type of the parameters are changed to overload.
Ques. 20. Can constructors be inherited?
Ans. No, a constructor cannot be inherited. However, a constructor of a superclass can be invoked by the subclass.
Ques. 21. What is the difference between constructors and methods?
Ans. Constructors-
- It is invoked when a class is instantiated to initialize the state of the object.
- They are a type of special method and don’t have a return type.
- The compiler provides a default constructor if one is not mentioned in the program.
- The name of the constructor must be the same as the class ibeing nstantiated.
Methods-
- The behavior of the object is reflected by the method.
- A method has a return type.
- No default method is created by the compiler if none is mentioned in the program
- A method cannot have the same name as the class, unless it is a constructor.
Ques. 22. What is a wrapper class in Java?
Ans. To include primitive data types like int, boolean, char, etc. in the family of objects (as Java is object-oriented) wrapper class is used. For every primitive data type, we have a wrapper class.
For example – Integer for int, Float – float, Character for char, etc.
Ques. 23. What is a package in Java? What are its advantages?
Ans. A package in Java is a type of directory or folder that contains all the related classes, sub-classes, and interfaces. There are 2 types of packages in Java, built-in and user-defined. One such built-in package is ‘java.lang’ imports the lang package, which has all the fundamental classes required to create a basic program.
Ques. 24. What are static, local, and instance variables?
Ans. In Java, variables are categorized based on their scope, lifetime, and where they are declared. Here’s a clear breakdown of static, instance, and local variables with examples-
1. Instance Variables (Non-Static Fields)
- Declaration: Inside a class but outside any method/block, without
static
. - Scope: Belongs to an object (instance) of the class.
- Lifetime: Exists as long as the object exists.
- Default Value: Automatically initialized (e.g.,
0
,null
,false
). - Access: Requires an object of the class.
Example-
class Car {
String model; // Instance variable (unique per object)
int year; // Instance variable
Car(String model, int year) {
this.model = model;
this.year = year;
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Tesla", 2023); // car1.model = "Tesla"
Car car2 = new Car("Toyota", 2022); // car2.model = "Toyota"
}
}
2. Static Variables (Class Variables)
- Declaration: Inside a class with the
static
keyword. - Scope: Belongs to the class (shared across all objects).
- Lifetime: Exists for the entire program.
- Default Value: Initialized automatically (like instance variables).
- Access: Via class name (no object needed).
Example-
class Car {
static int wheels = 4; // Static variable (shared by all cars)
String model; // Instance variable
}
public class Main {
public static void main(String[] args) {
System.out.println(Car.wheels); // Output: 4 (no object needed)
Car car1 = new Car();
Car car2 = new Car();
System.out.println(car1.wheels); // Also works (but discouraged)
}
}
3. Local Variables
- Declaration: Inside a method, constructor, or block.
- Scope: Limited to the block where it’s declared.
- Lifetime: Exists only while the block executes.
- Default Value: Not initialized (must be assigned manually).
- Access: Only within the declared block.
Example-
Ques. 25. What is the static keyword in Java?
Ans. The concept of static keywords is one of the commonly asked core Java interview questions.
The static keyword associated with any method, variable, or nested class means it belongs to the class and not any instance of the class.
Ques. 26. What do you mean by a static method?
Ans. A static method is a method for which there is no requirement to create an object. They can be invoked without creating an object. Therefore, they belong to the class and not to the instances of the class.
Ques. 27. What is an instance method?
Ans. An instance method requires an object of the class to call or invoke it. Therefore, they belong to the object of the class and not the class itself.
Ques 28. What is a string in Java?
Ans. A string is a sequence of characters and comes under non-primitive data types. A string is a class in Java and extends the Object class of Java. It is used to manipulate strings in the program through various methods included in it. Syntax-
String s= “name”; or String s = new String();
Ques. 29. What is a string constant/literal pool?
Ans. String constant pool is a special memory location that stores string objects. It is a place in the heap memory that stores string literal values.
Ques. 30. What are the different classes to create strings? Differentiate between them.
Ans. There are 3 classes to create strings-
- String – Strings created through the string class are immutable i.e., they cannot be altered once created.
- String Builder – Strings created through this are mutable (changeable) and preferable when used from a single thread.
- String Buffer – Strings created through this are mutable, i.e. the values can be changed, and also it is thread-safe. This means it can be accessed by multiple threads and yet will remain safe.
Ques. 31. Why are strings immutable in Java?
Ans. This is one of the most frequently asked core Java interview questions. Immutable means something that cannot be modified. So, when we say that String is immutable in Java. It means String objects cannot be modified once created. In case we try to change the value of the String, then a new object will get created.
Now, let’s see the benefit of making String immutable. Strings are immutable in Java because it uses the concept of string literal or string constant pool.
If a new String object is created with the value “ArtOfTesting” then the same will be placed in a Java heap memory called String pool. Now, whenever new String literals are created with the value – “ArtOfTesting”, then instead of creating multiple objects, each object will point to the same value (i.e., “ArtOfTesting”) in the String pool.
This saves a lot of memory. If the String value in Java is allowed to be modified, then the concept of the String pool will not hold. This is because changing the value of one object can update the value of other objects also, which may not be desired.
Ques. 32. Why is string final in Java?
Ans. A String is made final to maintain its property of immutability, thus saving it from any changes.
Ques. 33. Difference between == and .equals() method in Java.
Ans. == operator is used to compare two strings when string variables are pointing to the same memory location(address reference). The .equals() method is used to check the object values(content comparison).
Ques. 34. What is inheritance?
Ans. Inheritance is one of the concepts of OOPS where one class acquires/inherits the properties of the parent class. This ensures the reusability of methods and fields created in the parent class into the new classes created in the program. Syntax-
//A is sub-class and B is parent class
Class A extends Class B{
//code with methods and fields
}
Ques. 35. What is polymorphism?
Ans. Polymorphism in Java is the ability of an object to take on multiple forms. It allows methods to be used in different ways based on the object calling them, even if they share the same name. There are two types:
Compile-time (Static) Polymorphism: Achieved through method overloading or operator overloading. Methods in the same class have the same name but different parameters (e.g., different numbers or types of arguments).
class Example {
void display(int a) {
System.out.println("Integer: " + a);
}
void display(String s) {
System.out.println("String: " + s);
}
}
Run-time (Dynamic) Polymorphism: Achieved through method overriding using inheritance and interfaces. A parent class reference can point to a child class object, and the actual method called is determined at runtime based on the object’s type.
Using inheritance-
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
Animal myDog = new Dog();
myDog.sound(); // Outputs "Bark"
Key enablers include inheritance, interfaces, and the use of the @Override annotation for clarity. Polymorphism promotes flexibility and reusability in code.
Using Interface-
// Interface
interface Animal {
void sound(); // Abstract method
}
// Class implementing the interface
class Dog implements Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
// Another class implementing the same interface
class Cat implements Animal {
@Override
public void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
// Interface reference pointing to different objects
Animal myDog = new Dog();
Animal myCat = new Cat();
// Polymorphic behavior: method called depends on the object type
myDog.sound(); // Outputs: Dog barks
myCat.sound(); // Outputs: Cat meows
}
}
The Animal interface declares an abstract method sound(). Dog and Cat classes implement the Animal interface, providing their own versions of the sound() method. In the main method, the Animal interface reference (myDog, myCat) points to Dog and Cat objects, respectively. At runtime, the JVM determines the actual object type (Dog or Cat) and calls the appropriate sound() method, showcasing polymorphism.
Ques. 36. What is Abstraction?
Ans. Abstraction in Java is the process of hiding complex implementation details and exposing only the essential features of an object to the user. It simplifies interaction with objects by focusing on what an object does rather than how it does it. Abstraction is achieved in Java primarily through abstract classes and interfaces.
Key Concepts of Abstraction
Abstract Class:
- A class declared with the abstract keyword that cannot be instantiated directly.
- It can contain both abstract methods (without implementation) and concrete methods (with implementation).
- Subclasses must implement all abstract methods unless they are also abstract.
Interface:
- A fully abstract type that defines only method signatures (and possibly constants).
- Classes implement interfaces using the implements keyword and provide implementations for all methods.
- Supports multiple inheritance (a class can implement multiple interfaces).
Purpose:
- Reduces complexity by hiding internal details.
- Enhances modularity and maintainability.
- Enables polymorphism by allowing different implementations of the same method signature.
Ques. 37. What is encapsulation?
Ans. Encapsulation in Java is the mechanism of bundling data (fields) and methods that operate on that data into a single unit, typically a class, while restricting direct access to some of the object’s components. It is a fundamental principle of object-oriented programming that ensures data integrity and security by hiding the internal state of an object and exposing only necessary functionality through public methods.
Key Features of Encapsulation
- Data Hiding:
- Fields are declared private to prevent direct access from outside the class.
- Access to these fields is provided through public getter and setter methods, which can include validation logic.
- Controlled Access:
- Encapsulation allows the class to control how data is accessed or modified, ensuring consistency and preventing invalid states.
- Improved Maintainability:
- Internal implementation details can be changed without affecting code that uses the class, as long as the public interface remains consistent.
How Encapsulation Works
- Optionally, add logic in getters/setters to enforce rules or validation.
- Use private access modifiers for fields to restrict direct access.
- Provide public getter (to retrieve data) and setter (to modify data) methods to interact with private fields.
class Person {
// Private fields (data hiding)
private String name;
private int age;
// Public getter for name
public String getName() {
return name;
}
// Public setter for name with validation
public void setName(String name) {
if (name != null && !name.isEmpty()) {
this.name = name;
} else {
System.out.println("Invalid name");
}
}
// Public getter for age
public int getAge() {
return age;
}
// Public setter for age with validation
public void setAge(int age) {
if (age >= 0 && age <= 120) {
this.age = age;
} else {
System.out.println("Invalid age");
}
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
// Accessing and modifying data through setters
person.setName("Alice");
person.setAge(25);
// Retrieving data through getters
System.out.println("Name: " + person.getName()); // Outputs: Name: Alice
System.out.println("Age: " + person.getAge()); // Outputs: Age: 25
// Attempting invalid data
person.setAge(-5); // Outputs: Invalid age
person.setName(""); // Outputs: Invalid name
}
}
Ques. 38. What is the main difference between encapsulation and abstraction?
Ans. The major difference between encapsulation and abstraction is that abstraction is used to hide unwanted or unnecessary information. This can be done by using abstract classes and interfaces.
Encapsulation is used to hide data as a single block with all the variables and methods inside it. The data can be accessed through getter and setter methods.
Ques. 39. What do you mean by the interface in Java?
Ans. An interface is a collection of abstract methods in Java. A class can implement the interface by using the ‘interface’ keyword, which will result in inheriting all the abstract methods present in the interface. The interface provides complete(100%) data hiding.
Interfaces in Java can have variables, but they are implicitly public, static, and final (i.e., constants). This means they cannot be changed once initialized and are shared across all classes that implement the interface.
Ques. 40. What are the different types of inheritance in Java?
Ans. ava supports several types of inheritance, though it restricts certain forms to avoid complexity. Below are the types of inheritance in Java, with brief explanations and examples.
1. Single Inheritance
- A subclass inherits from one superclass.
- Simplest form of inheritance, widely used.
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
// Dog inherits eat() from Animal
2. Multilevel Inheritance
- A class inherits from a superclass, which itself inherits from another superclass, forming a chain.
- Represents a hierarchy of classes.
- Example:
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Mammal extends Animal {
void walk() {
System.out.println("Mammal walks");
}
}
class Dog extends Mammal {
void bark() {
System.out.println("Dog barks");
}
}
// Dog inherits from Mammal, which inherits from Animal
Content
3. Hierarchical Inheritance
- Multiple subclasses inherit from a single superclass.
- Useful when a common set of features is shared among different classes.
- Example:
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat meows");
}
}
// Both Dog and Cat inherit from Animal
4. Multiple Inheritance (via Interfaces)
- Java does not allow a class to inherit from multiple classes (to avoid issues like the “diamond problem”).
- However, a class can implement multiple interfaces, achieving multiple inheritance indirectly.
- Interfaces define method signatures, and the class provides the implementation.
- Example:
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable {
@Override
public void fly() {
System.out.println("Duck flies");
}
@Override
public void swim() {
System.out.println("Duck swims");
}
}
// Duck inherits behaviors from both Flyable and Swimmable
5. Hybrid Inheritance (via Interfaces)
- A combination of two or more types of inheritance (e.g., hierarchical and multiple inheritance).
- Achieved using interfaces, as Java does not support multiple class inheritance.
- Example:
interface Animal {
void eat();
}
interface Pet {
void play();
}
class Mammal implements Animal {
@Override
public void eat() {
System.out.println("Mammal eats");
}
}
class Dog extends Mammal implements Pet {
@Override
public void play() {
System.out.println("Dog plays");
}
}
// Dog inherits from Mammal (hierarchical) and implements Pet (multiple via interface)
Ques. 41. What are method overloading and method overriding?
Ans. Both methods are involved when the code is based on polymorphism. Method overloading is static polymorphism, and method overriding is dynamic polymorphism.
Method overloading-
Method overloading is a part of polymorphism where a class has multiple methods with the same name but different arguments. Conditions for creating method overriding are-
- Methods should have the same name.
- Arguments passed should be different (number, type, sequence).
- Methods should belong to the same class.
Example-
Class Overload{
void show(){
System.out.println("sum");
}
void show(int a){
System.out.println("multiply");
}
public static void main(String args[]){
Overload t = new overload();
t.show();
t.show(10);
}
}
Method overriding–
Creating and implementing a method with the same name in a subclass as the parent class is called method overriding.
- The methods’ name should be the same
- Arguments passed should be the same(number, type, sequence)
- Methods should belong to different classes
- Creating IS-A relationship.
Example-
Class Example1{
void show(){
System.out.println("method1");
}
}
Class Example2 extends Example1{
void show(){
System.out.println("method2");
}
public static void main(String args[]){
Example1 a= new Example1();
a.show(); //method1
Example2 b= new Example2();
b.show(); //method2
}
}
Ques. 42. What are the base class and derived class?
Ans. This is a concept of inheritance in OOPs. A base class is also called the parent class, from which the other classes derive. A derived class, or the child class inherits properties or functions from the base class.
Ques. 43. What are the limitations of inheritance?
Ans. The limitations of inheritance are-
- The parent and the child classes become tightly coupled.
- Needs proper and careful implementation due to multiple closely associated classes.
- Increases execution time due to jumping between the parent and child classes.
- Modifications have to be made to both parent’s and the child’s classes.
Ques. 44. Can instances of an abstract class be created?
Ans. No, abstract classes cannot be instantiated. This is because of the abstract methods, which are empty/without a body. They act as a base for subclasses. They have to be extended and built upon.
Ques. 45. Why does Java not support multiple inheritance?
Ans. Implementing multiple inheritance creates complexities like the diamond problem. The diamond problem occurs when ambiguity occurs between two classes that will be overridden. For example, class A has subclasses class B and class C. B & C are superclasses to class D. A method in A gets overridden by both B & C. Then, from which class will D inherit this method? Such complexity is called a diamond problem.
Ques. 46. How can we achieve multiple inheritance in Java?
Ans. Java supports multiple inheritance through interfaces. A class can implement multiple interfaces, which define method signatures without implementation (or with default methods since Java 8). This avoids ambiguity since the implementing class provides the concrete implementation.
// Superclass
class Vehicle {
String brand;
Vehicle(String brand) {
this.brand = brand;
}
void start() {
System.out.println(brand + " vehicle is starting");
}
}
// Subclass
class Car extends Vehicle {
int wheels;
Car(String brand, int wheels) {
super(brand); // Call superclass constructor
this.wheels = wheels;
}
@Override
void start() {
System.out.println(brand + " car with " + wheels + " wheels is starting");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle("Generic");
Car car = new Car("Toyota", 4);
vehicle.start(); // Outputs: Generic vehicle is starting
car.start(); // Outputs: Toyota car with 4 wheels is starting
// Polymorphism: Vehicle reference, Car object
Vehicle polyCar = new Car("Honda", 4);
polyCar.start(); // Outputs: Honda car with 4 wheels is starting
}
}
Code Explanation:
- The Vehicle class is the superclass with a brand field and a start() method.
- The Car class extends Vehicle, inheriting its brand field and start() method. It adds a wheels field and overrides start() to provide a specific implementation.
- In the main method:
- A Vehicle object calls the superclass’s start().
- A Car object calls the overridden start().
- A Vehicle reference pointing to a Car object (polyCar) demonstrates polymorphism, invoking Car’s start() method at runtime due to dynamic method dispatch.
- The super keyword in Car’s constructor calls the superclass constructor to initialize brand.
Why No Multiple Class Inheritance? If Car could extend both Vehicle and, say, Machine, and both had a start() method, it would be unclear which start() to call. Java avoids this by restricting classes to single inheritance. Instead, Car can implement multiple interfaces (e.g., Drivable, Insurable) to inherit multiple behaviors without ambiguity, as the Car class provides the implementation.
Ques. 47. What is aggregation in Java?
Ans. Aggregation in Java is a special type of association between two classes where one class (the container) contains a reference to another class (the contained), representing a “has-a” relationship. It is a form of composition where the contained object can exist independently of the container, meaning the lifecycle of the contained object is not tied to the container. Aggregation is a weaker relationship compared to composition, as it implies loose coupling.
Key Characteristics of Aggregation
“Has-A” Relationship:
- The container class “owns” or “has” an instance of the contained class.
- Example: A Car has an Engine, but the Engine can exist independently.
Loose Coupling:
- The contained object can be shared among multiple containers or exist on its own.
- Deleting the container does not necessarily destroy the contained object.
Unidirectional or Bidirectional:
- Typically unidirectional (e.g., Car references Engine), but can be bidirectional if both classes reference each other.
Implementation:
- Achieved by including a reference (or collection) to the contained class as a field in the container class.
- Often implemented using instance variables, lists, or other data structures.
// Contained class
class Student {
String name;
Student(String name) {
this.name = name;
}
void study() {
System.out.println(name + " is studying");
}
}
// Container class
class School {
String schoolName;
Student student; // Aggregation: School "has-a" Student
School(String schoolName, Student student) {
this.schoolName = schoolName;
this.student = student;
}
void conductClass() {
System.out.println(schoolName + " is holding a class");
student.study();
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice");
School school = new School("Greenwood High", student);
school.conductClass(); // Outputs: Greenwood High is holding a class
// Alice is studying
// Student exists independently
student.study(); // Outputs: Alice is studying
}
}
Explanation
- Aggregation: School has a Student (a “has-a” relationship), implemented via a Student reference in School.
- Independence: The Student object exists independently and can be used outside the School (e.g., student.study()).
- Loose Coupling: The Student can be shared or exist without the School, unlike composition where the contained object’s lifecycle is tied to the container.
Ques. 48. What is composition?
Ans. Composition is a strong “has-a” relationship in Java where a class (container) contains another class (contained), and the contained object’s lifecycle is tied to the container. If the container is destroyed, the contained object is also destroyed, indicating tight coupling.
// Contained class
class Engine {
String type;
Engine(String type) {
this.type = type;
}
void run() {
System.out.println(type + " engine is running");
}
}
// Container class
class Car {
String brand;
Engine engine; // Composition: Car "has-a" Engine
Car(String brand, String engineType) {
this.brand = brand;
this.engine = new Engine(engineType); // Engine created within Car
}
void drive() {
System.out.println(brand + " car is driving");
engine.run();
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", "V6");
car.drive(); // Outputs: Toyota car is driving
// V6 engine is running
}
}
Explanation
- Composition: Car contains an Engine, created within the Car constructor, representing a “has-a” relationship.
- Tight Coupling: The Engine is tied to the Car’s lifecycle. If the Car is destroyed (e.g., set to null), the Engine is also eligible for garbage collection.
- Contrast with Aggregation: Unlike aggregation, the Engine cannot exist independently outside the Car in this design, emphasizing stronger ownership.
Ques. 49. Can an abstract method exist without an abstract class?
Ans. No. If an abstract method is declared, an abstract class must exist. However, the reverse is not true.
Ques. 50. What are some advantages of OOPS?
Ans. The advantages of OOPS are-
1. Code maintenance – It helps in maintaining and modifying the code in the simplest way.
2. It helps in creating a clean, structured program or code.
3. Reusability – You can inherit the same methods in different classes by using inheritance.
4. It is helpful for security purposes as it helps in data hiding.
Also, check 👉 OOPS Interview Questions
Ques. 51. What is a super keyword?
Ans. The super keyword points to the instance of the super class or the parent class. It is majorly used to eliminate the confusion between the super and subclasses with same-name methods.
Ques. 52. What is this keyword?
Ans. The ‘this’ keyword is used to point to the current instance of a method or a constructor. The keyword is mostly used to eliminate the confusion of multiple methods of the same name existing in the program.
Ques. 53. What are the uses of the ‘this’ keyword?
Ans. The uses of the ‘this’ keyword are-
- Can be used as a reference variable to point to the instance of the current class.
- Can be used to invoke a constructor of the current class.
- It can be used to invoke the current class method.
- Can be passed as an argument in any method call.
Ques. 54. Can this keyword be used to refer to static members?
Ans. A static member is called without creating an instance, and this keyword is used to refer to the current class object. Therefore, the answer is no.
Ques. 55. What is constructor chaining?
Ans. In Java, constructor chaining is a technique where one constructor calls another constructor within the same class (using this()) or in a parent class (using super()) to reuse initialization logic, reduce code duplication, and ensure consistent object setup. It’s especially useful in classes with multiple constructors or inheritance hierarchies.
Within Same Class
class Student {
String name;
int age;
// Constructor 1: Basic
Student(String name) {
this.name = name;
this.age = 18; // Default age
}
// Constructor 2: Chained to Constructor 1
Student(String name, int age) {
this(name); // Calls Constructor 1
this.age = age; // Override default age
}
}
In Parent Class
class Person {
String name;
Person(String name) {
this.name = name;
}
}
class Student extends Person {
int rollNo;
Student(String name, int rollNo) {
super(name); // Calls Person's constructor
this.rollNo = rollNo;
}
}
Ques. 56. How is constructor chaining achieved? Why is it done?
Ans. Constructor chaining can be achieved in two ways-
- By using the ‘this’ keyword for the constructor in the same class.
- By using the ‘super’ keyword for the constructor in the base/parent class.
It is done so as to make code easier. This is because initialization is done only once at a single place and parameters are passed all over the constructors in the program.
Ques. 57. What is the init method in Java?
Ans. The init() method in Java is used for initialization purposes. It is an instance initialization method and is used by the JVM. Whenever a constructor is written in the program, the JVM considers its init method. This method is used by the compiler and therefore, not for the main program use purposes.
Ques. 58. What is the actual superclass in Java?
Ans. The Object class is the superclass of all the classes existing in Java.
Ques. 59. Why are pointers not supported in Java?
Ans. Pointers are used to point to the memory of another variable. By not supporting pointers Java achieves security by abstraction as the pointers directly lead to the memory of a variable.
Ques. 60. What is type casting in Java?
Ans. Type casting is a method to convert one data type to another data type in a program. This can be done manually by the developer or automatically by the compiler. Example-
int a = 45.66;
double d = (double)a;
Ques. 61. What are the different types of type casting?
Ans. There are two types of typecasting-
Narrow Typecasting is also called explicit casting or casting down. It is the method of converting a larger data type into a smaller data type. Like, double-> float-> long-> int-> char-> short-> byte.
Widening Typecasting is also called implicit casting or casting up. It is the method of converting a lower data type into a higher data type. Like, byte-> short-> char-> int-> long->float->double.
Ques. 62. What are some advantages of polymorphism?
Ans. Some advantages of polymorphism are-
- Helps in code reusability as the classes once written can be implemented again and again.
- Single variables can store multiple data types.
- Reduces coupling of classes, unlike inheritance.
Ques. 63. What are some advantages of abstraction?
Ans. Some advantages of abstraction are-
- Helps in creating a secured program as only required data is visible.
- Reduces the complexity of the program.
- Easier implementation of the software.
- Groups the related classes as siblings.
Ques. 64. Can we overload the main() method?
Ans. Yes, you can overload the main() method in Java. Method overloading allows defining multiple methods with the same name but different parameter lists (number, type, or order of parameters). The main() method, which serves as the entry point for a Java program (public static void main(String[] args)), can be overloaded like any other method, but only the standard main(String[] args) is called by the JVM to start the program.
Key Points
- Overloading main(): You can create additional main() methods with different parameters (e.g., main(int x), main(String s)), and they’ll work like regular methods.
- JVM Behavior: The JVM only looks for public static void main(String[] args) (or slight variations like String… args) to start execution. Overloaded main() methods won’t be called automatically.
- Use Case: Overloading main() is rare but can be useful for testing or providing alternative entry points within the same class.
public class MainOverload {
// Standard main method (JVM entry point)
public static void main(String[] args) {
System.out.println("Standard main: Program starts here!");
// Call overloaded main methods
main(5);
main("Hello");
}
// Overloaded main with int parameter
public static void main(int x) {
System.out.println("Overloaded main with int: " + x);
}
// Overloaded main with String parameter
public static void main(String s) {
System.out.println("Overloaded main with String: " + s);
}
}
Output
Standard main: Program starts here!
Overloaded main with int: 5
Overloaded main with String: Hello
How It Works?
- The JVM calls public static void main(String[] args) to start the program.
- Inside this main(), you can manually call overloaded versions (e.g., main(5) or main(“Hello”)) like any other method.
- Overloaded main() methods are treated as regular methods and don’t affect program startup.
Ques. 65. What is the final keyword in Java?
Ans. The final keyword added to any entity will declare it permanent. No changes can be made to the value once it is declared final. They can neither be overridden nor inherited. The final keyword is a non-access modifier.
Ques. 66. Can the main method be declared final?
Ans. Yes, the main() method can be declared final. Most methods are declared final so that they do not get overridden.
Ques. 67. Can we declare an interface as final?
Ans. The purpose of the interface is to provide methods that can be implemented. The final keyword abstains a method from being inherited or implemented. Therefore, an interface can never be final.
Ques. 68. What are static binding and dynamic binding?
Ans. Static Binding
- The compiler decides which method to call at compile-time based on the reference type (not the actual object). It’s fixed before the program runs.
- For private, final, or static methods (since they can’t be overridden).
- For method overloading (same method name, different parameters).
- The compiler looks at the declared type of the variable and picks the method matching the signature.
- Faster, as the method call is resolved early (no runtime checks).
Example
class Tester {
static void test(String tool) {
System.out.println("Testing with: " + tool);
}
static void test(String tool, int version) {
System.out.println("Testing with: " + tool + " v" + version);
}
}
public class Main {
public static void main(String[] args) {
Tester.test("Selenium"); // Calls test(String)
Tester.test("JMeter", 5); // Calls test(String, int)
}
}
Output
Testing with: Selenium
Testing with: JMeter v5
Dynamic Binding
- The JVM decides which method to call at runtime based on the actual object type (not the reference type). It’s flexible and supports polymorphism.
- For overridden methods in inheritance (non-private, non-final, non-static methods).
- Common in polymorphism where a parent reference points to a child object.
- The JVM checks the actual object’s class at runtime and calls the overridden method in that class.
- Slightly slower than static binding due to runtime lookup (but optimized by JIT compiler, as discussed earlier).
Example
class Tool {
void run() {
System.out.println("Running generic tool");
}
}
class Selenium extends Tool {
@Override
void run() {
System.out.println("Running Selenium automation");
}
}
public class Main {
public static void main(String[] args) {
Tool tool = new Selenium(); // Reference is Tool, object is Selenium
tool.run(); // Calls Selenium's run() at runtime
}
}
Output
Running Selenium automation
Ques. 69. What is the InstanceOf operator?
Ans. The instanceof operator in Java checks if an object is an instance of a specific class or interface (or their subclasses/subinterfaces) at runtime. It returns true if the object is of the specified type, false otherwise. It’s used for type checking before casting to avoid ClassCastException.
Syntax-
object instanceof ClassOrInterface
class Animal {}
class Dog extends Animal {}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
System.out.println(animal instanceof Dog); // true
System.out.println(animal instanceof Animal); // true
System.out.println(animal instanceof Object); // true
System.out.println(animal instanceof String); // false
}
}
Ques. 70. What do you mean by a multithreaded program?
Ans. A multithreaded program in Java runs multiple threads (smaller tasks) simultaneously within a single process, allowing parallel execution to improve performance and responsiveness. Each thread handles a separate task, like UI updates or data processing, sharing the same memory space.
Ques. 71. What is exception handling?
Ans. Exception handling in Java is a mechanism to manage runtime errors (exceptions) that disrupt normal program flow, ensuring the program doesn’t crash and can recover or fail gracefully. It uses specific keywords to catch, handle, or propagate exceptions.
Ques. 72. What are the types of exceptions in Java?
Ans. There are two types of exceptions: checked and unchecked.
Checked exceptions are handled during compile time. These include SQL exceptions, IO exceptions, etc.
The unchecked exceptions are those that cannot be checked or handled during compile-time and therefore throw an error during run-time. These include ArrayIndexOutOfBoundsException, NullPointerException, etc.
Ques. 73. Explain Java exception classes hierarchy.
Ans. The Java exception hierarchy starts from the throwable class which is a superclass. It is further divided into ‘exceptions’ and ‘errors’ classes. Errors are detected by the JVM. Some common errors are – OutOfMemoryError, unknown error, etc. Whereas exceptions are further bifurcated into checked and unchecked exceptions.
Ques. 74. What is the ‘finally’ block?
Ans. The ‘finally’ keyword is used with the statement of the program that has to run even if an exception is thrown or not, i.e., important codes. It is used with the try and catch blocks. There is always one final block in the end.
Ques. 75. Difference between throw and throws keyword.
Ans. In Java, throw and throws are used in exception handling but serve distinct purposes.
throw Keyword
- Inside a method body, to create and throw an exception object.
- Used to explicitly throw an exception in the code when a specific error condition occurs.
public void checkBrowser(String browser) {
if (!browser.equals("Chrome")) {
throw new IllegalArgumentException("Only Chrome is supported!");
}
System.out.println("Browser is valid.");
}
throws Keyword
- Declares that a method might throw one or more exceptions, warning callers to handle or propagate them.
- In the method signature, after the parameter list, listing exception types.
public void openFile(String path) throws IOException {
File file = new File(path);
if (!file.exists()) {
throw new IOException("File not found!");
}
// File processing code
}
Ques. 76. Can you catch multiple exceptions?
Ans. Yes, multiple exceptions can be caught in a program.
Ques. 77. What is the difference between an exception and an error?
Ans. Exceptions can be handled with the try-catch blocks but errors cause disruption in the flow of the program and cannot be fixed. Errors occur during the run time of the program. Most of the unchecked exceptions are errors only.
Ques. 78. What do you mean by OutOfMemoryError?
Ans. When the JVM runs out of heap memory, it throws an error called OutOfMemoryError.
Ques. 79. Can you write a custom exception in Java?
Ans. Yes, we can write custom exceptions by creating a whole new class that ends with the name ‘Exception’.
Ques. 80. What are some advantages of exception handling in Java?
Ans. The advantages of exception handling are-
- Separates the error-handling codes from the main program code.
- Grouping the errors thus helps in solving them more quickly.
- Maintains the normal flow of the program.
Ques. 81. How does exception handling work in Java?
Ans. Exception handling in Java is a powerful mechanism that allows developers to manage runtime errors gracefully. Here’s how the process works:
The Exception Handling Process-
- Exception Object Creation
- When an error occurs during program execution, Java creates an exception object
- This object contains detailed information about the error, including:
- Error type
- Error message
- Stack trace (sequence of method calls leading to the error)
- Call Stack Propagation
- The exception is propagated up through the call stack (the hierarchy of method calls)
- Java searches backward through the call stack to find an appropriate exception handler
- Handler Search
- The runtime system examines each method in the call stack sequentially
- It looks for code that can handle the specific type of exception that occurred
- The search starts from the method where the error occurred and moves outward
- Handler Execution
- When an appropriate exception handler is found, it’s executed
- The handler can:
- Log the error
- Display a user-friendly message
- Attempt recovery
- Perform cleanup operations
- If no handler is found, the program terminates
Ques. 82. Explain 5 keywords used in exception handling.
Ans. Try – Exception is handled by writing the code inside the try block that might throw an exception.
- Catch – The exception handling code is written in the catch block.
- Throw – It is used by the user to create an exception if the code does not run in the desired way.
- Throws – When we are aware of the checked exceptions and let the caller program know about those, the throws keyword is used before that exception.
- Finally – This block always gets executed even if an exception is thrown. It is used with the try-catch blocks.
Ques. 83. What is the chained exception?
Ans. When one exception explains the cause of the previous exception, it is called a chained exception. For example, if you divide a number by zero, it will throw an Arithmetic exception. But the underlying cause is that it was an I/O exception, and the program needs to know that. This is a chained exception.
Ques. 84. What is a stack trace?
Ans. A stack trace is used to list all the methods and names of the classes that have been called or used till the time the exception occurred. The stack trace helps in debugging the code.
Ques. 85. Can a child class that is overridden throw an exception?
Ans. If the parent class does not throw any exception, it is unlikely that the child class will throw one. But an unchecked exception can be thrown by it during runtime, regardless of whether an exception is thrown by the base class or not.
Ques. 86. What is a nested class?
Ans. A class created inside another class or interface is a nested class. The method of nested classes is used to group similar classes together so that the code looks neat and is maintainable.
Ques. 87. What are some advantages of nested classes?
Ans. Advantages of nested class-
- Helps to maintain the program neat and readable
- Code optimization
- Creates a special relation among the nested classes, which gives access to the outer class members, including the private class.
Ques. 88. What is the interrupt() method in Java?
Ans. The interrupt() method in Java throws InterruptedException whenever a thread is in a sleep or waiting state. There are 3 ways in which a thread can be interrupted-
- public void interrupt()
- public static boolean interrupted()
- public boolean isInterrupted()
Ques. 89. What are the different ways in which strings can be compared?
Ans. We can compare strings in the following ways-
1. .equals() method
2. Using == operator
3. s.charAt() method
4. compareTo() method
5. .equalsIgnoreCase() method
6. compareToIgnoreCase() method
Ques. 90. What are identifiers in Java?
Ans. Identifiers in Java are names given to a class, method, package, variable, etc., to ensure they can be identified easily. However, you cannot name them in any random way. There are some rules to create identifiers. Such as-
- Spaces cannot be used
- Special symbols cannot be used except the underscore and the $ sign.
- Reserved keywords of Java cannot be used.
- Integer values can only be used after 1st character.
Ques. 91. What are the memory areas allocated by JVM?
Ans. There are 5 memory types in JVM-
- Heap – Memory allocation for objects.
- class(method) area – For each of the classes’ structures(methods, variables, etc.)
- Stack – Holds local variables, methods invoked, methods returned, and partial results.
- PC(program counter) – Holds the address of the current instruction being executed.
- Native method stack – Stores all the native methods used.
Ques. 92. What is synchronization in Java?
Ans. When multiple threads(instructions) try to access the same resource, errors are bound to happen. Using synchronized blocks in Java, you can control access to these multiple threads. This is called synchronization. These synchronized blocks can be identified by the synchronized keyword.
class Counter {
private int count = 0;
// Synchronized method
public synchronized void increment() {
count++; // thread-safe operation
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 100
Synchronization ensures thread safety by allowing only one thread at a time to access shared resources using the synchronized
keyword. In the example, two threads safely increment a counter to 2000 without conflicts. It prevents race conditions by locking the critical section.
Ques. 93. Does the order of specifiers matter while creating a method?
Ans. No, the order does not matter till every specifier is mentioned. Public static void is the same as a static public void.
Ques. 94. Do local variables have a default value?
Ans. No, default variables do not have a value until initialized. The same goes for primitives and object references.
Ques. 95. What are the restrictions on the static methods?
Ans. The different restrictions in the static method are-
1. A static method cannot call a non-static method directly nor use a non-static data member.
2. This and super keywords cannot be used inside a static method.
Ques. 96. Can a program be run without the main method?
Ans. Yes, it is possible by using a static block.
public class WithoutMain {
static {
System.out.println("Program runs without main()!");
System.exit(0); // Required to prevent JVM from searching for main()
}
}
- Static blocks execute when the class loads.
System.exit(0)
prevents the JVM from looking formain()
.
Note: From Java 7 onwards, the JVM enforces the main()
method.
Ques. 97. What is the difference between Array and ArrayList?
Ans. Array-
1. It is a dynamic object and holds similar values.
2. It is static in size, meaning the size cannot be manipulated once created.
3. Can store both objects and primitives.
4. Multidimensional.
ArrayList-
1. It is a class of the Java collections framework and comes under Java.util package.
2. It is dynamic in size. Therefore, it can be resized according to need.
3. Cannot store primitives.
4. It is always of a single dimension.
Ques. 98. What is a list in Java?
Ans. The list is an interface in Java in which objects can be stored in an ordered way(indexed), and duplicate and null values can also be stored. ArrayList, Linked List, vector, and stack are implementation classes of the List.
Ques. 99. What is the Collection interface in Java?
Ans. It is a framework that acts as a base to store and manipulate groups of objects. Classes like ArrayList, LinkedList, Vector, and interfaces like queue, list, and set come under it.
Ques. 100. What is a hash map?
Ans. Hashmap is an implementation of a map interface. The data is stored in pairs in the form of a key, value. The key acts as an index to another object(value). The objects stored can be retrieved in the shortest time (O(1)) if the key is known.
This article on core Java interview questions is shared by Kanika Rawat. She is a tech enthusiast and has a keen interest in coding.
please next time give me the examples
Try to add basic java programs also for better practise .
Implicit and explicit casting is wrong
Implicit casting is also called as widening is actual answer.
Ques.61. What are the different types of type casting?
The answer to the above question is wrong, please review it.
Ques.61. What are the different types of type casting?
Expected:- Narrow Typecasting is also called Explicit casting or casting down,
and the given example is also wrong.
Thanks, must have been a typo. Corrected now.