ByteRevise

ByteRevise

Master Java, Byte by Byte

ByteRevise

Core Java Interview Questions

Q: Explain the Singleton design pattern in Java and provide a thread-safe implementation.

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. This is useful for managing shared resources like a database connection or a logger. A thread-safe implementation is crucial in multi-threaded environments to prevent multiple threads from creating separate instances simultaneously. The example below uses the "double-checked locking" and `volatile` keyword for efficiency and thread-safety.


public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    public void showMessage() {
        System.out.println("Hello from Singleton!");
    }
}
                        

Data Structures

Q: How do you reverse a LinkedList in Java?

Reversing a LinkedList is a common data structure problem. The most efficient way is to iterate through the list, changing the `next` pointer of each node to point to its previous node. You need to keep track of three nodes: `current`, `previous`, and `next`.


public class LinkedListReversal {
    static class Node {
        int data;
        Node next;
        Node(int d) { data = d; next = null; }
    }

    Node head;

    Node reverse(Node node) {
        Node prev = null;
        Node current = node;
        Node next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }
}
                        

Spring Framework

Q: What is the difference between @Component, @Service, @Repository, and @Controller in Spring?

All these annotations are stereotypes used for component scanning. They mark a class as a Spring-managed bean. While `@Component` is a generic stereotype, `@Service`, `@Repository`, and `@Controller` are specializations for more specific use cases, which allows for better-defined application architecture and can enable special features (like exception translation for `@Repository`).

Other GitHub Pages

Here are links to my other projects and pages hosted on GitHub: