Saturday, 5 April 2025

 

🔍 10 Tricky Spring Boot Internal working Interview Questions You Must Know (with Answers)

Spring Boot makes life easier for developers, but interviewers love to dig into what happens under the hood. If you're preparing for a Spring Boot interview, these tricky questions and answers will give you an edge!


✅ 1. What exactly happens when you call SpringApplication.run()?

When you invoke SpringApplication.run():

  • It creates and configures the ApplicationContext

  • Loads application.properties or .yml configuration files

  • Registers ApplicationListeners and ApplicationInitializers

  • Performs component scanning

  • Triggers auto-configuration via @EnableAutoConfiguration

Pro Tip: Mention that it uses SpringFactoriesLoader to load configuration classes from META-INF/spring.factories.


✅ 2. How does Spring Boot decide which configuration class to load automatically?

Spring Boot uses:


SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class)

It loads class names from:


META-INF/spring.factories

Only those relevant to the current classpath dependencies are activated.


✅ 3. What is the difference between @SpringBootApplication and @EnableAutoConfiguration?

  • @SpringBootApplication is a meta-annotation that includes:

    • @Configuration

    • @ComponentScan

    • @EnableAutoConfiguration

  • Using only @EnableAutoConfiguration will not scan for beans.

📌 Tip: Interviewers often test if you understand this convenience wrapper.


✅ 4. If two auto-configuration classes try to create the same bean, who wins?

Spring Boot uses conditional annotations like:


@ConditionalOnMissingBean

This means:

  • If you define the bean manually → your bean wins

  • Otherwise, Spring uses the auto-configured one

This is how Spring Boot gives you full control to override.


✅ 5. How is DispatcherServlet registered without a web.xml?

Spring Boot uses auto-configuration:


DispatcherServletAutoConfiguration

Internally, it uses a ServletRegistrationBean to register the DispatcherServlet at runtime — no need for web.xml.


✅ 6. How can you disable a specific auto-configuration?

There are two ways:

a) Using exclude in @SpringBootApplication:


@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })

b) In application.properties:


spring.autoconfigure.exclude=
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

✅ 7. What if multiple application.properties files are found in the classpath?

Spring Boot loads properties in the following priority order:

  1. /config/application.properties

  2. /application.properties in root classpath

  3. External files via -Dspring.config.location=...

  4. Command-line arguments override all

This enables flexible configuration across environments.


✅ 8. Can you run a Spring Boot app without @SpringBootApplication?

Yes. Just use the equivalent annotations manually:


@Configuration @EnableAutoConfiguration @ComponentScan

But @SpringBootApplication is the cleaner, preferred approach.


✅ 9. How does Spring Boot determine if it's a web application?

Spring Boot checks the classpath:

  • If it finds spring-web, spring-webmvc, or ServletContext → it's a web app

  • Then it loads web-specific configurations like:

    • DispatcherServletAutoConfiguration

    • WebMvcAutoConfiguration


✅ 10. What happens if there is no application.properties or .yml?

Spring Boot still starts using default values, such as:

  • Port: 8080

  • Context path: /

  • Embedded H2 database (if JPA is on classpath)

  • Default error page at /error

But defining properties is essential for production-ready apps

 

How Spring Boot Works Internally – Step-by-Step with Real Example

Spring Boot makes it easy to create stand-alone, production-grade Spring applications with minimal configuration. But what really happens when you run a Spring Boot app?

Let’s break it down step-by-step with code and an easy-to-understand flow.


1. Application Entry Point – @SpringBootApplication


@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }
  • @SpringBootApplication is a meta-annotation that includes:

    • @Configuration – Marks this class as a source of bean definitions

    • @EnableAutoConfiguration – Tells Spring Boot to auto-configure beans

    • @ComponentScan – Enables scanning for components (@Component, @Service, etc.)


2. Bootstrapping with SpringApplication.run()

When SpringApplication.run(MyApp.class, args) is called:

  • It creates a SpringApplication instance

  • Prepares the environment and application context

  • Loads application.properties or application.yml

  • Registers listeners and initializers


3. Auto-Configuration Magic

Spring Boot looks into the META-INF/spring.factories file and loads @Configuration classes based on dependencies.

Example:


org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
  • If spring-web is present → WebMvcAutoConfiguration kicks in

  • If spring-boot-starter-data-jpa is present → JPA configurations are loaded


4. Embedded Server Starts Automatically

If it's a web app:

  • Tomcat is auto-configured and started by Spring Boot

  • No need for external WAR deployment


TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();

App runs on http://localhost:8080 by default


5. Bean Scanning and Registration

Spring Boot scans for annotations like:

  • @Component

  • @Service

  • @Repository

  • @RestController

And registers them as beans in the ApplicationContext.


6. Request Dispatching with DispatcherServlet

Spring Boot registers DispatcherServlet automatically for web apps.

Example Controller:


@RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello from Spring Boot!"; } }

Request to /hello is handled by this method.


7. Application Ready

Once the context is loaded, Spring Boot triggers:

  • CommandLineRunner or ApplicationRunner if present

  • Prints a log like:

    Started MyApp in 3.456 seconds

Quick Example: Complete App


@SpringBootApplication public class BlogDemoApplication { public static void main(String[] args) { SpringApplication.run(BlogDemoApplication.class, args); } } @RestController class DemoController { @GetMapping("/") public String home() { return "Welcome to my blog!"; } }

Run it, and your app is live at http://localhost:8080/


Spring Boot Internals – Summary Flow


@SpringBootApplication ↓ SpringApplication.run() ↓ Load Properties & Beans ↓ Auto-Configuration via spring.factories ↓ Embedded Tomcat/Jetty Starts ↓ Component Scanning & Bean Registration ↓ DispatcherServlet Routes Requests ↓ App is Ready to Serve




Friday, 4 April 2025

Java interview questions on throw and throws 


1️⃣ Can we use throw and throws together in the same method?

Answer: Yes, we can use both throw and throws in the same method.

🔹 throws is used in the method signature to indicate that the method may throw an exception.
🔹 throw is used inside the method to actually throw an exception.

Example:


public void processPayment(double amount) throws IllegalArgumentException { if (amount <= 0) { throw new IllegalArgumentException("Amount must be greater than zero"); } System.out.println("Processing payment: " + amount); }

💡 Trick: Many candidates confuse throw and throws, but remember that throw actually throws the exception, while throws just declares it.


2️⃣ Can a method declare throws but never actually throw an exception?

Answer: Yes, a method can declare throws even if it does not explicitly throw an exception inside.

Example:


