← Back to DevBytes

Top 50 Java Interview Questions for Entry-Level Developers

Top 50 Java Interview Questions for Entry-Level Developers

Preparing for your first Java developer interview can feel overwhelming. Interviewers for entry-level roles typically focus on core Java concepts, object-oriented programming fundamentals, collections, exception handling, and basic multithreading. This tutorial walks you through the 50 most commonly asked Java interview questions, complete with clear explanations and practical code examples. Whether you are a fresh graduate or transitioning into Java development, mastering these questions will give you a strong foundation and the confidence to ace your interview.

Why These Questions Matter

Entry-level interviews are designed to test whether you truly understand the language fundamentals rather than just memorizing syntax. Interviewers want to see how you think, how you reason about memory, how you handle errors, and whether you can write clean, idiomatic Java. By studying these questions, you will not only prepare for interviews but also reinforce habits that will make you a better professional developer.

Section 1: Core Java Fundamentals

1. What is Java and what are its main features?

Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now owned by Oracle). Its main features include platform independence via the JVM, automatic memory management through garbage collection, strong typing, multithreading support, and a rich standard library.

2. How does Java achieve platform independence?

Java compiles source code into bytecode (.class files) rather than native machine code. The Java Virtual Machine (JVM) interprets or JIT-compiles this bytecode at runtime. Because each platform has its own JVM implementation, the same bytecode can run on Windows, Linux, or macOS without modification.

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

4. What are the primitive data types in Java?

Java has eight primitive types: byte, short, int, long, float, double, char, and boolean. Primitives store raw values directly on the stack (or as fields inside objects on the heap), unlike reference types which point to objects.

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

The == operator compares references (memory addresses) for objects, or values for primitives. The equals() method compares logical content, but only if the class overrides it. The default Object.equals() behaves like ==.

String a = new String("hello");
String b = new String("hello");
System.out.println(a == b);        // false (different objects)
System.out.println(a.equals(b));   // true (same content)

6. What is autoboxing and unboxing?

Autoboxing is the automatic conversion of a primitive to its corresponding wrapper class. Unboxing is the reverse. This feature allows primitives and wrappers to be used interchangeably in many contexts.

Integer boxed = 10;        // autoboxing int -> Integer
int primitive = boxed;     // unboxing Integer -> int

7. What is the difference between final, finally, and finalize?

8. What is the difference between static and instance variables?

Static variables belong to the class itself and are shared across all instances. Instance variables belong to individual objects, and each object has its own copy.

class Counter {
    static int total = 0;  // shared
    int count = 0;          // per instance

    void increment() {
        total++;
        count++;
    }
}

9. What is type casting in Java?

Type casting converts a variable from one type to another. Upcasting (implicit) converts a subclass reference to a superclass. Downcasting (explicit) converts a superclass reference back to a subclass, and requires an explicit cast.

Object obj = "Hello";        // upcasting
String str = (String) obj;   // downcasting

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

String is immutable, meaning every modification creates a new object. StringBuilder is mutable and not synchronized, making it efficient for single-threaded string manipulation. StringBuffer is mutable and synchronized, making it thread-safe but slower.

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);  // Hello World

Section 2: Object-Oriented Programming

11. What are the four pillars of OOP?

12. What is encapsulation and how is it achieved?

Encapsulation bundles data and methods that operate on that data within a class, and restricts direct access to fields using private modifiers. Access is provided through public getters and setters, allowing validation logic.

public class Account {
    private double balance;

    public double getBalance() { return balance; }

    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
}

13. What is inheritance in Java?

Inheritance allows a subclass to inherit fields and methods from a superclass using the extends keyword. Java supports single inheritance for classes but allows multiple inheritance of type through interfaces.

class Animal {
    void breathe() { System.out.println("Breathing..."); }
}

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

14. What is polymorphism?

Polymorphism allows objects to take many forms. Compile-time polymorphism is achieved through method overloading, while runtime polymorphism is achieved through method overriding.

class Shape {
    double area() { return 0; }
}
class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    @Override double area() { return Math.PI * r * r; }
}

Shape s = new Circle(5);
System.out.println(s.area());  // calls Circle's area()

15. What is method overloading?

Method overloading allows multiple methods with the same name but different parameter lists (different number, type, or order of parameters) within the same class. It is resolved at compile time.

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

16. What is method overriding?

Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass. The method signature must match, and you should use the @Override annotation for clarity and compiler checks.

17. Can you override a static method?

No. Static methods belong to the class, not instances. A subclass can declare a static method with the same signature, but this is called method hiding, not overriding. Runtime polymorphism does not apply.

18. What is an abstract class?

An abstract class cannot be instantiated and may contain abstract methods (without a body) as well as concrete methods. It is used as a base for subclasses to provide common behavior and enforce contracts.

abstract class Vehicle {
    abstract void start();
    void stop() { System.out.println("Stopping..."); }
}

19. What is an interface and how does it differ from an abstract class?

An interface defines a contract with abstract methods (and since Java 8, default and static methods). A class can implement multiple interfaces but extend only one class. Interfaces cannot maintain state (instance fields), while abstract classes can.

interface Flyable {
    void fly();
    default void land() { System.out.println("Landing..."); }
}

class Bird implements Flyable {
    public void fly() { System.out.println("Flying!"); }
}

20. What is the super keyword used for?

The super keyword refers to the immediate parent class object. It is used to call superclass constructors, access superclass methods that have been overridden, and access superclass fields.

class Parent {
    void greet() { System.out.println("Hello from Parent"); }
}
class Child extends Parent {
    @Override void greet() {
        super.greet();
        System.out.println("Hello from Child");
    }
}

21. What is a constructor and what are its types?

A constructor is a special method invoked when an object is created, used to initialize its state. Types include default (no-arg), parameterized, and copy constructors. Java does not have a built-in copy constructor, but you can define one manually.

class Person {
    String name;
    Person() { this.name = "Unknown"; }              // default
    Person(String name) { this.name = name; }        // parameterized
    Person(Person other) { this.name = other.name; } // copy
}

22. Does Java support multiple inheritance?

Java does not support multiple inheritance of classes to avoid the diamond problem. However, a class can implement multiple interfaces, which provides the benefits of multiple inheritance of type without the ambiguity.

Section 3: Collections Framework

23. What is the Java Collections Framework?

The Collections Framework is a unified architecture in java.util for storing and manipulating groups of objects. It includes interfaces like List, Set, and Map, and implementations such as ArrayList, HashSet, and HashMap.

24. What is the difference between ArrayList and LinkedList?

ArrayList is backed by a dynamic array, providing fast random access but slow insertions and deletions in the middle. LinkedList is backed by a doubly linked list, providing fast insertions and deletions at any position but slower random access.

25. What is the difference between HashMap and HashTable?

26. What is the difference between Set and List?

A List is an ordered collection that allows duplicate elements and provides positional access. A Set is a collection that does not allow duplicates and typically has no guaranteed order (unless using LinkedHashSet or TreeSet).

27. How does a HashMap work internally?

A HashMap uses an array of buckets. When you put a key-value pair, it computes the key's hash code, applies a hash function to determine the bucket index, and stores the entry. If multiple keys map to the same bucket (collision), entries are stored in a linked list or balanced tree (since Java 8, when the list exceeds a threshold).

28. What is the difference between Comparable and Comparator?

Comparable defines natural ordering within the class itself by implementing compareTo(). Comparator is a separate object that defines custom ordering, allowing multiple sort strategies without modifying the class.

List<String> names = Arrays.asList("Charlie", "Alice", "Bob");
Collections.sort(names);                                  // Comparable
names.sort(Comparator.comparingInt(String::length));      // Comparator

29. What is Iterator and how is it different from ListIterator?

An Iterator allows forward traversal and removal of elements from any collection. A ListIterator is specific to List and supports bidirectional traversal, element replacement, and addition.

30. What is the difference between fail-fast and fail-safe iterators?

Fail-fast iterators throw a ConcurrentModificationException if the collection is modified during iteration (e.g., ArrayList iterator). Fail-safe iterators operate on a copy of the collection and do not throw exceptions (e.g., CopyOnWriteArrayList), but they may not reflect the latest changes.

Section 4: Exception Handling

31. What is an exception in Java?

An exception is an event that disrupts the normal flow of a program during execution. Java represents exceptions as objects of classes that inherit from Throwable, enabling structured error handling.

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

33. What is the try-catch-finally block?

The try block contains code that might throw an exception. The catch block handles the exception. The finally block always executes (unless the JVM exits) and is used for cleanup such as closing resources.

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

34. What is the throws keyword?

The throws keyword in a method signature declares that the method may throw one or more checked exceptions, forcing the caller to handle or propagate them.

public void readFile(String path) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    // ...
}

35. What is the difference between throw and throws?

