Menu

Java Topic

Java Interview Question 2

Java Fundamentals - Advanced

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

  • final: Keyword for constants, non-inheritable classes, non-overridable methods

  • finally: Block that always executes in exception handling

  • **finalize(): Method called by garbage collector before object destruction

2. Explain static keyword and its uses

  • Static variables: Class-level variables, shared among all instances

  • Static methods: Class-level methods, can be called without object

  • Static block: Executes when class is loaded

  • Static nested class: Nested class that doesn't require outer class instance

3. What is method overloading vs method overriding?

  • Overloading: Same method name, different parameters (compile-time polymorphism)

  • Overriding: Same method signature in child class (runtime polymorphism)

Memory Management & Performance

4. What are the different types of memory in JVM?

  • Heap: Object storage

  • Stack: Method calls and local variables

  • Method Area: Class metadata

  • PC Registers: Thread execution points

  • Native Method Stack: Native method calls

5. How does garbage collection work in Java?

  • Mark and Sweep: Marks reachable objects, sweeps unreachable ones

  • Generational GC: Young Generation (Eden, S0, S1) and Old Generation

  • Types: Serial, Parallel, CMS, G1 GC

6. What are memory leaks in Java and how to avoid them?

  • Causes: Static collections, unclosed resources, listeners not removed

  • Prevention: Use weak references, close resources in finally, avoid static collections

Collections Framework - Deep Dive

7. How does HashMap work internally?

  • Uses array of buckets (Node<K,V>[] table)

  • Hash function determines bucket index

  • Handles collisions using linked list or tree (Java 8+)

  • Load factor (0.75) triggers resizing

8. Difference between Comparable and Comparator

  • Comparable: Natural ordering (compareTo() method)

  • Comparator: Custom ordering (compare() method)

// Comparable
class Person implements Comparable<Person> {
    public int compareTo(Person other) {
        return this.name.compareTo(other.name);
    }
}

// Comparator
Comparator<Person> ageComparator = (p1, p2) -> p1.getAge() - p2.getAge();

9. What is ConcurrentHashMap and how is it different from HashMap?

  • Thread-safe: Uses segment locking or CAS operations

  • Better performance: than synchronized collections

  • Doesn't allow null keys/values

Multithreading - Advanced

10. What is volatile keyword in Java?

  • Ensures variable visibility across threads

  • Prevents compiler reordering optimizations

  • Doesn't provide atomicity (unlike synchronized)

11. Explain Executor framework

  • Manages thread pools and execution

  • Types: FixedThreadPool, CachedThreadPool, ScheduledThreadPool

ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> System.out.println("Task executed"));

12. What is deadlock and how to prevent it?

  • Situation: Two or more threads waiting for each other indefinitely

  • Prevention:

    • Lock ordering

    • Timeout on lock acquisition

    • Avoid nested locks

Java 8+ Features - Detailed

13. What are functional interfaces?

  • Interfaces with exactly one abstract method

  • Can have multiple default/static methods

  • Examples: Runnable, Callable, Comparator

  • New: Predicate, Function, Consumer, Supplier

14. Explain method references

  • Shorthand for lambda expressions

// Instead of: list.forEach(s -> System.out.println(s));
list.forEach(System.out::println);

// Types:
// Static method: Class::staticMethod
// Instance method: instance::method
// Arbitrary object: Class::method
// Constructor: Class::new

15. What are the new Date/Time API features in Java 8?

  • LocalDate: Date without time

  • LocalTime: Time without date

  • LocalDateTime: Date and time

  • ZonedDateTime: Date, time with timezone

  • Immutable and thread-safe

Design Patterns & Architecture

16. What is the Factory pattern?

  • Creates objects without exposing creation logic

  • Centralized object creation

public class AnimalFactory {
    public static Animal createAnimal(String type) {
        switch(type) {
            case "dog": return new Dog();
            case "cat": return new Cat();
            default: throw new IllegalArgumentException();
        }
    }
}

17. Explain the Builder pattern

  • Constructs complex objects step by step

  • Useful when object has many parameters

Person person = new Person.Builder()
    .name("John")
    .age(30)
    .address("123 Street")
    .build();

Spring Framework Basics

18. What is dependency injection?

  • Objects receive their dependencies from external source rather than creating them

  • Types: Constructor injection, Setter injection, Field injection

  • Promotes loose coupling and testability

19. What are Spring Bean scopes?

  • singleton: One instance per Spring container (default)

  • prototype: New instance each time requested

  • request: One instance per HTTP request

  • session: One instance per HTTP session

  • global-session: One instance per global HTTP session

Database & JDBC

20. What is JDBC and how does it work?

  • Java Database Connectivity API

  • Steps:

    1. Load driver: Class.forName("com.mysql.jdbc.Driver")

    2. Create connection: DriverManager.getConnection(url, user, pass)

    3. Create statement: connection.createStatement()

    4. Execute query: statement.executeQuery(sql)

    5. Process results: ResultSet

    6. Close resources

21. Difference between Statement, PreparedStatement, and CallableStatement

  • Statement: Simple SQL, prone to SQL injection

  • PreparedStatement: Precompiled, parameterized, prevents SQL injection

  • CallableStatement: For stored procedures

Testing & Debugging

22. What is JUnit and how to write test cases?

  • Unit testing framework

@Test
public void testAddition() {
    Calculator calc = new Calculator();
    assertEquals(5, calc.add(2, 3));
}

@BeforeEach // JUnit 5 (was @Before in JUnit 4)
public void setUp() {
    // Setup before each test
}

Security

23. What is the principle of least privilege in Java security?

  • Code should run with only necessary permissions

  • Implemented through SecurityManager and policy files

Microservices & Cloud

24. What are microservices and their advantages?

  • Architecture: Small, independent, loosely coupled services

  • Advantages:

    • Independent deployment

    • Technology diversity

    • Fault isolation

    • Scalability

System Design

25. How would you design a caching system in Java?

  • Requirements: Thread-safe, eviction policy, memory management

  • Implementation:

    • Use ConcurrentHashMap with expiration

    • LRU/LFU eviction policies

    • Consider distributed caching (Redis, Hazelcast)

    • Monitor cache hit/miss ratios

These questions cover advanced Java concepts, design patterns, framework knowledge, and system design principles that are crucial for senior Java developer positions and technical architecture roles.

 

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?