21. What is a Java interface, and how does it differ from an abstract class?
- An interface is a collection of abstract methods that a class can implement. Unlike an abstract class, a class can implement multiple interfaces but can extend only one class.
22. What is the purpose of the break and continue statements in Java loops?
- The break statement is used to exit a loop prematurely, while the continue statement is used to skip the current iteration and continue with the next iteration of the loop.
23. Explain the concept of polymorphism in Java.
- Polymorphism allows objects of different classes to be treated as objects of a common superclass. It’s achieved through method overriding and method overloading.
24. What is the role of the Comparable and Comparator interfaces in Java?
- The Comparable interface is used to define a natural order for a class, while the Comparator interface allows you to define multiple ways to compare objects.
25. What is the purpose of the final keyword in Java?
- The final keyword is used to indicate that a variable, method, or class cannot be modified, extended, or subclassed, respectively.
26. Explain the concept of the Java memory model and its significance in multithreading.
- The Java memory model defines how threads interact with memory. It’s crucial for ensuring proper synchronization and visibility of data between threads in multithreaded applications.
27. What is the difference between checked and unchecked exceptions in Java?
- Checked exceptions are exceptions that must be either caught or declared, while unchecked exceptions (subclasses of RuntimeException) do not need to be explicitly caught or declared.
28. What is the purpose of the instanceof operator in Java?
- The instanceof operator is used to check if an object is an instance of a particular class or interface, allowing you to perform type checking before casting.
29. Explain the concept of class loading in Java and the role of the classloader.
- Class loading is the process of loading classes into memory when they are referenced in a Java program. The classloader is responsible for finding and loading classes at runtime.
30. What is the purpose of the java.lang.Math class in Java, and how is it different from the java.util.Random class?
- The java.lang.Math class provides mathematical functions and constants, while the java.util.Random class is used for generating random numbers. The Math class does not provide random number generation capabilities.