Core Java Qustion Set 1
Core Java Qustion Set 1
● HashMap:
○ Not thread-safe.
○ Allows one null key and multiple null values.
○ Fast performance in single-threaded environments.
● ConcurrentHashMap:
○ Thread-safe and designed for concurrent access.
○ Does not allow null keys or values.
○ Uses segment-level locking or CAS (Compare and Swap) operations for
better concurrency.
● The Java Memory Model defines how threads interact through memory and
ensures visibility of changes across threads.
● Key concepts:
Heap: Shared memory area where objects are stored.
Stack: Each thread has its own stack for local variables and method calls.
Visibility: Ensures changes made by one thread are visible to others (using
volatile, synchronized, etc.).
● ArrayList:
○ Backed by a dynamic array.
○ Fast random access (O(1)).
○ Slower insertions/deletions in the middle (O(n)).
● LinkedList:
○ Backed by a doubly-linked list.
○ Slower random access (O(n)).
○ Faster insertions/deletions in the middle (O(1)).
● The transient keyword is used to indicate that a field should not be serialized
during object serialization.
● Example: Sensitive data like passwords can be marked as transient to avoid
being saved in serialized form.
● Comparable:
○ Interface used to define the natural ordering of objects.
○ Implemented by the class itself (compareTo() method).
● Comparator:
○ Interface used to define custom ordering.
○ Implemented in a separate class (compare() method).
○ Allows multiple sorting strategies.
● String:
○ Immutable and thread-safe.
○ Every modification creates a new object.
● StringBuilder:
○ Mutable and not thread-safe.
○ Faster for single-threaded operations.
● StringBuffer:
○ Mutable and thread-safe (synchronized methods).
○ Slower than StringBuilder due to synchronization.
9. What is the diamond problem in Java, and how does Java handle it?
● The diamond problem occurs in multiple inheritance when a class inherits from
two classes that have a common ancestor.
● Java handles it by not supporting multiple inheritance for classes. However, it
allows multiple inheritance for interfaces (default methods) and ensures clarity
by requiring the implementing class to override ambiguous methods.
● Fail-Fast:
○ Throws ConcurrentModificationException if the collection is modified
while iterating.
○ Example: ArrayList, HashMap.
● Fail-Safe:
○ Does not throw exceptions and works on a clone of the collection.
○ Example: ConcurrentHashMap, CopyOnWriteArrayList.
● The finally block is used to execute code that must run regardless of whether
an exception is thrown or not.
● It is often used for resource cleanup (e.g., closing files, database connections).
● Checked Exceptions:
○ Checked at compile-time.
○ Must be handled using try-catch or declared in the method signature
(throws).
○ Example: IOException, SQLException.
● Unchecked Exceptions:
○ Checked at runtime.
○ Do not need to be explicitly handled.
○ Example: NullPointerException, ArithmeticException.
13. What is the try-with-resources statement?
● ==:
○ Compares object references (memory addresses).
○ Used for primitive types and object references.
● .equals():
○ Compares the actual content of objects.
○ Must be overridden in custom classes for meaningful comparison.
● stream():
○ Processes elements sequentially.
● parallelStream():
○ Processes elements in parallel using multiple threads.
○ Useful for large datasets but requires thread-safe operations
17. What is the purpose of the spliterator in Java?
● ClassNotFoundException:
○ Occurs when the classloader cannot find the class at runtime (e.g., during
Class.forName()).
● NoClassDefFoundError:
○ Occurs when the JVM cannot find the class definition at runtime, even
though it was present during compile-time.
● Checked exceptions: These are exceptions that must be declared in the method
signature using the throws keyword or handled within the method (e.g.,
IOException).
● Unchecked exceptions: These are runtime exceptions (e.g.,
NullPointerException, ArrayIndexOutOfBoundsException) and don't
need to be explicitly handled
Answer:
Answer:
● synchronized: It is used to ensure that only one thread can access a particular
block of code or method at a time, ensuring thread safety. It locks an object to
prevent simultaneous access.
● volatile: It is used to ensure that the value of a variable is always read from the
main memory, and not from the thread's local cache. It ensures visibility of
changes to a variable across different threads.
Answer:
● HashMap: It stores key-value pairs in a hash table. It does not guarantee any
specific order of elements. It allows null values and null keys.
● TreeMap: It stores key-value pairs in a red-black tree and sorts the keys
according to their natural order (or by a custom comparator). It does not allow
null keys but allows null values.
Example:
java
Copy
numbers.stream().filter(n -> n % 2 ==
0).forEach(System.out::println); // Prints even number
Answer:
●
// Method implementation
● }
Java 8
2. What is a lambda expression?
● Predicate:
○ Represents a boolean-valued function.
○ Method: boolean test(T t).
○ Example: Filtering a list.
● Predicate<Integer> isEven = n -> n % 2 == 0;
● Consumer:
○ Represents an operation that accepts a single input and returns no result.
○ Method: void accept(T t).
○ Example: Printing elements.
○ java
○ Copy
○ Consumer<String> print = s -> System.out.println(s);
● Supplier:
○ Represents a supplier of results.
○ Method: T get().
○ Example: Generating random numbers.
○ java
○ Copy
○ Supplier<Double> random = Math::random;
5. What is the Stream API?
● map():
○ Transforms each element of a stream into another object.
○ Example:
○ java
○ Copy
List<String> names = Arrays.asList("John", "Doe");
List<Integer> nameLengths = names.stream()
.map(String::length)
○ .collect(Collectors.toList());
● flatMap():
○ Flattens nested structures (e.g., List<List<T>> to List<T>).
○ Example:
○ List<List<String>> nestedList = Arrays.asList(
○ Arrays.asList("a", "b"),
○ Arrays.asList("c", "d")
○ );
○ List<String> flatList = nestedList.stream()
○ .flatMap(List::stream)
○ .collect(Collectors.toList());
● Optional is a container class that may or may not contain a non-null value.
● It is used to avoid NullPointerException and make the code more readable.
● Example:
Optional<String> optional = Optional.ofNullable(getName());
String name = optional.orElse("Default Name");
● limit(n):
○ Returns a stream with the first n elements.
● skip(n):
○ Returns a stream after skipping the first n elements.
.peek(System.out::println)
.collect(Collectors.toList());
Answer:
● map(): Transforms each element of the stream into another object, returning a stream of transformed
elements.
● flatMap(): Similar to map(), but it flattens the result into a single stream. This is useful when the
transformation results in nested collections.
Arrays.asList("Alice", "Bob"),
Arrays.asList("Charlie", "David")
);
// Using map
namesList.stream()
// Using flatMap
namesList.stream()
2. What is Dependency Injection (DI), and how does Spring implement it?
● Dependency Injection is a design pattern where objects are provided with their
dependencies instead of creating them internally.
● Spring implements DI using:
○ XML Configuration: Defining beans in an XML file.
○ Annotation-Based Configuration: Using annotations like @Autowired,
@Component, @Service, etc.
○ Java-Based Configuration: Using @Configuration and @Bean annotations.
● @Autowired:
○ Part of the Spring framework.
○ Injects by type by default.
○ Can be used with @Qualifier to specify the bean name.
● @Resource:
○ Part of Java EE (JSR-250).
○ Injects by name by default.
○ Can fall back to type-based injection if no name is specified.
● BeanFactory:
○ Basic container for bean management.
○ Lazy-loads beans.
○ Does not support annotation-based configuration.
● ApplicationContext:
○ Extends BeanFactory with additional features.
○ Eagerly loads beans by default.
○ Supports annotation-based configuration, AOP, and internationalization.
● @Controller:
○ Used in Spring MVC to handle web requests.
○ Returns a view name or ModelAndView.
● @RestController:
○ A combination of @Controller and @ResponseBody.
○ Used in RESTful web services to return JSON/XML responses directly.
11. What is Spring Boot, and how does it simplify Spring development?
● Spring Boot is an extension of the Spring framework that simplifies the
development of production-ready applications.
● Key features:
○ Auto-configuration: Automatically configures beans based on
dependencies.
○ Embedded servers: Includes Tomcat, Jetty, etc.
○ Starter dependencies: Simplifies dependency management.
○ Actuator: Provides production-ready features like health checks and
metrics.
● @SpringBootApplication:
○ A combination of @Configuration, @EnableAutoConfiguration, and
@ComponentScan.
○ Used to mark the main class of a Spring Boot application.
● @EnableAutoConfiguration:
○ Enables Spring Boot's auto-configuration mechanism.
15. What is Spring Data, and how does it simplify database access?
● CrudRepository:
○ Provides basic CRUD operations (create, read, update, delete).
● JpaRepository:
○ Extends CrudRepository and adds JPA-specific methods (e.g., flush(),
saveAndFlush()).
● The @Profile annotation is used to conditionally load beans based on the active
profile.
● Example:
@Configuration
@Profile("dev")
public class DevConfig {
// Beans for development environment
}
● @Qualifier:
○ Used to resolve ambiguity when multiple beans of the same type exist.
● @Primary:
○ Indicates that a bean should be given preference when multiple
candidates are available.
● @RequestParam:
○ Used to extract query parameters from the URL.
○ Example: /users?id=123
● @PathVariable:
○ Used to extract values from the URI template.
○ Example: /users/{id}
● @Configuration:
○ Indicates that the class is a source of bean definitions.
○ Can contain @Bean methods.
● @Component:
○ A generic stereotype for any Spring-managed bean.
● @SpringBootApplication:
○ A combination of @Configuration, @EnableAutoConfiguration, and
@ComponentScan.
○ Used to mark the main class of a Spring Boot application.
● @EnableAutoConfiguration:
○ Enables Spring Boot's auto-configuration mechanism.
○ Automatically configures beans based on the classpath and properties
● The @Profile annotation is used to conditionally load beans based on the active
profile.
● Example: