Java Basic Interview Questions – 2025 Updated

Basic Java Interview Questions

Java Basic Interview Questions. Java has been one of the most popular programming languages for decades, making it essential for software engineers and aspiring developers to master. If you are preparing for a Java interview, especially for entry-level or junior roles, understanding the basics is crucial.

In this article, we’ll cover the most commonly searched Java Basic Interview Questions, with clear, easy-to-understand answers to help you succeed in your next interview.

Top Java Basic Interview Questions

1. What is Java?

Answer:
Java is a high-level, object-oriented programming language that was first developed by Sun Microsystems in 1995, later acquired by Oracle Corporation. Known for its platform independence, Java uses the concept of “Write Once, Run Anywhere (WORA),” meaning that compiled Java code can run on any device that has a Java Virtual Machine (JVM). Java follows an object-oriented programming approach, focusing on concepts like classes, objects, inheritance, encapsulation, polymorphism, and abstraction. Its strong memory management, security features, and vast ecosystem make it a top choice for building web applications, Android apps, enterprise software, and large-scale systems.

2. What are the main features of Java?

Answer:
Java offers several key features that make it one of the most popular programming languages:

  • Platform Independent: Thanks to the JVM, Java applications can run on different operating systems without modification.
  • Object-Oriented: Everything in Java revolves around objects and classes.
  • Robust and Secure: Java has powerful memory management, garbage collection, and built-in security mechanisms.
  • Multithreading: Java supports multiple threads, allowing developers to create applications that perform several tasks simultaneously.
  • Portable: Java bytecode can be carried anywhere and executed by any JVM.
  • High Performance: Although not as fast as C/C++, Java performance is optimized by using the Just-In-Time (JIT) compiler.
  • Dynamic: Java supports dynamic loading of classes and libraries during runtime.

These features make Java suitable for both beginners and professional developers.

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

Answer:
These three components are often confusing for beginners, but understanding them is vital for Java developers:

  • JDK (Java Development Kit):
    JDK is the complete package for Java development. It contains JRE, compiler (javac), debugger, and tools required to write, compile, and debug Java programs.
  • JRE (Java Runtime Environment):
    JRE provides the environment required to run Java applications. It contains the JVM, core libraries, and other resources needed for execution.
  • JVM (Java Virtual Machine):
    JVM is the heart of Java. It translates Java bytecode into machine code specific to the underlying hardware, making Java platform independent. JVM handles memory management, garbage collection, and security.

In short: JDK = JRE + development tools, and JRE = JVM + libraries.

4. What is Object-Oriented Programming (OOP)?

Answer:
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions or logic. Objects represent real-world entities, encapsulating data (attributes) and behavior (methods).

The four core principles of OOP in Java are:

  1. Encapsulation: Wrapping data and methods into a single unit (class) and restricting direct access to internal data.
  2. Inheritance: Allows one class (child) to inherit fields and methods from another class (parent), promoting code reusability.
  3. Polymorphism: Allows objects to take many forms—method overloading (compile-time) and method overriding (runtime) are two types.
  4. Abstraction: Hiding implementation details and showing only essential features to the user.

Java is entirely based on OOP principles, making it powerful, flexible, and easier to manage as applications grow in complexity.

5. What is a Constructor in Java?

Answer:
A constructor in Java is a special method that is automatically invoked when an object of a class is created. Its primary purpose is to initialize objects.

Key points about constructors:

  • A constructor has the same name as the class.
  • It does not have a return type, not even void.
  • If you don’t explicitly define a constructor, Java provides a default constructor.
  • You can use constructor overloading by defining multiple constructors with different parameter lists.

Example:

public class Person {
String name;

Person(String personName) {
name = personName;
}
}

Constructors help provide default or custom values to objects when they are created.

6. What is Method Overloading in Java?

Answer:
Method Overloading in Java is a feature that allows a class to have multiple methods with the same name but different parameter lists. It’s a type of compile-time polymorphism.

Benefits of Method Overloading:

  • Improves code readability.
  • Provides flexibility to perform similar operations with different input parameters.
  • Helps avoid using multiple method names for similar functionality.

Example:

class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {
return a + b;
}
}

In the example above, two add() methods exist with different parameter types. The compiler determines which one to execute based on the provided arguments.