throw is used to explicitly throw an exception object. throws is used in a method declaration to indicate the exceptions that method might throw.

public void validate(int age) throws IllegalArgumentException {
    if (age < 0) throw new IllegalArgumentException("Age cannot be negative");
}

36. Can a finally block be skipped?

Yes. A finally block will not execute if the JVM exits via System.exit() before reaching it, or if the thread running the code is killed. Otherwise, it executes whether or not an exception is thrown.

37. What is a custom exception?

A custom exception is a user-defined exception class that extends Exception (for checked) or RuntimeException (for unchecked). It allows you to represent domain-specific error conditions.

class InvalidUserException extends Exception {
    public InvalidUserException(String message) {
        super(message);
    }
}

Section 5: Strings and Wrappers

38. Why is String immutable in Java?

Strings are immutable to provide security (safe use in class loading and networking), thread safety without synchronization, and performance optimizations such as the string constant pool and caching of hash codes.

39. What is the String constant pool?

The String constant pool is a special memory region in the heap where string literals are stored. When you create a string literal, the JVM checks the pool first and reuses an existing reference, saving memory.

String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b);      // true (same pool reference)
System.out.println(a == c);      // false
System.out.println(a == c.intern()); // true

40. What is the difference between String.equals() and String.equalsIgnoreCase()?

equals() compares two strings with case sensitivity. equalsIgnoreCase() compares them ignoring character case, so "Java".equalsIgnoreCase("java") returns true.

41. What are wrapper classes?

Wrapper classes are object representations of primitive types, found in java.lang. They allow primitives to be used in collections and provide utility methods. Examples include Integer, Double, Boolean, and Character.

Section 6: Multithreading and Concurrency

42. What is a thread in Java?

A thread is the smallest unit of execution within a program. Java supports multithreading, allowing multiple threads to run concurrently within a single process, sharing memory but executing independently.

43. What are the two ways to create a thread in Java?

You can create a thread by extending the Thread class or by implementing the Runnable interface. Implementing Runnable is generally preferred because it allows the class to extend another class.

class MyTask implements Runnable {
    public void run() {
        System.out.println("Running in: " + Thread.currentThread().getName());
    }
}

Thread t = new Thread(new MyTask());
t.start();

44. What is the difference between start() and run()?

Calling start() creates a new thread and invokes run() in that thread. Calling run() directly executes the method in the current thread, just like a normal method call, without creating a new thread.

45. What is synchronization and why is it needed?

Synchronization controls access to shared resources by multiple threads to prevent race conditions and ensure data consistency. Java provides the synchronized keyword for methods and blocks, as well as higher-level utilities in java.util.concurrent.

class Counter {
    private int count = 0;
    synchronized void increment() { count++; }
    int getCount() { return count; }
}

46. What is the volatile keyword?

The volatile keyword ensures that a variable's value is always read from and written to main memory, not cached in a thread's local cache. It guarantees visibility across threads but does not provide atomicity for compound operations.

Section 7: Memory, Keywords, and Best Practices

47. What is garbage collection in Java?

Garbage collection is the automatic process by which the JVM reclaims memory occupied by objects that are no longer reachable. The garbage collector runs in the background, freeing developers from manual memory management. You can suggest collection with System.gc(), but it is not guaranteed to run immediately.

48. What is the difference between break and continue?

The break statement exits the enclosing loop or switch statement entirely. The continue statement skips the remaining statements in the current iteration and moves to the next iteration of the loop.

for (int i = 0; i < 10; i++) {
    if (i == 5) break;      // stops loop at i=5
    if (i % 2 == 0) continue; // skips even numbers
    System.out.println(i);
}

49. What is the this keyword?

The this keyword refers to the current object instance. It is used to differentiate between instance variables and parameters with the same name, to call other constructors in the same class via this(), and to pass the current object as an argument.

class Employee {
    String name;
    Employee(String name) {
        this.name = name;  // disambiguate
    }
}

50. What are some Java best practices every entry-level developer should follow?

Conclusion

Mastering these 50 Java interview questions will give you a solid foundation for any entry-level Java developer role. The key is not just to memorize answers but to understand the underlying concepts, write small code samples to test your assumptions, and be able to explain your reasoning clearly during an interview. Practice coding these examples yourself, experiment with variations, and review the official Java documentation to deepen your understanding. With consistent preparation and hands-on practice, you will be well-equipped to demonstrate your Java knowledge confidently and land your first developer position.

— Ad —

Google AdSense will appear here after approval

← Back to all articles