Most Asked Java Interview Questions – Set 1

Most Asked Java Interview Questions – Set 1

Most Asked Java Interview Questions – Set 1

1. What are the main features of Java?

Answer:
Java is a high-level, object-oriented, platform-independent programming language. Some key features include:

  • Platform Independence (Write Once, Run Anywhere – WORA)
  • Object-Oriented (Supports concepts like Encapsulation, Inheritance, and Polymorphism)
  • Multithreading (Supports concurrent execution of multiple tasks)
  • Memory Management (Automatic garbage collection)
  • Security (Runs inside a JVM sandbox)

2. Explain the difference between JDK, JRE, and JVM.

Answer:

  • JDK (Java Development Kit) → Contains JRE + Development tools (compilers, debuggers). Needed to develop Java programs.
  • JRE (Java Runtime Environment) → Contains JVM + libraries to run Java applications.
  • JVM (Java Virtual Machine) → Converts Java bytecode into machine code for execution.

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

Answer:

  • == → Compares memory addresses (checks if both objects reference the same memory).
  • .equals() → Compares the contents of the object (logical equality).

Example:

String s1 = new String("Hello");
String s2 = new String("Hello");

System.out.println(s1 == s2); // false (different objects)
System.out.println(s1.equals(s2)); // true (same content)

4. What are Java access modifiers?

Answer:
Access modifiers in Java control the visibility of classes, methods, and variables.

ModifierScopeAccessible in Same ClassAccessible in Same PackageAccessible in SubclassAccessible Outside Package
privateOnly within the class
defaultWithin the package
protectedPackage + subclass
publicEverywhere

5. What is the difference between static and final keywords?

Answer:

  • static → Used for class-level variables and methods (shared among all instances).
  • final → Used to declare constants, prevent method overriding, and class inheritance.

Example:

class Example {
static int count = 0; // Shared among all objects
final int MAX = 100; // Constant value

final void display() { // Cannot be overridden
System.out.println("Hello");
}
}

6. What is the difference between method overloading and method overriding?

Answer:

FeatureMethod OverloadingMethod Overriding
DefinitionMultiple methods with the same name but different parameters in the same class.A child class provides a new implementation for a method from the parent class.
ParametersMust be different (number, type, or order).Must be the same.
Return TypeCan be different.Must be the same or covariant.
Access ModifierNo restrictions.Cannot have a more restrictive access modifier than the parent class.
Static MethodsCan be overloaded.Cannot be overridden.

Example of Overloading:

class OverloadingExample {
void show(int a) {
System.out.println("Integer: " + a);
}
void show(double a) {
System.out.println("Double: " + a);
}
}

Example of Overriding:

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

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

Answer:

FeatureAbstract ClassInterface
UsageUsed to provide a base class with some implemented methods.Defines only abstract methods (before Java 8).
MethodsCan have both abstract & concrete methods.Can only have abstract methods (Java 8+ allows default and static methods).
VariablesCan have instance variables.Only contains public static final variables.
ConstructorCan have constructors.Cannot have constructors.
Access ModifiersMethods can have any access modifier.Methods are public by default.
Multiple InheritanceCannot support multiple inheritance.Supports multiple inheritance.

Example of Abstract Class:

abstract class Animal {
abstract void makeSound();
void sleep() {
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark!");
}
}

Example of Interface:

interface Animal {
void makeSound(); // Abstract method
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark!");
}
}

8. What are the types of exceptions in Java? How is exception handling done?

Answer:
Exceptions are unexpected runtime errors. Java has two types of exceptions:

  1. Checked Exceptions (Compile-time) – Must be handled using try-catch or throws.
    • Examples: IOException, SQLException
  2. Unchecked Exceptions (Runtime) – Occur at runtime and need not be explicitly handled.
    • Examples: NullPointerException, ArrayIndexOutOfBoundsException

Example of Exception Handling:

try {
int result = 10 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("Execution completed.");
}

9. What is multithreading in Java? How do you create a thread?

Answer:
Multithreading allows a program to run multiple threads simultaneously for better performance.

Two ways to create a thread:

  1. Extending the Thread class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running...");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
  1. Implementing the Runnable interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running...");
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}

10. What are Java Collections? Name important classes in Java Collections Framework (JCF).

Answer:
The Java Collections Framework (JCF) provides ready-to-use data structures and algorithms for handling groups of objects.

TypeInterfaceImplementations
List (Ordered, Duplicates Allowed)List<E>ArrayList, LinkedList, Vector, Stack
Set (Unique Elements)Set<E>HashSet, LinkedHashSet, TreeSet
Queue (FIFO Order)Queue<E>PriorityQueue, Deque, LinkedList
Map (Key-Value Pairs)Map<K,V>HashMap, LinkedHashMap, TreeMap, Hashtable

Example: Using ArrayList

import java.util.ArrayList;

public class ListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println(names);
}
}

11. What is the difference between String, StringBuilder, and StringBuffer?

Answer:

FeatureStringStringBufferStringBuilder
MutabilityImmutable (Creates new object)Mutable (Thread-safe)Mutable (Faster, but not thread-safe)
PerformanceSlow (because new objects are created)Fast (synchronized)Fastest (no synchronization)
Thread Safety✅ Safe✅ Safe❌ Not Safe

Example:

String str = "Hello";
str = str + " World"; // Creates new object

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Modifies existing object

12. What is the difference between HashMap and Hashtable?

Answer:

FeatureHashMapHashtable
Synchronization❌ Not synchronized (Faster)✅ Synchronized (Thread-safe)
PerformanceFastSlow
Null Keys/ValuesAllows 1 null key, multiple null values❌ Does not allow null keys or values
IterationUses Iterator (Fail-fast)Uses Enumeration (Not fail-fast)

Example:

import java.util.*;

public class MapExample {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
System.out.println(map);
}
}

13. What is the difference between Comparable and Comparator?

Answer:

FeatureComparableComparator
PurposeUsed for natural sorting of objects.Used for custom sorting.
MethodcompareTo(T obj)compare(T obj1, T obj2)
Example UsageTreeSet, TreeMapCollections sort() method

Example using Comparator:

import java.util.*;

class Student {
int age;
Student(int age) { this.age = age; }
}

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

public class ComparatorExample {
public static void main(String[] args) {
List<Student> students = Arrays.asList(new Student(25), new Student(20));
Collections.sort(students, new AgeComparator());
}
}
Boost Your Placement Chances – Join Our FREE Campus Placement Evaluation Test

If you’re serious about placements, feel free to attend our FREE Campus Placement Evaluation Test! https://faceprep.in/article/campus-placement-evaluation-test/

Conclusion

Mastering Java interview questions is essential for securing a job in software development. In this set, we covered fundamental and frequently asked Java interview questions that assess your understanding of core concepts such as OOP principles, exception handling, collections, multithreading, and more.

Click here to know more our program!

Most Asked Java Interview Questions - Set 1
c