7. What is the difference between ‘==’ and .equals() in Java?

Answer:
In Java, both == and .equals() are used for comparison, but they serve different purposes:

  • == Operator:
    Compares object references. It checks whether two reference variables point to the same memory location.
  • .equals() Method:
    Compares the contents of two objects. The default implementation in the Object class behaves like ==, but many classes (like String) override .equals() to perform value-based comparison.

Example:

String a = new String("Java");
String b = new String("Java");

System.out.println(a == b); // false (different memory locations)
System.out.println(a.equals(b)); // true (same content)

Always use .equals() when comparing strings or custom objects for logical equality.

8. What is Inheritance in Java?

Answer:
Inheritance in Java is an OOP concept where one class acquires the properties (fields) and behaviors (methods) of another class. It promotes code reusability and establishes a relationship between parent and child classes.

  • Parent Class (Superclass): The class whose features are inherited.
  • Child Class (Subclass): The class that inherits features from the parent.

Java supports single inheritance (one class extending another) using the extends keyword.

Example:

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}

Inheritance helps in maintaining cleaner, more organized code and avoids redundancy.

9. What are Java Data Types?

Answer:
Java has two main types of data types:

  1. Primitive Data Types:
    Includes byte, short, int, long, float, double, char, and boolean. These are basic types provided by the language for simple data handling.
  2. Non-Primitive Data Types:
    Includes Arrays, Classes, Interfaces, and Strings. These are more complex and are used to build structures and objects.

Example of primitive data types:

int age = 30;
double price = 99.99;
char grade = 'A';
boolean isActive = true;

Understanding data types is essential because they determine how data is stored, accessed, and manipulated in Java programs.

10. What is Exception Handling in Java?

Answer:
Exception Handling in Java refers to the mechanism of handling runtime errors to maintain the normal flow of application execution. Java provides a robust structure for dealing with exceptions using:

  • try — Block of code to monitor for errors.
  • catch — Defines how to handle specific exceptions.
  • finally — Executes regardless of an exception, used for resource cleanup.
  • throw — Used to manually throw an exception.
  • throws — Declares exceptions that a method might throw.

Example:

try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}

Proper exception handling ensures that applications remain stable and user-friendly even when errors occur.

Java Basic Interview Questions

11. What is method overriding in Java?

Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass. The overridden method in the child class must have the same name, return type, and parameters as the method in the parent class. This allows Java to support runtime polymorphism and enables dynamic method dispatch. It’s commonly used to define specific behaviors for different types of objects. To override a method, the @Override annotation is often used for better readability and compiler-level checks. Overriding improves flexibility and maintainability in object-oriented design.

