Top Basic Java interview questions for freshers with answers – Easy to Reply

Below are some of the most important basic Java interview questions for freshers, along with simple and easy-to-understand answers:


1. What is Java?

Answer:
Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle). It is platform-independent, meaning Java code can run on any device with a Java Virtual Machine (JVM). Java is widely used for building web applications, mobile apps (Android), and enterprise software.


2. What are the key features of Java?

Answer:
The key features of Java are:

  • Platform Independence: Write once, run anywhere (WORA) using the JVM.
  • Object-Oriented: Java follows OOP concepts like inheritance, encapsulation, polymorphism, and abstraction.
  • Simple and Secure: Java is easy to learn and has built-in security features.
  • Multithreading: Supports concurrent execution of multiple threads.
  • Robust and Memory Management: Automatic garbage collection helps manage memory.

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

Answer:

  • JDK (Java Development Kit): A software package that includes tools for developing Java applications (e.g., compiler, debugger).
  • JRE (Java Runtime Environment): Provides the libraries and JVM required to run Java programs.
  • JVM (Java Virtual Machine): Executes Java bytecode and makes Java platform-independent.

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

Answer:

  • ==: Compares references (memory addresses) for objects and values for primitives.
  • .equals(): Compares the actual content or values of objects (overridden in classes like String).

Example:

String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2); // false (different references)
System.out.println(s1.equals(s2)); // true (same content)

5. What is the difference between StringStringBuilder, and StringBuffer?

Answer:

  • String: Immutable (cannot be changed after creation).
  • StringBuilder: Mutable and not thread-safe (faster for single-threaded operations).
  • StringBuffer: Mutable and thread-safe (slower due to synchronization).

6. What is the main difference between an abstract class and an interface?

Answer:

  • Abstract Class: Can have both abstract (no body) and concrete (with body) methods. It supports instance variables and constructors.
  • Interface: Can only have abstract methods (before Java 8). From Java 8, interfaces can have default and static methods. It does not support instance variables or constructors.

7. What is the final keyword in Java?

Answer:
The final keyword is used to restrict modification:

  • Final Variable: Cannot be reassigned.
  • Final Method: Cannot be overridden.
  • Final Class: Cannot be inherited.

Example:

final int x = 10;
x = 20; // Error: cannot reassign final variable

8. What is method overloading and method overriding?

Answer:

  • Method Overloading: Having multiple methods with the same name but different parameters (compile-time polymorphism).
  • Method Overriding: Redefining a method in a subclass that is already defined in its superclass (runtime polymorphism).

Example of Overloading:

void add(int a, int b) { }
void add(double a, double b) { }

Example of Overriding:

class Parent {
void display() { System.out.println("Parent"); }
}
class Child extends Parent {
void display() { System.out.println("Child"); }
}

9. What is a constructor in Java?

Answer:
A constructor is a special method used to initialize objects. It has the same name as the class and does not have a return type.

Example:

class Student {
Student() { // Constructor
System.out.println("Object created");
}
}

10. What is the difference between ArrayList and LinkedList?

Answer:

  • ArrayList: Uses a dynamic array. Faster for random access but slower for insertions/deletions in the middle.
  • LinkedList: Uses a doubly linked list. Faster for insertions/deletions but slower for random access.

11. What is exception handling in Java?

Answer:
Exception handling is a mechanism to handle runtime errors using trycatchfinally, and throw keywords.

Example:

try {
int x = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("This will always execute");
}

12. What is the difference between throw and throws?

Answer:

  • throw: Used to explicitly throw an exception.
  • throws: Used in method signatures to declare that a method might throw an exception.

Example:

void method() throws IOException {
throw new IOException("Error");
}

13. What is the static keyword in Java?

Answer:
The static keyword is used for memory management. It can be applied to variables, methods, blocks, and nested classes. Static members belong to the class rather than instances.

Example:

class Counter {
static int count = 0; // Shared across all instances
Counter() { count++; }
}

14. What is the super keyword in Java?

Answer:
The super keyword is used to refer to the immediate parent class object. It is used to call the parent class constructor, methods, or variables.

Example:

class Parent {
Parent() { System.out.println("Parent Constructor"); }
}
class Child extends Parent {
Child() {
super(); // Calls Parent Constructor
}
}

15. What is the this keyword in Java?

Answer:
The this keyword refers to the current object. It is used to differentiate between instance variables and parameters with the same name.

Example:

class Student {
    int age;
    Student(int age) {
        this.age = age; // Refers to instance variable
    }
}

