Singleton Design Pattern Problem: Ensure a class has only one instance and provide a global point of access to that instance. Solution: Create a class with a private constructor, a private static instance variable, and a public static method to provide access to the single instance. Key Points to Make a Singleton Class in Java: Private constructor to prevent external instantiation. Private static instance variable to hold the single instance. Public static method to provide access to the instance. Ways to Break a Singleton: Reflection: Using reflection to access the private constructor. Serialization: When a Singleton is serialized and deserialized, it creates a new instance. Cloning: Creating a clone of the Singleton instance. Prevention Techniques: Lazy Initialization with Double-Checked Locking: Use double-checked locking for lazy initialization to ensure thread safety. Enum Singleton: Implement the Singleton using an enum to handle serialization, reflection, and cloning. Ove...
To find the second-highest salary from a list of employees using Java 8 streams, you can follow these steps: Create a list of employees with their salaries. Use Java 8 streams to sort the employees by salary in descending order. Skip the first element (which is the employee with the highest salary). Get the first element of the remaining stream (which is the employee with the second-highest salary). Example code: java import java.util.ArrayList; import java.util.List; class Employee { private String name; private double salary; public Employee (String name, double salary) { this .name = name; this .salary = salary; } public double getSalary () { return salary; } } public class SecondHighestSalary { public static void main (String[] args) { List<Employee> employees = new ArrayList <>(); employees.add( new Employee ( "John" , 60000.0 )); employees.add( new Employe...