class Animal {
void sound() { System.out.println("Generic sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}

12. What is the difference between ArrayList and LinkedList in Java?

Both ArrayList and LinkedList are implementations of the List interface in Java, but they have distinct differences in performance and structure. ArrayList uses a dynamic array, making random access operations like get() and set() faster (O(1) time complexity). However, inserting or deleting elements in the middle of an ArrayList can be costly (O(n) time). In contrast, LinkedList uses a doubly linked list, making insertions and deletions faster (O(1) if you have the reference), but slower random access (O(n) time). Choosing between them depends on your specific use case.

13. What is the use of the final keyword in Java?

This is one of the most asked Java Basic Interview Questions. The final keyword in Java is used to declare constants, prevent method overriding, and prevent class inheritance. final varriables ensures that the value cannot be changed once assigned, making it constant. When applied to methods, it prevents subclasses from modifying the method’s implementation. final classes make the class non-inheritable. For example, final class MyClass {} cannot be extended by any other class. Using final improves code stability and security by avoiding accidental changes or overriding of essential behavior in inheritance hierarchies.

14. What is the role of the super keyword in Java?

The super keyword in Java refers to the immediate parent class of a subclass. It is used to invoke parent class constructors, methods, or fields. This is especially useful in inheritance when you want to reuse or extend the behavior of a superclass without rewriting the same logic. super() must be the first statement in a subclass constructor if you wish to call the parent class’s constructor explicitly. It’s a powerful way to maintain clean, readable, and DRY (Don’t Repeat Yourself) code in hierarchical designs.

15. Explain checked and unchecked exceptions in Java.

In Java, exceptions are divided into checked and unchecked types. Checked exceptions are checked at compile-time, meaning the compiler forces the programmer to handle them using try-catch or throws. Examples include IOException and SQLException. On the other hand, unchecked exceptions are checked at runtime and are subclasses of RuntimeException. These include NullPointerException and ArithmeticException. While checked exceptions encourage proper error handling, unchecked exceptions usually indicate programming errors or bugs that should be fixed. Understanding both helps in writing robust, maintainable code.

16. What is multithreading in Java?

Multithreading in Java is a feature that allows the simultaneous execution of two or more threads for maximum utilization of CPU. Each thread represents a separate path of execution in a program. Java provides strong support for multithreading via the Thread class and the Runnable interface. Multithreading is essential for applications requiring high responsiveness, like GUIs or server-side applications. It improves performance by performing multiple tasks concurrently. Proper use of multithreading requires handling challenges like synchronization, deadlocks, and race conditions to ensure data consistency and avoid unpredictable behavior.

17. What is the static keyword in Java?

The static keyword in Java is used to indicate that a member (variable or method) belongs to the class itself rather than to any specific object. This means static variables and methods can be accessed without creating an instance of the class. Static members are useful for shared data or utility methods. For example, Math.sqrt() uses a static method, and a static final variable is often used for defining constants. Be cautious when using static members with shared data in multithreaded environments, as they can lead to concurrency issues if not handled properly.

18. What is encapsulation in Java?

Encapsulation is a fundamental principle of Object-Oriented Programming (OOP) that involves hiding the internal details of a class from outside interference and misuse. It is implemented in Java using private fields and public getters/setters to control access to those fields. Encapsulation improves code maintainability, flexibility, and security. By exposing only the necessary parts of an object’s data through controlled methods, you can prevent accidental changes and enforce rules for how data is accessed and modified. This leads to cleaner and more robust code.

19. What is an abstract class in Java?

An abstract class in Java is a class that cannot be instantiated and is designed to be extended by other classes. It may contain both abstract methods (without implementation) and concrete methods (with implementation). Abstract classes are used to provide a common base with shared code, while leaving specific implementations to subclasses. You use the abstract keyword to declare an abstract class. It’s different from interfaces because abstract classes can have state (fields) and constructors, while interfaces (before Java 8) could not have any method implementation or state.

Java Basic Interview Questions

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

The throw and throws keywords in Java are related to exception handling but serve different purposes. throw is used to actually throw an exception during program execution, typically within a method. For example, throw new IllegalArgumentException("Invalid input");. throws, on the other hand, is used in a method signature to declare that the method might throw certain exceptions. This informs the caller of the method about the potential exceptions that need to be handled. Both are crucial for writing clean and reliable exception-handling code in Java applications.

21. What is the difference between interface and abstract class in Java?

Both interfaces and abstract classes help in achieving abstraction in Java, but they have different use cases and characteristics. An interface represents a contract for what a class should do but not how to do it. Before Java 8, interfaces could only contain method signatures and constants, but now they can include default and static methods. An abstract class can have fields, constructors, and method implementations. Choose interfaces when you want multiple inheritance (since a class can implement multiple interfaces) and abstract classes when sharing common code across related classes.

22. What is garbage collection in Java?

Garbage collection (GC) in Java is an automatic memory management feature that reclaims memory occupied by objects no longer in use. The Java Virtual Machine (JVM) automatically runs garbage collectors in the background, freeing up memory to prevent memory leaks and improve performance. Objects that are unreachable or have no active references are eligible for garbage collection. Although developers don’t need to manually free memory like in C/C++, understanding how GC works (e.g., generational GC, major/minor collections) helps write efficient and memory-friendly Java applications.

23. What is the difference between Stack and Heap memory in Java?

In Java, memory is broadly divided into Stack and Heap. Stack memory is used for storing method calls, local variables, and function parameters. Each thread has its own stack, making it thread-safe. Heap memory, on the other hand, is used to store objects and their instance variables. It is shared among all threads. Stack memory is faster to access but limited in size, while Heap can store larger amounts of data but has overhead due to garbage collection. Understanding this distinction is essential for writing memory-efficient Java applications and avoiding memory leaks or stack overflows.

24. What is the main() method in Java?

Another very basic and most overlooked Java Basic Interview Questions. The main() method in Java is the entry point of any standalone Java application. Its standard signature is:
public static void main(String[] args).
Here’s what each keyword signifies:

  • public: Accessible by JVM from anywhere.
  • static: No need to create an instance of the class to run it.
  • void: It doesn’t return any value.
  • String[] args: Accepts command-line arguments.
    Without a main() method, the JVM won’t know where to start executing the program. It acts as the starting block of execution for Java applications.

25. What is the difference between break and continue in Java?

In Java, break and continue are control flow statements used within loops and switch statements. The break statement terminates the loop or switch entirely, exiting control to the next statement outside the loop or switch. Conversely, the continue statement skips the current iteration and proceeds with the next one. For example, you might use continue to skip certain elements in a loop but keep iterating. Using break and continue properly can make looping logic more readable and efficient by giving fine-grained control over flow execution.

26. What is a default constructor in Java?

A default constructor in Java is a constructor without parameters, either defined explicitly or provided automatically by the compiler if no constructor is written. Its primary role is to initialize the object with default values or to perform setup work that doesn’t require external input. For example:

public class Example {
Example() {
System.out.println("Default Constructor Called");
}
}

As soon as you define any constructor manually, the compiler doesn’t create a default one, making it essential to define one yourself if you need parameterless initialization along with parameterized ones.

27. What is the use of ‘this’ keyword in Java?

The this keyword in Java refers to the current instance of a class. It’s mainly used to resolve ambiguity between instance variables and local variables or constructor parameters with the same name. For example:

this.name = name;

It’s also used to invoke another constructor within the same class by using this() syntax. Additionally, you can pass this as a parameter to methods or constructors where the reference to the current object is required. this helps in writing clear, unambiguous, and readable code, especially in complex object-oriented structures.

Java Basic Interview Questions

28. Can a Java class have multiple constructors?

Yes, Java supports constructor overloading, which allows a class to have multiple constructors with different parameter lists. This flexibility enables the creation of objects in various ways depending on the required initialization. For example, one constructor might initialize only a few fields, while another might initialize all fields. The compiler differentiates between them based on the number and types of parameters. Constructor overloading improves usability and provides multiple entry points for object creation, enhancing the versatility and flexibility of class design in Java. This is one of the most important Java Basic Interview Questions.

29. What are wrapper classes in Java?

Wrapper classes in Java are used to convert primitive data types into objects. Java provides wrapper classes for each primitive type:

  • intInteger
  • charCharacter
  • booleanBoolean
    Wrapper classes allow primitives to be stored in collections like ArrayList, which require objects, not primitives. They also provide utility methods, such as parseInt() for converting strings to integers. With the introduction of autoboxing and unboxing in Java 5, conversion between primitives and wrapper objects is mostly automatic, simplifying code and improving readability.

30. What is type casting in Java?

Type casting in Java refers to converting one data type into another. There are two types of casting:

  1. Widening (Implicit): Smaller to larger type (e.g., int to long), done automatically.
  2. Narrowing (Explicit): Larger to smaller type (e.g., double to int), requires explicit casting like (int) value;.
    While widening conversions are safe, narrowing conversions can lead to data loss. Casting is essential in scenarios like numerical computations or handling object references when dealing with polymorphism or generic types. Proper understanding of casting helps prevent runtime exceptions like ClassCastException.

31. What is type casting in Java?

Polymorphism allows one entity to take multiple forms. In Java, it primarily refers to method overloading (compile-time polymorphism) and method overriding (runtime polymorphism). Method overloading allows multiple methods in the same class with the same name but different parameter lists. Method overriding allows a subclass to provide its specific implementation for a method declared in its parent class. Polymorphism helps in designingflexible, maintainable, and scalable code, where specific behaviors can be implemented depending on object type at runtime.

32. What is inheritance in Java?

Inheritance allows a class to inherit the properties and behaviors of another class using the extends keyword. This promotes code reusability and establishes a parent-child relationship between classes. For example:

class Animal { void eat() {} }  
class Dog extends Animal { void bark() {} }

Here, Dog inherits the eat() method from Animal. Java supports single inheritance to avoid ambiguity, but it provides multiple inheritance via interfaces. Inheritance forms the backbone of object-oriented programming (OOP).

33. What is abstraction in Java?

Abstraction in Java focuses on hiding the internal implementation details and showing only the necessary features of an object. It’s achieved through abstract classes and interfaces. Abstract classes can have both abstract (unimplemented) and concrete methods, while interfaces provide a blueprint for classes to implement. Abstraction allows developers to design programs more effectively by working on a higher level of thought, focusing on what an object does rather than how it does it.

34. What is abstraction in Java?

An interface in Java is like a contract specifying what a class must do, without defining how it does it. Interfaces contain abstract methods (and default/static methods from Java 8 onwards) and constant variables. For example:

interface Vehicle { void start(); }

A class implementing the interface must define its methods. Interfaces help in achieving full abstraction and support multiple inheritance, which classes don’t. They play a crucial role in designing flexible and scalable systems.

35. What is bytecode in Java?

Bytecode is an intermediate code generated after Java source code is compiled using javac. The Java Virtual Machine (JVM) executes the code regardless of the underlying processor. Bytecode files have a .class extension and are platform-independent, making Java programs portable. This abstraction allows the same bytecode to run on different operating systems with their respective JVMs. Bytecode enhances security, portability, and performance, making Java a widely adopted language across platforms.

Java Basic Interview Questions

36. What is a final variable in Java?

A final variable in Java is a constant—it can be assigned only once. Once a final variable is assigned a value, it cannot be changed. Final variables are useful when you want to define constants like final int MAX_USERS = 100;. Final can also be used with methods and classes:

  • Final method: We cannot override final methods
  • Final class: We cannot create a sublcass from a final class
    Using final improves code safety, readability, and intent, making it clear that a variable or method is not meant to be modified or overridden.

37. What are Java modifiers?

Java provides various modifiers that define access levels and behavioral properties of classes, methods, and variables.

  • Access Modifiers: public, private, protected, default
  • Non-access Modifiers: final, static, abstract, synchronized, volatile, transient
    Modifiers allow you to control the visibility, scope, and lifespan of code elements, making your application more structured and secure.

38. What is the ‘instanceof’ keyword in Java?

The instanceof keyword is used to check if an object is an instance of a specific class or subclass. It returns true if the object belongs to that class, otherwise false. It’s often used in type-checking before casting:

if (animal instanceof Dog) {
((Dog) animal).bark();
}

This helps prevent ClassCastException during runtime. It’s particularly useful when working with polymorphism or collections of superclass references.

39. How HashMap Works Internally in Java ?

HashMap in Java stores data as key-value pairs. Internally, it uses an array of buckets where each bucket holds a linked list or, in some cases, a balanced tree (from Java 8 onward).

  1. Hashing: When you add a key, Java computes its hash code, which determines which bucket (index) the entry will go into.
  2. Handling Collisions: If multiple keys have the same hash bucket, they are stored in a linked list or converted into a Red-Black Tree if the list grows too long (≥8 elements).
  3. Resizing: When the number of elements crosses the load factor (default 0.75), the HashMap doubles its size and rehashes the entries to spread them evenly.
  4. Retrieval (get()): HashMap uses the hash to find the bucket quickly, then compares keys using equals() to find the exact match.

40. How to create a Singleton class in Java?

A Singleton class in Java is a class that allows only one object (instance) of itself to be created throughout the lifetime of the application. It is commonly used when you need to control access to shared resources, like database connections, logging systems, or configuration managers.

Creating a Singleton involves three simple steps:

1. Private Constructor

Prevents other classes from instantiating the Singleton class directly.

2. Private Static Instance

Holds the single object of the class.

3. Public Static Method (getInstance())

Returns the instance to outside code, creating it if necessary.

public class Singleton {

    // Step 2: Create private static instance of the class
    private static Singleton instance;

    // Step 1: Private constructor prevents direct instantiation
    private Singleton() {
        // Initialization code here
    }

    // Step 3: Provide a public static method for getting the instance
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton(); // Create if not already created
        }
        return instance;
    }
}

Final Thoughts

Mastering these Java Basic Interview Questions is the first step toward cracking your next Java interview. By understanding Java’s core concepts—like OOP, constructors, inheritance, overloading, and exception handling—you’ll build the confidence to tackle real interview challenges.

Start practicing these questions today and boost your chances of landing your dream Java developer job. Download Java

Leave a Comment