16. What is a package in Java?

Answer:
A package is a collection of related classes and interfaces. It helps organize code and avoid naming conflicts. Packages can be categorized into:

  • Built-in packages (e.g., java.langjava.util)
  • User-defined packages (created by the developer).

Example:

package com.example.myapp;

17. What is the difference between publicprivateprotected, and default access modifiers?

Answer:

  • public: Accessible from anywhere.
  • private: Accessible only within the same class.
  • protected: Accessible within the same package and subclasses (even in other packages).
  • Default (no modifier): Accessible only within the same package.

18. What is the difference between HashMap and HashTable?

Answer:

  • HashMap: Not synchronized (not thread-safe), allows one null key and multiple null values.
  • HashTable: Synchronized (thread-safe), does not allow null keys or values.

19. What is the instanceof operator in Java?

Answer:
The instanceof operator is used to check if an object is an instance of a specific class or interface.

Example:

class Animal {}
class Dog extends Animal {}

Animal a = new Dog();
System.out.println(a instanceof Dog); // true
System.out.println(a instanceof Animal); // true

20. What is the difference between break and continue?

Answer:

  • break: Exits the loop or switch statement immediately.
  • continue: Skips the current iteration and moves to the next iteration of the loop.

Example:

for (int i = 1; i <= 5; i++) {
    if (i == 3) break; // Stops the loop at i = 3
    if (i == 2) continue; // Skips i = 2
    System.out.println(i);
}
// Output: 1

21. What is the difference between while and do-while loops?

Answer:

  • while: Checks the condition before executing the loop body.
  • do-while: Executes the loop body at least once before checking the condition.

Example:

int i = 5;
while (i < 5) { // Condition is false, so nothing happens
    System.out.println(i);
}

do {
    System.out.println(i); // Prints 5 once
} while (i < 5);

22. What is the difference between Stack and Queue?

Answer:

  • Stack: Follows Last-In-First-Out (LIFO) order. Operations: push()pop()peek().
  • Queue: Follows First-In-First-Out (FIFO) order. Operations: add()remove()peek().

23. What is the toString() method in Java?

Answer:
The toString() method is used to return a string representation of an object. It is defined in the Object class and can be overridden in custom classes.

Example:

class Student {
    String name;
    int age;
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Name: " + name + ", Age: " + age;
    }
}

Student s = new Student("Alice", 20);
System.out.println(s); // Calls toString() implicitly
// Output: Name: Alice, Age: 20

24. What is the difference between Comparable and Comparator?

Answer:

  • Comparable: A single sorting sequence defined within the class using the compareTo() method.
  • Comparator: Multiple sorting sequences defined outside the class using the compare() method.

Example of Comparable:

class Student implements Comparable<Student> {
    int age;
    Student(int age) { this.age = age; }
    @Override
    public int compareTo(Student s) {
        return this.age - s.age;
    }
}

Example of Comparator:

class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {
        return s1.age - s2.age;
    }
}

25. What is the volatile keyword in Java?

Answer:
The volatile keyword is used to indicate that a variable’s value may be modified by multiple threads. It ensures visibility of changes across threads.

Example:

volatile boolean flag = true;

26. What is the difference between checked and unchecked exceptions?

Answer:

  • Checked Exceptions: Checked at compile-time (e.g., IOExceptionSQLException). Must be handled using try-catch or throws.
  • Unchecked Exceptions: Checked at runtime (e.g., NullPointerExceptionArithmeticException). Handling is optional.

27. What is the transient keyword in Java?

Answer:
The transient keyword is used to indicate that a variable should not be serialized during object serialization.

Example:

class Student implements Serializable {
    transient int age; // Will not be serialized
}

28. What is the difference between List and Set?

Answer:

  • List: Ordered collection that allows duplicate elements (e.g., ArrayListLinkedList).
  • Set: Unordered collection that does not allow duplicate elements (e.g., HashSetTreeSet).

29. What is the synchronized keyword in Java?

Answer:
The synchronized keyword is used to make a method or block thread-safe, ensuring that only one thread can access it at a time.

Example:

synchronized void print() {
    System.out.println("Thread-safe method");
}

30. What is the difference between FileInputStream and FileReader?

Answer:

  • FileInputStream: Reads raw bytes (e.g., images, videos).
  • FileReader: Reads characters (text files).

*************** ALL THE BEST *****************
Visit JaganInfo youtube channel for more valuable content https://www.youtube.com/@jaganinfo

Similar Posts you may get more info >>