public void dummyMethod() throws IOException { // No actual exception thrown inside System.out.println("This method declares IOException but does not throw it."); }

💡 Trick: Some interviewers use this question to check if you understand that throws is just a declaration and does not enforce throwing an exception inside the method.


3️⃣ What happens if we write throw without specifying an exception?

Answer: The code will not compile.

🔹 The throw statement must be followed by an exception object.
🔹 Java requires an explicit exception object (of type Throwable or its subclasses).

Incorrect Code:


public void testMethod() { throw; // Compilation error: 'throw' must be followed by an exception instance }

Correct Code:


public void testMethod() { throw new RuntimeException("Something went wrong!"); }

💡 Trick: Java does not allow a bare throw statement without an exception object.


4️⃣ Can we throw multiple exceptions using throw?

Answer: No, throw can only throw one exception at a time.

🔹 If multiple exceptions need to be thrown, they must be handled in separate conditions or wrapped in a combined exception.

Incorrect Code:


throw new IOException(); throw new SQLException(); // Compilation error: unreachable code

Correct Code:


public void checkErrors(boolean condition1, boolean condition2) { if (condition1) { throw new IOException("File error"); } else if (condition2) { throw new SQLException("Database error"); } }

💡 Trick: Unlike throws, which can declare multiple exceptions, throw can only send one exception at a time.


5️⃣ What happens if we declare a throws clause in main()?

Answer: The main() method can declare throws, and any unhandled exception will be propagated to the JVM.

Example:


public static void main(String[] args) throws IOException { readFile("nonexistent.txt"); // Exception not handled, JVM will terminate the program if it occurs } public static void readFile(String filePath) throws IOException { FileReader fr = new FileReader(filePath); // May throw IOException }

💡 Trick: If main() has throws Exception, the program may crash unless handled properly using try-catch.


6️⃣ Why should we prefer custom exceptions over generic exceptions in throw?

Answer: Custom exceptions provide better clarity and help in debugging issues more effectively.

🔹 Instead of throwing a generic exception like Exception or RuntimeException, we should create our own meaningful exceptions.

Example:


class InsufficientBalanceException extends Exception { public InsufficientBalanceException(String message) { super(message); } } public void withdraw(double amount) throws InsufficientBalanceException { if (amount > balance) { throw new InsufficientBalanceException("Balance is too low!"); } balance -= amount; }

💡 Trick: A well-defined exception name (like InsufficientBalanceException) makes debugging much easier than throw new RuntimeException("Something went wrong").


7️⃣ What happens if we throw an exception inside a finally block?

Answer: If an exception is thrown inside the finally block, it overrides any previous exceptions thrown in try or catch.

Example:


public void testMethod() { try { throw new IOException("Try block exception"); } catch (Exception e) { System.out.println("Caught: " + e.getMessage()); } finally { throw new RuntimeException("Finally block exception"); // Overrides previous exception } }

Output:


Exception in thread "main" java.lang.RuntimeException: Finally block exception

💡 Trick: Any exception in finally will suppress exceptions from try and catch, so avoid throwing exceptions from finally unless necessary.


8️⃣ What happens if a checked exception is thrown but not declared using throws or handled using try-catch?

Answer: The code will not compile because Java enforces checked exceptions to be either:

  1. Handled using try-catch

  2. Declared using throws

Incorrect Code (Compilation Error):


public void readFile() { FileReader fr = new FileReader("file.txt"); // Compilation error: Unhandled exception }

Correct Code:


public void readFile() throws IOException { FileReader fr = new FileReader("file.txt"); // No compilation error now }

💡 Trick: Java forces you to handle checked exceptions, unlike unchecked exceptions.


9️⃣ Can we override a method and remove throws from the overridden method?

Answer: Yes, a subclass can remove the throws clause while overriding a method, but it cannot declare new broader exceptions than the superclass.

Example:


class Parent { public void display() throws IOException { System.out.println("Parent method"); } } class Child extends Parent { @Override public void display() { // Removed 'throws IOException' System.out.println("Child method"); } }

💡 Trick: A subclass can handle exceptions internally and remove throws, but it cannot declare new broader exceptions (e.g., Exception instead of IOException).


🔟 Can we use throws with finally?

Answer: Yes, but the finally block executes before the method exits, even if an exception is thrown.

Example:


public void riskyMethod() throws IOException { try { throw new IOException("Try block exception"); } finally { System.out.println("Finally block executed"); } }

💡 Trick: finally will always execute before the exception propagates to the caller.


🔥 Quick Recap (for Interviews)

throwActually throws an exception.
throwsDeclares that a method may throw an exception.
throw requires an exception object.
throws does not require an object—just a declaration.
✅ A method can throws multiple exceptions but can only throw one at a time.
✅ Exceptions in finally override exceptions from try-catch.

 

throw vs throws in Java (With Real-Life Examples)

Java provides robust exception handling using try, catch, throw, throws, and finally. Among these, throw and throws often confuse beginners. In this post, we'll break down their real-time differences, practical syntax, and usage in real-world Java projects.


🔹 1. Basic Difference

Feature throw throws
Purpose Used to throw an exception manually Declares that a method can throw an exception
Position Used inside a method Declared with method signature
Syntax throw new ExceptionType("msg"); public void method() throws ExceptionType {}
Number Allowed Only one exception object can be thrown Can declare multiple exceptions
Object Required Yes, needs an object of Throwable class No object required

🔹 2. Syntax Examples

// Using throw
public void validateAge(int age) {
    if (age < 18) {
        throw new IllegalArgumentException("Age must be 18 or above");
    }
}
// Using throws
public void readFile(String filePath) throws IOException {
    FileReader fr = new FileReader(filePath); // might throw IOException
}

🔹 3. Real-Time Project Example: Banking System

Let’s assume we are building a banking microservice.

throw Example

public void withdraw(double amount) {
    if (amount > balance) {
        throw new InsufficientFundsException("Insufficient balance");
    }
    balance -= amount;
}
  • Use Case: You manually check a condition and throw an exception to stop the process if it fails.

  • Real-Time Benefit: Helps enforce business rules clearly (like balance checks).

throws Example

public void processLoanApplication(String filePath) throws IOException {
    // Reading a document
    FileInputStream fis = new FileInputStream(filePath);
    // Business logic
}
  • Use Case: You’re dealing with checked exceptions from Java IO or JDBC APIs.

  • Real-Time Benefit: Declares that the caller must handle or propagate it further.


🔹 4. Combined Example

public void applyForLoan(String userId, String documentPath) throws IOException {
    if (!isEligible(userId)) {
        throw new IllegalArgumentException("User not eligible for loan");
    }

    processLoanApplication(documentPath); // throws IOException
}

➕ Explanation:

  • throw is used for business rule failure.

  • throws is used for possible checked exception from external resources (file, DB, etc).


🔹 5. Best Practices

  • Use throw when a method detects an exceptional situation and wants to fail fast.

  • Use throws to delegate responsibility to the caller for handling expected exceptions.

  • Always prefer custom exceptions (like InsufficientFundsException) for clear error handling.


💡 Fun Tip (for Reels or Shorts):

throw is like yelling: 'Hey! Something’s wrong!' 🎯
throws is like politely saying: 'Hey caller, you might want to handle this issue.' 🤝”


🔚 Conclusion

Understanding the difference between throw and throws is crucial for writing clean and effective Java code. Whether you're building microservices, reading files, or validating user input, knowing when to use throw or throws ensures your application handles errors gracefully.

Happy coding! 🚀

 

🚀 Top Tricky HashMap Questions & Answers for MNC Interviews

🌟 1. Can we store a null key in HashMap and ConcurrentHashMap?

✅ Answer:

  • HashMap allows one null key.

  • ConcurrentHashMap ❌ does not allow null keys.

Example:

Map<String, String> map = new HashMap<>();
map.put(null, "value");  // ✅ Works fine

Map<String, String> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put(null, "value");  // ❌ Throws NullPointerException

🌟 2. What happens when two keys have the same hashCode()?

✅ Answer:

This is called a hash collision.

  • Java stores both keys in the same bucket but differentiates them using equals().

  • In Java 7, it used Linked List chaining.

  • In Java 8, if collisions exceed 8, it converts the linked list to a Red-Black Tree to improve O(n)O(log n).


🌟 3. What happens if hashCode() is different but equals() is true?

✅ Answer:

This should never happen because Java assumes:

🚨 If two objects are equal (equals() returns true), they must have the same hashCode().
Otherwise, Java will store them in different buckets, breaking the contract.

Example:

@Override
public int hashCode() { return 123; }  // ❌ Wrong: Every object gets the same hash
@Override
public boolean equals(Object obj) { return true; } // ❌ Bad practice

🔴 This can cause data inconsistency and difficult debugging issues.


🌟 4. What is the worst-case time complexity of HashMap.get()?

✅ Answer:

Scenario Java 7 (O(n)) Java 8 (O(log n))
Best case O(1) (Direct bucket access) O(1)
Worst case O(n) (All elements in same bucket, linked list traversal) O(log n) (Tree traversal in Red-Black Tree)

🚩 Real-world trap: If your hashCode() implementation is bad (returns same value for all keys), performance degrades to O(n).


🌟 5. Can a HashMap have duplicate keys?

✅ Answer:

📝 No. If you insert a duplicate key, it overwrites the existing value.

Map<String, String> map = new HashMap<>();
map.put("fruit", "apple");
map.put("fruit", "banana");
System.out.println(map.get("fruit"));  // Output: banana (replaced apple)

🌟 6. What happens if put() is called during iteration?

✅ Answer:

It throws ConcurrentModificationException.

for (Map.Entry<String, String> entry : map.entrySet()) {
   map.put("newKey", "newValue");  // ❌ ConcurrentModificationException
}

📝 How to avoid?
👉 Use Iterator.remove() instead of map.put() during iteration.
👉 Use ConcurrentHashMap if multi-threading is needed.


🌟 7. What is the default capacity of a HashMap?

✅ Answer:

  • Default capacity: 16

  • Default load factor: 0.75

  • Resize happens when size reaches 16 * 0.75 = 12

📝 How to avoid frequent resizing?
🚀 Initialize HashMap with correct size using:

Map<String, String> map = new HashMap<>(128);

🌟 8. What happens if two threads modify a HashMap at the same time?

✅ Answer:

💀 Data corruption or infinite loop (Java 7)
💀 Lost updates (Java 8)

📝 Solution?
👉 Use ConcurrentHashMap for multi-threading.
👉 Or wrap with Collections.synchronizedMap() (slower).


🌟 9. How does ConcurrentHashMap work internally?

✅ Answer:

👉 Before Java 8: Used segments (mini hash tables)
👉 In Java 8+:

  • No segments

  • Uses bucket-level locking

  • Uses CAS (Compare-And-Swap) for atomic updates

  • Avoids full map locking → much faster


🌟 10. Can we use a mutable object as a HashMap key?

✅ Answer:

🚨 Bad idea! If key’s hashCode() changes, it gets lost in the map.

Example:

class Key {
    int id;
    Key(int id) { this.id = id; }
    @Override
    public int hashCode() { return id; }
}
Map<Key, String> map = new HashMap<>();
Key key = new Key(10);
map.put(key, "value");

key.id = 20;  // ❌ Changing key's hashCode!
System.out.println(map.get(key)); // Output: null ❌ LOST ENTRY!

📝 Solution: Use immutable objects as keys (like String or Integer).



 

🔥 Top 15+ Tricky HashMap Interview Questions (With Smart Answers)

Whether you're preparing for interviews at Amazon, Google, TCS, Infosys, Wipro, or Capgemini, or simply leveling up your Java skills, understanding HashMap internals is a must. Let's explore the trickiest HashMap interview questions—with crisp, smart answers that impress interviewers.


🚀 1. Can HashMap have null keys and null values?

🧠 Trick: Many think null is never allowed.

✅ Answer:

  • Yes, 1 null key is allowed.

  • Multiple null values are allowed.


HashMap<String, String> map = new HashMap<>(); map.put(null, "value"); // ✅ null key map.put("a", null); // ✅ null value

🚀 2. What happens when you insert duplicate keys?

🧠 Trick: Interviewers expect you to explain key replacement.

✅ Answer:
The latest value overrides the old value for the same key.


map.put("fruit", "apple"); map.put("fruit", "mango"); System.out.println(map.get("fruit")); // Output: mango

🚀 3. Is HashMap thread-safe?

🧠 Trick: If you say yes — that’s a red flag.

✅ Answer:
No, it is not thread-safe. Use:

  • Collections.synchronizedMap() (slower, locks whole map)

  • ConcurrentHashMap (preferred in multi-threading)


🚀 4. Can two unequal objects have the same hash code?

🧠 Trick: This is about collision handling.

✅ Answer:
Yes! It's called a hash collision.


System.out.println("FB".hashCode()); // 2236 System.out.println("Ea".hashCode()); // 2236

Java handles collisions using:

  • Linked List (Java 7)

  • Red-Black Tree (Java 8+)


🚀 5. What happens internally when put() is called?

🧠 Trick: They want step-by-step internal flow.

✅ Answer (Java 8):

  1. Compute hash using hashCode()

  2. Map hash to bucket index

  3. Check if key exists using equals()

  4. If exists → replace value

  5. If not → create new Node

  6. If collisions > 8 → convert bucket to Red-Black Tree


🚀 6. What is the load factor?

🧠 Trick: Misunderstanding load factor leads to wrong resizing logic.

✅ Answer:
Load factor = threshold to resize

  • Default = 0.75f

  • Resize happens when:
    current size ≥ capacity * loadFactor


🚀 7. What is rehashing?

🧠 Trick: Interviewers want to test your understanding of resizing.

✅ Answer:
When capacity threshold is crossed, HashMap creates a new array (double size) and repositions all existing keys (rehashing).


🚀 8. Can HashMap key be mutable?

🧠 Trick: Many devs unknowingly use mutable objects as keys.

✅ Answer:
Technically yes, but it's a bad practice.
If a key’s hashCode changes after insertion, you won't be able to retrieve the value.


🚀 9. Difference between HashMap, TreeMap, and LinkedHashMap?

FeatureHashMapTreeMapLinkedHashMap
Ordering❌ No order✅ Sorted✅ Insertion order
Null Key✅ One❌ Not allowed✅ One
Thread-safe❌ No❌ No❌ No

🚀 10. What is treeification in Java 8?

🧠 Trick: This tests Java 8 internal knowledge.

✅ Answer:
If one bucket has more than 8 entries and capacity ≥ 64, Java 8 converts the bucket into a Red-Black Tree → improves lookup to O(log n)


🚀 11. What’s the worst-case time complexity of get() and put()?

ScenarioJava 7Java 8
Best case (no collision)O(1)O(1)
Worst case (collision)O(n)O(log n)

🚀 12. What causes ConcurrentModificationException?

🧠 Trick: Simple-looking question, but many fail it.

✅ Answer:
Modifying a HashMap while iterating it using for-each loop (without Iterator’s remove()).

for (Map.Entry entry : map.entrySet()) { map.put("x", "y"); // ❌ Throws ConcurrentModificationException }

🚀 13. Can initial capacity be set to a large value like Integer.MAX_VALUE?

✅ Answer:
You can, but it’s risky:

  • Might throw OutOfMemoryError

  • Wastes memory if not filled


🚀 14. Why should hashCode() and equals() be overridden for custom keys?

🧠 Trick: Real-world trap question.

✅ Answer:
HashMap uses:

  • hashCode() → to find bucket

  • equals() → to find key in that bucket

If not overridden, keys won’t match, leading to unexpected behavior.


🚀 15. Can a HashMap have two keys with same hash code?

✅ Answer:
Yes. HashMap handles collisions using chaining.


Key1.hashCode() == Key2.hashCode() // true Key1.equals(Key2) // false → both exist in same bucket

 Top 10 Java Interview Questions and Answers for 2025

Preparing for a Java interview in 2025? The Java ecosystem continues to evolve, and companies seek developers with strong problem-solving skills and up-to-date knowledge. Here are the top 10 Java interview questions with answers to help you ace your next interview.


1. What are the main features introduced in Java 17?

Answer: Java 17 (LTS) introduced several key features, including:

  • Sealed Classes

  • Pattern Matching for switch

  • Strongly Encapsulated JDK Internals

  • New macOS Rendering Pipeline

  • Deprecation of Security Manager

Example:

sealed class Vehicle permits Car, Bike {}
final class Car extends Vehicle {}
final class Bike extends Vehicle {}

2. What is the difference between var, final var, and record in Java?

Answer:

  • var is used for local variable type inference.

  • final var ensures that the variable cannot be reassigned.

  • record is a new type for immutable data classes.

Example:

record Person(String name, int age) {}
Person p = new Person("Alice", 30);
System.out.println(p.name()); // Alice

3. How does Java handle memory management?

Answer: Java uses Automatic Garbage Collection (GC) with different collectors like:

  • G1 GC (Default since Java 9)

  • ZGC (Low-latency GC introduced in Java 11)

  • Shenandoah GC (Highly concurrent GC)


4. Explain the difference between ExecutorService and ForkJoinPool.

Answer:

  • ExecutorService is for managing a fixed pool of threads.

  • ForkJoinPool is for parallel processing and divide-and-conquer algorithms.

Example:

ForkJoinPool pool = new ForkJoinPool();

5. What are Virtual Threads in Java?

Answer: Virtual Threads (Project Loom) provide lightweight, scalable concurrency.

Example:

Thread.startVirtualThread(() -> System.out.println("Hello Virtual Threads!"));

6. What is the difference between CompletableFuture and Reactive Streams?

Answer:

  • CompletableFuture handles asynchronous programming.

  • Reactive Streams (Project Reactor) provides backpressure support.


7. How to implement a Kafka consumer in Java?

Answer:

Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
Consumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("my-topic"));

8. What is the difference between HashMap and ConcurrentHashMap?

Answer:

  • HashMap is not thread-safe.

  • ConcurrentHashMap is optimized for concurrent read/write operations.


9. How to optimize performance in Spring Boot applications?

Answer:

  • Use @Transactional to manage DB transactions efficiently.

  • Enable caching with @Cacheable.

  • Use Connection Pooling (HikariCP).


10. What are the best practices for writing clean Java code?

Answer:

  • Follow SOLID principles.

  • Use meaningful variable names.

  • Avoid redundant code (DRY principle).

  • Use logging frameworks (Log4j, SLF4J).


Happy learning....

What is map in java 8

In Java 8, the map method is part of the Stream API, and it is used for transforming each element of a stream using a given function. It applies the provided function to each element in the stream and produces a new stream of the transformed elements. The original stream remains unchanged.

Here’s a basic example using map to convert a stream of strings to uppercase:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MapExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "orange");

// Using map to convert each element to uppercase
List<String> uppercasedWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());

// Print the transformed elements
System.out.println(uppercasedWords);
}
}
  1. words.stream() converts the List of strings (words) into a stream.
  2. .map(String::toUpperCase) applies the toUpperCase method to each element of the stream, transforming each string to its uppercase version.
  3. .collect(Collectors.toList()) collects the transformed elements into a new List.

The result is a new List containing the uppercase versions of the original strings.

You can use map with any function that transforms the elements of the stream. It is a powerful and versatile operation, commonly used for tasks like extracting specific properties from objects, transforming data, or performing calculations on each element of the stream.

see another example of map in java8

  int[] num = {1, 2, 3, 4, 5};

Integer[] result = Arrays.stream(num)
.map(x -> x * 2)
.boxed()
.toArray(Integer[]::new);

System.out.println(Arrays.asList(result));

output- [2, 4, 6, 8, 10]


Happy learning...