<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hemanth Kumar N V on Medium]]></title>
        <description><![CDATA[Stories by Hemanth Kumar N V on Medium]]></description>
        <link>https://medium.com/@hemanthcse1?source=rss-bbdb1d68a3c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FPIugmYP6aVgZsevtj6f_g.jpeg</url>
            <title>Stories by Hemanth Kumar N V on Medium</title>
            <link>https://medium.com/@hemanthcse1?source=rss-bbdb1d68a3c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 21:01:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hemanthcse1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[DispatcherServlet in Spring Boot]]></title>
            <link>https://hemanthcse1.medium.com/dispatcherservlet-in-spring-boot-9e6f7fdc7a45?source=rss-bbdb1d68a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e6f7fdc7a45</guid>
            <category><![CDATA[dispatcherservlet]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Hemanth Kumar N V]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 15:32:33 GMT</pubDate>
            <atom:updated>2024-06-19T15:32:33.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIy6EEdlrO0RQelinI20aQ.png" /></figure><p>In Spring Boot, the DispatcherServlet retains its central role as the front controller for handling all HTTP requests and responses within a web application. However, Spring Boot simplifies the configuration and management of the DispatcherServlet compared to traditional Spring MVC applications.</p><h4>Key Features and Functions</h4><ol><li><strong>Centralized Request Handling</strong>: The DispatcherServlet intercepts all incoming requests and delegates them to the appropriate controllers based on URL patterns and request mappings.</li><li><strong>Pre-processing and Post-processing</strong>: The DispatcherServlet allows for pre-processing and post-processing of requests via interceptors, enabling tasks like logging, authentication, and data manipulation.</li><li><strong>View Resolution</strong>: It resolves logical view names returned by controllers to actual views, such as JSP, Thymeleaf, or other templating engines.</li><li><strong>Exception Handling</strong>: The DispatcherServlet handles exceptions that occur during request processing, providing a consistent error-handling mechanism through configured exception resolvers.</li></ol><h4>Configuration in Spring Boot</h4><p>Spring Boot automatically configures the DispatcherServlet without requiring explicit definitions in XML or Java classes. This auto-configuration is part of Spring Boot&#39;s ability to reduce boilerplate code and simplify setup.</p><p><strong>Default Configuration</strong>: By default, Spring Boot registers the DispatcherServlet and maps it to the root URL pattern (/). This means it will handle all incoming requests.</p><h4>Customizing the DispatcherServlet</h4><p>While Spring Boot provides sensible defaults, you can customize the DispatcherServlet if needed.</p><ol><li><strong>Changing the DispatcherServlet URL Pattern</strong>:</li><li>You can customize the URL pattern by configuring the spring.mvc.servlet.path property in the application.properties file:</li></ol><pre>spring.mvc.servlet.path=/api</pre><p>This configuration changes the default URL pattern from / to /api, so the DispatcherServlet will handle requests starting with /api.</p><p>2. <strong>Customizing the DispatcherServlet Bean</strong>:</p><p>If you need to customize the DispatcherServlet bean directly, you can define a DispatcherServlet bean in a configuration class:</p><pre>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.servlet.DispatcherServlet;<br><br>@Configuration<br>public class WebConfig {<br><br>    @Bean<br>    public DispatcherServlet dispatcherServlet() {<br>        DispatcherServlet dispatcherServlet = new DispatcherServlet();<br>        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);<br>        return dispatcherServlet;<br>    }<br>}</pre><p>Here, we customize the DispatcherServlet to throw an exception if no handler is found for a request.</p><p>3. <strong>Customizing the DispatcherServlet Registration</strong>:</p><p>You can also customize how the DispatcherServlet is registered in the ServletContext:</p><pre>import org.springframework.boot.web.servlet.ServletRegistrationBean;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.servlet.DispatcherServlet;<br><br>@Configuration<br>public class WebConfig {<br><br>    @Bean<br>    public ServletRegistrationBean&lt;DispatcherServlet&gt; dispatcherServletRegistration() {<br>        DispatcherServlet dispatcherServlet = new DispatcherServlet();<br>        ServletRegistrationBean&lt;DispatcherServlet&gt; registrationBean = new ServletRegistrationBean&lt;&gt;(dispatcherServlet, &quot;/custom/*&quot;);<br>        registrationBean.setName(&quot;customDispatcher&quot;);<br>        return registrationBean;<br>    }<br>}</pre><p>This example registers the DispatcherServlet with a custom URL pattern /custom/* and a custom name customDispatcher.</p><h4>Using Interceptors with DispatcherServlet in Spring Boot</h4><p>Interceptors can be used in Spring Boot in a manner similar to traditional Spring MVC applications. Define the interceptor and register it using WebMvcConfigurer.</p><p><strong>Step 1: Define the Interceptor</strong></p><pre>import org.springframework.web.servlet.HandlerInterceptor;<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;<br><br>public class CustomInterceptor implements HandlerInterceptor {<br><br>    @Override<br>    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<br>        System.out.println(&quot;Pre Handle method is Calling&quot;);<br>        return true;<br>    }<br><br>    @Override<br>    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {<br>        System.out.println(&quot;Post Handle method is Calling&quot;);<br>    }<br><br>    @Override<br>    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {<br>        System.out.println(&quot;Request and Response is completed&quot;);<br>    }<br>}</pre><p>Step 2: Register the Interceptor</p><pre>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.servlet.config.annotation.InterceptorRegistry;<br>import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;<br><br>@Configuration<br>public class WebConfig implements WebMvcConfigurer {<br><br>    @Override<br>    public void addInterceptors(InterceptorRegistry registry) {<br>        registry.addInterceptor(new CustomInterceptor())<br>                .addPathPatterns(&quot;/api/**&quot;)<br>                .excludePathPatterns(&quot;/api/login&quot;, &quot;/api/register&quot;);<br>    }<br>}</pre><h4>Conclusion</h4><p>The DispatcherServlet in Spring Boot simplifies the process of building web applications by providing automatic configuration and reducing the need for boilerplate code. It remains a crucial component, serving as the front controller that manages all HTTP requests and responses. With the ability to customize its behavior and integrate with other Spring features seamlessly, the DispatcherServlet helps developers build robust and maintainable web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e6f7fdc7a45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Interceptors]]></title>
            <link>https://hemanthcse1.medium.com/spring-interceptors-1692f43e5b4e?source=rss-bbdb1d68a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1692f43e5b4e</guid>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[learning-and-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Hemanth Kumar N V]]></dc:creator>
            <pubDate>Mon, 17 Jun 2024 15:32:34 GMT</pubDate>
            <atom:updated>2024-06-17T15:32:34.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIy6EEdlrO0RQelinI20aQ.png" /></figure><p>Spring Interceptors are a powerful mechanism provided by the Spring MVC framework to intercept HTTP requests and responses. They are used to perform operations before and after the execution of controller methods. Interceptors can be applied to pre-process and post-process requests in a web application, allowing developers to implement cross-cutting concerns like logging, authentication, authorization, and more.</p><h4>Key Concepts and Components</h4><ol><li><strong>HandlerInterceptor Interface</strong>: The HandlerInterceptor interface defines three methods that need to be implemented:</li></ol><ul><li>boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler): This method is called before the actual handler (controller method) is executed. It can be used to perform tasks such as authentication and logging. If it returns true, the request is allowed to proceed; if it returns false, the request processing is stopped.</li><li>void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView): This method is called after the handler method is executed, but before the view is rendered. It can be used to add additional attributes to the model or to manipulate the ModelAndView object.</li><li>void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex): This method is called after the complete request has finished. It can be used for resource cleanup, logging, and handling exceptions.</li></ul><p><strong>2. HandlerInterceptorAdapter Class</strong>: The HandlerInterceptorAdapter class is a convenient abstract class that provides default implementations of the HandlerInterceptor methods. Developers can extend this class and override only the methods they are interested in.</p><p><strong>3. Configuring Interceptors</strong>: Interceptors are configured in the Spring MVC configuration file. They can be applied to specific URL patterns or to all requests.</p><h4>Example: Implementing and Configuring an Interceptor</h4><p><strong>Step 1: Create an Interceptor</strong></p><pre>import org.springframework.web.servlet.HandlerInterceptor;<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;<br><br>public class CustomInterceptor implements HandlerInterceptor {<br><br>    @Override<br>    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<br>        System.out.println(&quot;Pre Handle method is Calling&quot;);<br>        // Perform operations like logging or authentication here<br>        return true; // Proceed with the request<br>    }<br><br>    @Override<br>    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {<br>        System.out.println(&quot;Post Handle method is Calling&quot;);<br>        // Perform operations like adding attributes to the model here<br>    }<br><br>    @Override<br>    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {<br>        System.out.println(&quot;Request and Response is completed&quot;);<br>        // Perform cleanup operations here<br>    }<br>}</pre><p><strong>Step 2: Configure the Interceptor</strong></p><p>In the Spring MVC configuration file (usually WebConfig.java or applicationContext.xml), you need to register the interceptor:</p><p><strong>Java-based Configuration</strong>:</p><pre>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.servlet.config.annotation.InterceptorRegistry;<br>import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;<br><br>@Configuration<br>public class WebConfig implements WebMvcConfigurer {<br><br>    @Override<br>    public void addInterceptors(InterceptorRegistry registry) {<br>        registry.addInterceptor(new CustomInterceptor())<br>                .addPathPatterns(&quot;/api/**&quot;)  // Apply interceptor to specific URL patterns<br>                .excludePathPatterns(&quot;/api/login&quot;, &quot;/api/register&quot;);  // Exclude specific URL patterns<br>    }<br>}</pre><p><strong>XML-based Configuration</strong>:</p><pre>&lt;mvc:interceptors&gt;<br>    &lt;mvc:interceptor&gt;<br>        &lt;mvc:mapping path=&quot;/api/**&quot;/&gt;<br>        &lt;mvc:exclude-mapping path=&quot;/api/login&quot;/&gt;<br>        &lt;mvc:exclude-mapping path=&quot;/api/register&quot;/&gt;<br>        &lt;bean class=&quot;com.example.CustomInterceptor&quot;/&gt;<br>    &lt;/mvc:interceptor&gt;<br>&lt;/mvc:interceptors&gt;</pre><h4>Use Cases for Interceptors</h4><ol><li><strong>Logging</strong>:</li></ol><ul><li>Log incoming requests and outgoing responses.</li><li>Measure the execution time of requests.</li></ul><p><strong>2. Authentication and Authorization</strong>:</p><ul><li>Check if the user is authenticated before allowing access to certain endpoints.</li><li>Verify user permissions and roles.</li></ul><p><strong>3. Data Manipulation</strong>:</p><ul><li>Add or modify request and response headers.</li><li>Transform data before it reaches the controller or before it is sent to the client.</li></ul><p><strong>4. Resource Management</strong>:</p><ul><li>Open and close resources, such as database connections or file streams.</li><li>Manage transactions or perform cleanup operations.</li></ul><p><strong>5. Performance Monitoring</strong>:</p><ul><li>Collect metrics for performance monitoring and analysis.</li><li>Track request processing times and system load.</li></ul><h4>Advantages of Using Interceptors</h4><ul><li><strong>Separation of Concerns</strong>: Interceptors allow you to separate cross-cutting concerns (like logging and security) from the main business logic.</li><li><strong>Reusability</strong>: Common logic implemented in interceptors can be reused across multiple controllers and endpoints.</li><li><strong>Centralized Control</strong>: Interceptors provide a centralized way to manage pre-processing and post-processing of requests.</li></ul><p>For a practical implementation example, you can refer to the <a href="https://github.com/hemanthcse1/spring-things/tree/feature/interceptors">Spring Interceptors Example on GitHub</a>.</p><h4>Conclusion</h4><p>Spring Interceptors are a powerful feature that enhances the flexibility and maintainability of web applications. By using interceptors, developers can efficiently handle cross-cutting concerns, improving code modularity and separation of concerns. With a clear understanding of how to implement and configure interceptors, developers can leverage this feature to build robust and scalable web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1692f43e5b4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interfaces in Java]]></title>
            <link>https://hemanthcse1.medium.com/interfaces-in-java-e3a0c65315fa?source=rss-bbdb1d68a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3a0c65315fa</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interfaces-in-java]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <dc:creator><![CDATA[Hemanth Kumar N V]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 15:32:24 GMT</pubDate>
            <atom:updated>2024-06-03T15:32:24.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIy6EEdlrO0RQelinI20aQ.png" /></figure><p>An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors. They are used to specify a set of methods that a class must implement. An interface is a way to achieve abstraction and multiple inheritance in Java.</p><h3>Characteristics of Interfaces</h3><ol><li><strong>Abstract Methods</strong>: Interfaces can contain abstract methods (methods without a body). These methods must be implemented by any class that implements the interface.</li></ol><pre>interface Drivable {<br>    void drive();<br>}</pre><ol><li><strong>Default Methods</strong>: Since Java 8, interfaces can include default methods (methods with a body). These methods provide default behavior that implementing classes can use or override.</li></ol><pre>interface Vehicle {<br>    default void start() {<br>        System.out.println(&quot;Vehicle is starting&quot;);<br>    }<br>}</pre><ol><li><strong>Static Methods</strong>: Interfaces can also contain static methods. These methods belong to the interface class and can be called independently of any objects.</li></ol><pre>interface Utility {<br>    static void printMessage() {<br>        System.out.println(&quot;Static method in interface&quot;);<br>    }<br>}</pre><ol><li><strong>Constants</strong>: Fields in interfaces are implicitly public, static, and final, meaning they are constants.</li></ol><pre>interface Config {<br>    int MAX_VALUE = 100;<br>}</pre><ol><li><strong>Multiple Inheritance</strong>: A class can implement multiple interfaces, providing a way to achieve multiple inheritance, which is not possible with classes alone.</li></ol><pre>class Car implements Drivable, Vehicle {<br>    public void drive() {<br>        System.out.println(&quot;Car is driving&quot;);<br>    }<br>}</pre><h3>Why Use Interfaces</h3><ol><li><strong>Abstraction</strong>: Interfaces allow you to define methods that must be implemented by classes, without providing the implementation. This enforces a contract for the implementing classes.</li><li><strong>Multiple Inheritance</strong>: Since Java does not support multiple inheritance of classes, interfaces provide a way to achieve multiple inheritance by allowing a class to implement multiple interfaces.</li><li><strong>Loose Coupling</strong>: Interfaces help in reducing the dependency of classes on concrete implementations, promoting loose coupling.</li><li><strong>Testability</strong>: Interfaces make it easier to write testable code by allowing the use of mock implementations.</li><li><strong>Design Flexibility</strong>: Interfaces provide flexibility in the design of systems by allowing various implementations of a given interface.</li></ol><h3>Detailed Example</h3><p>Consider a real-world scenario where you have a media player application. You want to support different types of media players, such as audio players and video players. Each type of player will have some common methods, such as play, pause, and stop, but the implementation of these methods will vary depending on the type of player.</p><h4>Step 1: Define the Interface</h4><pre>interface MediaPlayer {<br>    void play();<br>    void pause();<br>    void stop();<br>}</pre><h4>Step 2: Implement the Interface in Concrete Classes</h4><p>Audio Player Implementation</p><pre>public class AudioPlayer implements MediaPlayer {<br>    @Override<br>    public void play() {<br>        System.out.println(&quot;Audio player is playing&quot;);<br>    }<br><br>    @Override<br>    public void pause() {<br>        System.out.println(&quot;Audio player is paused&quot;);<br>    }<br><br>    @Override<br>    public void stop() {<br>        System.out.println(&quot;Audio player is stopped&quot;);<br>    }<br>}</pre><p>Video Player Implementation</p><pre>public class VideoPlayer implements MediaPlayer {<br>    @Override<br>    public void play() {<br>        System.out.println(&quot;Video player is playing&quot;);<br>    }<br><br>    @Override<br>    public void pause() {<br>        System.out.println(&quot;Video player is paused&quot;);<br>    }<br><br>    @Override<br>    public void stop() {<br>        System.out.println(&quot;Video player is stopped&quot;);<br>    }<br>}</pre><h4>Step 3: Use the Interface in the Application</h4><pre>public class MediaApp {<br>    public static void main(String[] args) {<br>        MediaPlayer audioPlayer = new AudioPlayer();<br>        MediaPlayer videoPlayer = new VideoPlayer();<br><br>        audioPlayer.play();   // Output: Audio player is playing<br>        audioPlayer.pause();  // Output: Audio player is paused<br>        audioPlayer.stop();   // Output: Audio player is stopped<br><br>        videoPlayer.play();   // Output: Video player is playing<br>        videoPlayer.pause();  // Output: Video player is paused<br>        videoPlayer.stop();   // Output: Video player is stopped<br>    }<br>}</pre><h3>Detailed Explanation</h3><ol><li><strong>Defining Common Behavior</strong>: The MediaPlayer interface defines three methods (play, pause, and stop) that must be implemented by any class that claims to be a media player. This enforces a contract that all media players will have these functionalities.</li><li><strong>Implementing Specific Behavior</strong>: The AudioPlayer and VideoPlayer classes provide specific implementations for the methods defined in the MediaPlayer interface. Each class has its own way of handling the play, pause, and stop actions.</li><li><strong>Polymorphism</strong>: The application code (MediaApp) can use the MediaPlayer interface type to refer to both AudioPlayer and VideoPlayer objects. This allows for polymorphic behavior, where the same interface type can point to different implementations.</li><li><strong>Loose Coupling</strong>: The use of the MediaPlayer interface decouples the application logic from the specific implementations of the media players. This makes the code more flexible and easier to maintain.</li><li><strong>Extensibility</strong>: Adding support for new types of media players is easy. You simply create a new class that implements the MediaPlayer interface and provide the specific implementation for the methods. The existing application code remains unchanged.</li></ol><h3>Advanced Features of Interfaces</h3><h4>Default Methods</h4><p>Default methods allow interfaces to provide methods with a body. This enables adding new methods to interfaces without breaking the existing implementation of those interfaces.</p><pre>interface Vehicle {<br>    void start();<br>    default void stop() {<br>        System.out.println(&quot;Vehicle is stopping&quot;);<br>    }<br>}<br><br>class Car implements Vehicle {<br>    @Override<br>    public void start() {<br>        System.out.println(&quot;Car is starting&quot;);<br>    }<br>}<br><br>public class Test {<br>    public static void main(String[] args) {<br>        Car car = new Car();<br>        car.start();  // Output: Car is starting<br>        car.stop();   // Output: Vehicle is stopping<br>    }<br>}</pre><h4>Static Methods</h4><p>Static methods in interfaces are similar to static methods in classes. They belong to the interface class and can be called independently of any objects.</p><pre>interface Utility {<br>    static void printMessage() {<br>        System.out.println(&quot;Static method in interface&quot;);<br>    }<br>}<br><br>public class Test {<br>    public static void main(String[] args) {<br>        Utility.printMessage();  // Output: Static method in interface<br>    }<br>}</pre><h3><strong>Real-Time Example of Interface in Java</strong></h3><p>Let’s consider a real-time example of an interface in the context of a payment processing system for an e-commerce application. In this system, we have different payment methods like Credit Card, PayPal, and Bank Transfer. Each payment method will have common actions such as pay, refund, and generateReceipt.</p><h3>Step 1: Define the Interface</h3><p>The PaymentProcessor interface will define the common methods that all payment methods must implement.</p><pre>public interface PaymentProcessor {<br>    void pay(double amount);<br>    void refund(double amount);<br>    String generateReceipt();<br>}</pre><h3>Step 2: Implement the Interface in Concrete Classes</h3><h4>Credit Card Payment Implementation</h4><pre>public class CreditCardPayment implements PaymentProcessor {<br>    private String cardNumber;<br><br>    public CreditCardPayment(String cardNumber) {<br>        this.cardNumber = cardNumber;<br>    }<br><br>    @Override<br>    public void pay(double amount) {<br>        // Logic for processing credit card payment<br>        System.out.println(&quot;Processing credit card payment of $&quot; + amount + &quot; for card &quot; + cardNumber);<br>    }<br><br>    @Override<br>    public void refund(double amount) {<br>        // Logic for refunding credit card payment<br>        System.out.println(&quot;Refunding $&quot; + amount + &quot; to credit card &quot; + cardNumber);<br>    }<br><br>    @Override<br>    public String generateReceipt() {<br>        // Logic for generating receipt<br>        return &quot;Receipt for credit card payment to card &quot; + cardNumber;<br>    }<br>}</pre><h4>PayPal Payment Implementation</h4><pre>public class PayPalPayment implements PaymentProcessor {<br>    private String email;<br><br>    public PayPalPayment(String email) {<br>        this.email = email;<br>    }<br><br>    @Override<br>    public void pay(double amount) {<br>        // Logic for processing PayPal payment<br>        System.out.println(&quot;Processing PayPal payment of $&quot; + amount + &quot; for email &quot; + email);<br>    }<br><br>    @Override<br>    public void refund(double amount) {<br>        // Logic for refunding PayPal payment<br>        System.out.println(&quot;Refunding $&quot; + amount + &quot; to PayPal account &quot; + email);<br>    }<br><br>    @Override<br>    public String generateReceipt() {<br>        // Logic for generating receipt<br>        return &quot;Receipt for PayPal payment to account &quot; + email;<br>    }<br>}</pre><h4>Bank Transfer Payment Implementation</h4><pre>public class BankTransferPayment implements PaymentProcessor {<br>    private String bankAccount;<br><br>    public BankTransferPayment(String bankAccount) {<br>        this.bankAccount = bankAccount;<br>    }<br><br>    @Override<br>    public void pay(double amount) {<br>        // Logic for processing bank transfer payment<br>        System.out.println(&quot;Processing bank transfer payment of $&quot; + amount + &quot; for account &quot; + bankAccount);<br>    }<br><br>    @Override<br>    public void refund(double amount) {<br>        // Logic for refunding bank transfer payment<br>        System.out.println(&quot;Refunding $&quot; + amount + &quot; to bank account &quot; + bankAccount);<br>    }<br><br>    @Override<br>    public String generateReceipt() {<br>        // Logic for generating receipt<br>        return &quot;Receipt for bank transfer payment to account &quot; + bankAccount;<br>    }<br>}</pre><h3>Step 3: Use the Interface in the Application</h3><p>In the main application, we can use the PaymentProcessor interface to process payments without worrying about the specific implementation details.</p><pre>public class ECommerceApp {<br>    public static void main(String[] args) {<br>        PaymentProcessor creditCardPayment = new CreditCardPayment(&quot;1234-5678-9012-3456&quot;);<br>        PaymentProcessor payPalPayment = new PayPalPayment(&quot;user@example.com&quot;);<br>        PaymentProcessor bankTransferPayment = new BankTransferPayment(&quot;9876543210&quot;);<br><br>        // Process payments<br>        creditCardPayment.pay(100.0);<br>        payPalPayment.pay(200.0);<br>        bankTransferPayment.pay(300.0);<br><br>        // Refund payments<br>        creditCardPayment.refund(50.0);<br>        payPalPayment.refund(100.0);<br>        bankTransferPayment.refund(150.0);<br><br>        // Generate receipts<br>        System.out.println(creditCardPayment.generateReceipt());<br>        System.out.println(payPalPayment.generateReceipt());<br>        System.out.println(bankTransferPayment.generateReceipt());<br>    }<br>}</pre><h3>Explanation</h3><ol><li><strong>Defining the Interface</strong>: The PaymentProcessor interface defines three methods (pay, refund, and generateReceipt) that all payment processors must implement. This ensures a consistent API for all payment types.</li><li><strong>Implementing the Interface</strong>: Each payment method (Credit Card, PayPal, Bank Transfer) provides its specific implementation for the methods defined in the PaymentProcessor interface. This allows each payment method to handle the payment process in its unique way.</li><li><strong>Using the Interface</strong>: In the ECommerceApp class, we use the PaymentProcessor interface to process payments, refunds, and generate receipts. This abstraction allows the application to handle different payment methods in a unified manner, making the code more flexible and easier to maintain.</li></ol><h3>Conclusion</h3><p>Interfaces in Java are a powerful tool for defining contracts and achieving abstraction, multiple inheritance, loose coupling, and design flexibility. They allow you to define what a class must do without specifying how it should do it, promoting a clear separation of concerns and enabling more modular and maintainable code. By understanding and effectively utilizing interfaces, you can design robust and flexible Java applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3a0c65315fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract class in Java]]></title>
            <link>https://hemanthcse1.medium.com/abstract-class-in-java-6e825d671c10?source=rss-bbdb1d68a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e825d671c10</guid>
            <category><![CDATA[oops-in-java]]></category>
            <category><![CDATA[abstract]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Hemanth Kumar N V]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 14:57:26 GMT</pubDate>
            <atom:updated>2024-06-02T14:57:26.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIy6EEdlrO0RQelinI20aQ.png" /></figure><p>An abstract class in Java is a class that cannot be instantiated directly and is designed to be subclassed. It serves as a blueprint for other classes, allowing you to define methods that must be implemented by any concrete subclass. Abstract classes are useful for defining common behaviors and characteristics that can be shared across multiple related classes while enforcing a contract for method implementation.</p><h3>Characteristics of Abstract Classes</h3><ol><li><strong>Cannot Be Instantiated</strong>: You cannot create an instance of an abstract class directly.</li></ol><pre>// This is not allowed<br>AbstractClass obj = new AbstractClass();</pre><p><strong>2. May Contain Abstract Methods</strong>: Abstract methods are methods without a body that must be implemented by subclasses. They are declared with the abstract keyword.</p><pre>abstract void doSomething();</pre><p><strong>3. Can Have Concrete Methods</strong>: Abstract classes can also have methods with implementations (concrete methods).</p><pre>public void concreteMethod() {<br>    System.out.println(&quot;This is a concrete method.&quot;);<br>}</pre><p><strong>4. Can Have Fields and Constructors</strong>: Abstract classes can have instance variables and constructors.</p><pre>abstract class Vehicle {<br>    String name;<br><br>    public Vehicle(String name) {<br>        this.name = name;<br>    }<br>}</pre><p><strong>5. Can Implement Interfaces</strong>: Abstract classes can implement interfaces, and any abstract methods of the interface must be implemented by the subclasses.</p><pre>interface Drivable {<br>    void drive();<br>}<br><br>abstract class Vehicle implements Drivable {<br>    // Other methods and fields<br>}</pre><h3>Syntax of Abstract Class</h3><pre>abstract class AbstractClass {<br>    // Abstract method (no implementation)<br>    abstract void abstractMethod();<br><br>    // Concrete method<br>    public void concreteMethod() {<br>        System.out.println(&quot;This is a concrete method.&quot;);<br>    }<br>}</pre><h3>Example of an Abstract Class</h3><p>Let’s consider an example to understand the concept better.</p><h4>Abstract Class: Vehicle</h4><pre>abstract class Vehicle {<br>    private String name;<br><br>    public Vehicle(String name) {<br>        this.name = name;<br>    }<br><br>    // Abstract method<br>    public abstract void startEngine();<br><br>    // Concrete method<br>    public void stopEngine() {<br>        System.out.println(name + &quot; engine stopped.&quot;);<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br>}</pre><h4>Concrete Class: Car</h4><pre>public class Car extends Vehicle {<br>    private int numberOfDoors;<br><br>    public Car(String name, int numberOfDoors) {<br>        super(name); // Call the constructor of the Vehicle class<br>        this.numberOfDoors = numberOfDoors;<br>    }<br><br>    // Implement the abstract method<br>    @Override<br>    public void startEngine() {<br>        System.out.println(getName() + &quot; engine started.&quot;);<br>    }<br><br>    public int getNumberOfDoors() {<br>        return numberOfDoors;<br>    }<br><br>    public static void main(String[] args) {<br>        Car myCar = new Car(&quot;Toyota&quot;, 4);<br>        myCar.startEngine(); // Output: Toyota engine started.<br>        myCar.stopEngine();  // Output: Toyota engine stopped.<br>    }<br>}</pre><h3>Detailed Explanation</h3><h4>1. Defining Common Behavior</h4><p>Abstract classes are used to define common behavior that can be inherited by multiple subclasses. For example, in the Vehicle abstract class, the stopEngine method is defined and shared among all subclasses, while the startEngine method is abstract, requiring subclasses to provide their own implementation.</p><h4>2. Enforcing Method Implementation</h4><p>By declaring a method as abstract in an abstract class, you enforce that all subclasses must implement this method. This is useful for ensuring that certain behaviors are always provided by subclasses. In the Vehicle example, any class that extends Vehicle must implement the startEngine method.</p><h4>3. Partial Implementation</h4><p>Abstract classes allow for partial implementation. You can define some methods in the abstract class and leave others to be implemented by subclasses. This provides a flexible way to build a common base for related classes while allowing for specific implementations in the subclasses.</p><h4>4. Constructors in Abstract Classes</h4><p>Abstract classes can have constructors, which can be used to initialize fields. However, you cannot instantiate an abstract class directly. Instead, the constructor of the abstract class is called when a subclass is instantiated. In the Vehicle example, the constructor initializes the name field.</p><h4>5. Fields and Methods</h4><p>Abstract classes can have fields, concrete methods, and abstract methods. This allows you to create a rich base class with both implemented functionality and abstract methods that must be overridden.</p><h3>Comparison with Interfaces</h3><h4>Similarities:</h4><ul><li>Both abstract classes and interfaces cannot be instantiated directly.</li><li>Both can contain abstract methods that must be implemented by subclasses or implementing classes.</li></ul><h4>Differences:</h4><ol><li><strong>Abstract Classes</strong>:</li></ol><ul><li>Can have concrete methods with implementations.</li><li>Can have fields and constructors.</li><li>A class can extend only one abstract class (single inheritance).</li><li>Can provide default behavior for some methods.</li></ul><ol><li><strong>Interfaces</strong>:</li></ol><ul><li>Cannot have fields (except static final constants).</li><li>Cannot have constructors.</li><li>A class can implement multiple interfaces (multiple inheritance).</li><li>Methods in interfaces are abstract by default (until Java 8, when default methods were introduced).</li></ul><h3>Use Cases for Abstract Classes</h3><ol><li><strong>Class Hierarchies</strong>: Use abstract classes when you have a class hierarchy where base classes should not be instantiated but should define common behavior for subclasses.</li></ol><pre>abstract class Animal {<br>    abstract void makeSound();<br>}<br><br>class Dog extends Animal {<br>    void makeSound() {<br>        System.out.println(&quot;Bark&quot;);<br>    }<br>}<br><br>class Cat extends Animal {<br>    void makeSound() {<br>        System.out.println(&quot;Meow&quot;);<br>    }<br>}</pre><ol><li><strong>Frameworks and Libraries</strong>: Abstract classes are often used in frameworks and libraries to provide a base class that defines a template for other classes to extend and customize.</li><li><strong>Partial Implementation</strong>: When you want to provide some common implementation while leaving certain methods to be implemented by subclasses.</li></ol><p><strong>Real-Time Use Case for Abstract Class in Java</strong></p><p>Let’s consider a real-time use case involving an e-commerce application. In such an application, you might have various types of payment methods, such as credit cards, PayPal, and bank transfers. Each payment method has some common functionality and some specific functionality.</p><h3>Abstract Class in Payment System</h3><h4>Step-by-Step Example:</h4><ol><li><strong>Abstract Class</strong>: Define an abstract class Payment that provides common behavior for all payment methods.</li><li><strong>Concrete Classes</strong>: Create concrete classes for each payment method that extend the Payment abstract class and implement the specific behaviors.</li></ol><h3>Step 1: Define the Abstract Class</h3><pre>abstract class Payment {<br>    private double amount;<br><br>    public Payment(double amount) {<br>        this.amount = amount;<br>    }<br><br>    // Abstract method to be implemented by subclasses<br>    public abstract void processPayment();<br><br>    // Concrete method to print the payment amount<br>    public void printReceipt() {<br>        System.out.println(&quot;Payment of $&quot; + amount + &quot; processed.&quot;);<br>    }<br><br>    public double getAmount() {<br>        return amount;<br>    }<br>}</pre><h3>Step 2: Create Concrete Classes</h3><h4>Credit Card Payment</h4><pre>public class CreditCardPayment extends Payment {<br>    private String cardNumber;<br><br>    public CreditCardPayment(double amount, String cardNumber) {<br>        super(amount);<br>        this.cardNumber = cardNumber;<br>    }<br><br>    @Override<br>    public void processPayment() {<br>        // Implement credit card payment processing logic<br>        System.out.println(&quot;Processing credit card payment for card: &quot; + cardNumber);<br>        // After processing, print the receipt<br>        printReceipt();<br>    }<br><br>    public String getCardNumber() {<br>        return cardNumber;<br>    }<br>}</pre><p><strong>PayPal Payment</strong></p><pre>public class PayPalPayment extends Payment {<br>    private String email;<br><br>    public PayPalPayment(double amount, String email) {<br>        super(amount);<br>        this.email = email;<br>    }<br><br>    @Override<br>    public void processPayment() {<br>        // Implement PayPal payment processing logic<br>        System.out.println(&quot;Processing PayPal payment for email: &quot; + email);<br>        // After processing, print the receipt<br>        printReceipt();<br>    }<br><br>    public String getEmail() {<br>        return email;<br>    }<br>}</pre><p><strong>Bank Transfer Payment</strong></p><pre>public class BankTransferPayment extends Payment {<br>    private String bankAccount;<br><br>    public BankTransferPayment(double amount, String bankAccount) {<br>        super(amount);<br>        this.bankAccount = bankAccount;<br>    }<br><br>    @Override<br>    public void processPayment() {<br>        // Implement bank transfer payment processing logic<br>        System.out.println(&quot;Processing bank transfer payment for account: &quot; + bankAccount);<br>        // After processing, print the receipt<br>        printReceipt();<br>    }<br><br>    public String getBankAccount() {<br>        return bankAccount;<br>    }<br>}</pre><h3><strong>Step 3: Use the Concrete Classes</strong></h3><pre>public class ECommerceApp {<br>    public static void main(String[] args) {<br>        Payment creditCardPayment = new CreditCardPayment(100.0, &quot;1234-5678-9012-3456&quot;);<br>        Payment payPalPayment = new PayPalPayment(200.0, &quot;user@example.com&quot;);<br>        Payment bankTransferPayment = new BankTransferPayment(300.0, &quot;9876543210&quot;);<br><br>        creditCardPayment.processPayment(); // Output: Processing credit card payment for card: 1234-5678-9012-3456<br>                                            //         Payment of $100.0 processed.<br><br>        payPalPayment.processPayment();     // Output: Processing PayPal payment for email: user@example.com<br>                                            //         Payment of $200.0 processed.<br><br>        bankTransferPayment.processPayment(); // Output: Processing bank transfer payment for account: 9876543210<br>                                              //         Payment of $300.0 processed.<br>    }<br>}</pre><h3>Explanation</h3><ol><li><strong>Abstract Class (Payment)</strong>:</li></ol><ul><li>Defines a common method printReceipt that is shared among all payment methods.</li><li>Declares an abstract method processPayment which must be implemented by any subclass.</li><li>Contains common properties like amount.</li></ul><p><strong>2. Concrete Classes (CreditCardPayment, PayPalPayment, BankTransferPayment)</strong>:</p><ul><li>Each subclass provides a specific implementation for the processPayment method.</li><li>Each subclass can have additional properties specific to the payment method (e.g., cardNumber for credit card, email for PayPal, bankAccount for bank transfer).</li></ul><p><strong>3. Usage</strong>:</p><ul><li>In the ECommerceApp class, different types of payment objects are created and used polymorphically.</li><li>Each payment type processes its payment and then prints a receipt using the common printReceipt method defined in the abstract class.</li></ul><p>In summary, abstract classes in Java provide a powerful mechanism for defining common behavior, enforcing method implementation, and creating flexible class hierarchies. By understanding how to use abstract classes effectively, you can build robust and maintainable object-oriented systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e825d671c10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concrete class in Java]]></title>
            <link>https://hemanthcse1.medium.com/concrete-class-in-java-3379304f33cb?source=rss-bbdb1d68a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3379304f33cb</guid>
            <category><![CDATA[classés]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Hemanth Kumar N V]]></dc:creator>
            <pubDate>Sat, 01 Jun 2024 11:41:05 GMT</pubDate>
            <atom:updated>2024-06-01T11:41:05.637Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*27VuRuP_DDL5C_kY.png" /></figure><p>Let’s delve deeper into the concept of concrete classes in Java, including their uses, characteristics, examples, and the distinctions between abstract classes, interfaces, and concrete classes.</p><h3>Characteristics of Concrete Classes:</h3><ol><li><strong>Instantiable</strong>: Concrete classes can be instantiated, meaning you can create objects from them using the new keyword.</li></ol><pre>ConcreteClass obj = new ConcreteClass();</pre><ol><li><strong>Complete Method Implementations</strong>: All methods declared in a concrete class must have complete implementations. There can be no abstract methods in a concrete class.</li><li><strong>Inheritance</strong>: A concrete class can extend another class (abstract or concrete) and implement multiple interfaces. When a concrete class extends an abstract class or implements an interface, it must provide implementations for all inherited abstract methods.</li></ol><pre>class ConcreteClass extends AbstractClass implements Interface1, Interface2 {    <br> // Implement all abstract methods from AbstractClass and Interface1, Interface2 <br>}</pre><ol><li><strong>Constructors</strong>: Concrete classes can have constructors to initialize objects. They can also have overloaded constructors.</li></ol><pre>class ConcreteClass {<br>    int value;<br><br>    // Default constructor<br>    public ConcreteClass() {<br>        this.value = 0;<br>    }<br><br>    // Parameterized constructor<br>    public ConcreteClass(int value) {<br>        this.value = value;<br>    }<br>}</pre><ol><li><strong>Polymorphism</strong>: Concrete classes can be used polymorphically. You can refer to a concrete class object using a reference of a superclass type or interface type.</li></ol><pre>AbstractClass obj = new ConcreteClass();<br>Interface1 obj = new ConcreteClass();</pre><h3>Example of Concrete Class:</h3><p>Let’s build a more detailed example involving inheritance and interfaces:</p><h3>Abstract Class:</h3><pre>abstract class Vehicle {<br>    private String name;<br><br>    public Vehicle(String name) {<br>        this.name = name;<br>    }<br><br>    // Abstract method (no implementation)<br>    public abstract void startEngine();<br><br>    // Concrete method<br>    public void stopEngine() {<br>        System.out.println(name + &quot; engine stopped.&quot;);<br>    }<br>}</pre><h3>Interface:</h3><pre>interface Drivable {<br>    void drive();<br>}</pre><h3>Concrete Class:</h3><pre>public class Car extends Vehicle implements Drivable {<br>    private int numberOfDoors;<br><br>    public Car(String name, int numberOfDoors) {<br>        super(name); // Call the constructor of the Vehicle class<br>        this.numberOfDoors = numberOfDoors;<br>    }<br><br>    // Implement the abstract method from Vehicle<br>    @Override<br>    public void startEngine() {<br>        System.out.println(getName() + &quot; engine started.&quot;);<br>    }<br><br>    // Implement the method from Drivable<br>    @Override<br>    public void drive() {<br>        System.out.println(&quot;Driving the car.&quot;);<br>    }<br><br>    public int getNumberOfDoors() {<br>        return numberOfDoors;<br>    }<br><br>    public static void main(String[] args) {<br>        Car myCar = new Car(&quot;Toyota&quot;, 4);<br>        myCar.startEngine(); // Output: Toyota engine started.<br>        myCar.drive();       // Output: Driving the car.<br>        myCar.stopEngine();  // Output: Toyota engine stopped.<br>    }<br>}</pre><h3>Comparison with Abstract Classes and Interfaces:</h3><h3>Abstract Class:</h3><ul><li><strong>Cannot be instantiated</strong>.</li><li>Can have both abstract methods (without implementation) and concrete methods (with implementation).</li><li>Used to define a template for subclasses.</li></ul><h3>Interface:</h3><ul><li>Cannot be instantiated.</li><li>Can only have abstract methods (until Java 8), default methods, and static methods.</li><li>Used to define a contract that implementing classes must follow.</li></ul><h3>Concrete Class:</h3><ul><li><strong>Can be instantiated</strong>.</li><li>Must provide implementations for all methods, including inherited abstract methods.</li><li>Represents actual objects and behaviors in the system.</li></ul><h3>Use Cases for Concrete Classes:</h3><ol><li><strong>Modeling Real-World Entities</strong>: Concrete classes are often used to represent tangible objects in the system, such as Car, Employee, Product, etc.</li><li><strong>Utility Classes</strong>: Concrete classes can be used to provide utility functions, such as StringUtils, FileUtils, etc., containing static methods.</li><li><strong>Data Transfer Objects (DTOs)</strong>: Concrete classes are used to transfer data between different layers of an application. For example, UserDTO, OrderDTO, etc.</li><li><strong>Business Logic Implementation</strong>: Concrete classes often encapsulate business logic, providing methods that perform specific operations related to the business domain.</li></ol><h3>More Detailed Example:</h3><p>Let’s consider a more complex example involving multiple concrete classes, inheritance, and interfaces.</p><h3>Abstract Class and Interfaces:</h3><pre>abstract class Employee {<br>    private String name;<br>    private int id;<br><br>    public Employee(String name, int id) {<br>        this.name = name;<br>        this.id = id;<br>    }<br><br>    public abstract void work();<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public int getId() {<br>        return id;<br>    }<br>}<br><br>interface Payable {<br>    void processPayment();<br>}<br><br>interface Trackable {<br>    void logHours(int hours);<br>}</pre><h3>Concrete Classes:</h3><pre>public class FullTimeEmployee extends Employee implements Payable, Trackable {<br>    private double salary;<br><br>    public FullTimeEmployee(String name, int id, double salary) {<br>        super(name, id);<br>        this.salary = salary;<br>    }<br><br>    @Override<br>    public void work() {<br>        System.out.println(getName() + &quot; is working full-time.&quot;);<br>    }<br><br>    @Override<br>    public void processPayment() {<br>        System.out.println(&quot;Processing salary payment for &quot; + getName());<br>    }<br><br>    @Override<br>    public void logHours(int hours) {<br>        System.out.println(getName() + &quot; logged &quot; + hours + &quot; hours.&quot;);<br>    }<br>}<br><br>public class PartTimeEmployee extends Employee implements Payable {<br>    private double hourlyRate;<br><br>    public PartTimeEmployee(String name, int id, double hourlyRate) {<br>        super(name, id);<br>        this.hourlyRate = hourlyRate;<br>    }<br><br>    @Override<br>    public void work() {<br>        System.out.println(getName() + &quot; is working part-time.&quot;);<br>    }<br><br>    @Override<br>    public void processPayment() {<br>        System.out.println(&quot;Processing hourly payment for &quot; + getName());<br>    }<br>}</pre><h3>Main Class:</h3><pre>public class Car extends Vehicle implements Drivable {<br>    private int numberOfDoors;<br><br>    public Car(String name, int numberOfDoors) {<br>        super(name); // Call the constructor of the Vehicle class<br>        this.numberOfDoors = numberOfDoors;<br>    }<br><br>    // Implement the abstract method from Vehicle<br>    @Override<br>    public void startEngine() {<br>        System.out.println(getName() + &quot; engine started.&quot;);<br>    }<br><br>    // Implement the method from Drivable<br>    @Override<br>    public void drive() {<br>        System.out.println(&quot;Driving the car.&quot;);<br>    }<br><br>    public int getNumberOfDoors() {<br>        return numberOfDoors;<br>    }<br><br>    public static void main(String[] args) {<br>        Car myCar = new Car(&quot;Toyota&quot;, 4);<br>        myCar.startEngine();<br>        myCar.drive();       <br>        myCar.stopEngine();  <br>    }<br>}</pre><h3>Summary:</h3><p>Concrete classes in Java are the building blocks for creating actual objects with specific behaviors and properties. They can be instantiated, provide complete method implementations, and can work polymorphically with abstract classes and interfaces. By understanding and effectively utilizing concrete classes, developers can create robust, maintainable, and efficient applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3379304f33cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimum Size Subarray Sum]]></title>
            <link>https://hemanthcse1.medium.com/minimum-size-subarray-sum-e7a6b24a2215?source=rss-bbdb1d68a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7a6b24a2215</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[sliding-windows]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Hemanth Kumar N V]]></dc:creator>
            <pubDate>Thu, 23 May 2024 15:32:04 GMT</pubDate>
            <atom:updated>2024-05-23T15:32:04.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwh3VrV-PAG89ROdLj6oXg.png" /></figure><h3>Problem Statement</h3><p>Given an array of positive integers nums and a positive integer target, the goal is to return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.</p><h3>Examples</h3><ol><li>Input: target = 7, nums = [2, 3, 1, 2, 4, 3] Output: 2 Explanation: The subarray [4, 3] has the minimal length under the problem constraint.</li><li>Input: target = 4, nums = [1, 4, 4] Output: 1 Explanation: The subarray [4] has the minimal length.</li><li>Input: target = 11, nums = [1, 1, 1, 1, 1, 1, 1, 1] Output: 0 Explanation: There is no subarray whose sum is greater than or equal to 11.</li></ol><h3>Solution Explanation</h3><h3>Approach</h3><p>To solve this problem, we can use the sliding window technique. The sliding window technique involves maintaining a window of elements that satisfies certain conditions and adjusting the window’s size and position to find the optimal solution.</p><h3>Steps</h3><ol><li>Initialize Variables:</li></ol><ul><li>minWindowLen to store the minimum length of the subarray found. Initialize it to Int.MAX_VALUE.</li><li>currentSum to keep track of the sum of the current window. Initialize it to 0.</li><li>Two pointers low and high to represent the bounds of the window. Both are initialized to 0.</li></ul><p>2. Expand the Window:</p><ul><li>Use a while loop to expand the window by moving the high pointer from the beginning to the end of the array (nums.size).</li><li>Add nums[high] to currentSum and increment high.</li></ul><p>3. Contract the Window:</p><ul><li>Use a nested while loop to check if the currentSum is greater than or equal to target.</li><li>If true, calculate the current window length (high - low).</li><li>Update minWindowLen with the minimum value between the current window length and minWindowLen.</li><li>Subtract nums[low] from currentSum and increment low.</li></ul><p>4. Return Result:</p><ul><li>After processing the entire array, check if minWindowLen was updated from its initial value. If it was, return minWindowLen. Otherwise, return 0.</li></ul><h3>Code</h3><p>Here is the Kotlin implementation of the solution:</p><pre>fun main() {<br>    val nums = intArrayOf(2, 3, 1, 2, 4, 3)<br>    val target = 7<br>println(&quot;result -&gt; ${minSubarraySum(target, nums)}&quot;)<br>}<br>fun minSubarraySum(target: Int, nums: IntArray): Int {<br>    var minWindowLen = Int.MAX_VALUE<br>    var currentSum = 0<br>    var low = 0<br>    var high = 0<br>    while (high &lt; nums.size) {<br>        currentSum += nums[high]<br>        high++<br>        while (currentSum &gt;= target) {<br>            val currentWindowLen = high - low<br>            minWindowLen = kotlin.math.min(currentWindowLen, minWindowLen)<br>            currentSum -= nums[low]<br>            low++<br>        }<br>    }<br>    return if (minWindowLen == Int.MAX_VALUE) 0 else minWindowLen<br>}</pre><h3>Time and Space Complexity</h3><ul><li>Time Complexity: O(n)</li><li>Each element in the array is processed at most twice (once by the high pointer and once by the low pointer), making the algorithm linear in terms of time complexity.</li><li>Space Complexity: O(1)</li><li>The algorithm uses a constant amount of extra space, as it only uses a few variables (minWindowLen, currentSum, low, high) regardless of the size of the input array.</li></ul><p>This solution efficiently finds the minimal length subarray with a sum greater than or equal to the target using a sliding window approach.</p><p>For the complete implementation, you can refer to the code in this <a href="https://github.com/hemanthcse1/dsa-solutions/blob/feature/problems/src/main/java/problems/arrays/minimumsizesubarraysum/MinimumSizeSubArraySum.kt">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7a6b24a2215" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[@RegisterForReflection vs @Serializable in Quarkus with kotlin]]></title>
            <link>https://hemanthcse1.medium.com/registerforreflection-vs-serializable-in-quarkus-with-kotlin-1b32cfa91671?source=rss-bbdb1d68a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b32cfa91671</guid>
            <category><![CDATA[container-orchestration]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[quarkus-framework]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Hemanth Kumar N V]]></dc:creator>
            <pubDate>Wed, 22 May 2024 03:32:05 GMT</pubDate>
            <atom:updated>2024-05-22T03:32:05.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Jtz5xLUl8ltaZ-Lt" /></figure><h3>Overview of @RegisterForReflection</h3><p>In Quarkus, <strong>@RegisterForReflection</strong> is an annotation used to ensure that certain classes, methods, or fields are retained for reflection when the application is compiled into a native executable using GraalVM. This is necessary because GraalVM performs aggressive dead code elimination and may remove elements that are only accessed through reflection, leading to runtime errors. The <strong>@RegisterForReflection</strong> annotation prevents this by explicitly marking elements that should be preserved.</p><h3>Detailed Code Example</h3><p>Here’s your provided Kotlin code with explanations:</p><pre>import com.fasterxml.jackson.annotation.JsonProperty<br>import io.quarkus.runtime.annotations.RegisterForReflection<br><br>@RegisterForReflection<br>data class CreateProductInfoRequest(<br>    @field:JsonProperty(&quot;code&quot;)<br>    val code: String,<br>    @field:JsonProperty(&quot;itemRefNum&quot;)<br>    val itemRefNum: String,<br>    @field:JsonProperty(&quot;site&quot;)<br>    val site: String,<br>    @field:JsonProperty(&quot;commercialName&quot;)<br>    val commercialName: String,<br>    @field:JsonProperty(&quot;packagedQuantity&quot;)<br>    var packagedQuantity: Double,<br>    @field:JsonProperty(&quot;shippedQuantity&quot;)<br>    var shippedQuantity: Double,<br>    @field:JsonProperty(&quot;state&quot;)<br>    var state: String<br>) {<br>    fun toEntity(): ProductInfo {<br>        return ProductInfo().apply {<br>            this.code = this@CreateProductInfoRequest.code<br>            this.itemRefNum = this@CreateProductInfoRequest.itemRefNum<br>            this.site = this@CreateProductInfoRequest.site<br>            this.commercialName = this@CreateProductInfoRequest.commercialName<br>            this.packagedQuantity = this@CreateProductInfoRequest.packagedQuantity<br>            this.shippedQuantity = this@CreateProductInfoRequest.shippedQuantity<br>            this.state = this@CreateProductInfoRequest.state<br>        }<br>    }<br>}</pre><h3>Detailed Explanation</h3><ol><li><strong>Importing Necessary Annotations</strong>:</li></ol><pre>import com.fasterxml.jackson.annotation.JsonProperty<br>import io.quarkus.runtime.annotations.RegisterForReflection</pre><ul><li><strong>JsonProperty</strong>: This annotation from the Jackson library is used to specify the JSON property names that should be mapped to the fields in the data class. This is crucial for JSON serialization and deserialization.</li><li><strong>RegisterForReflection</strong>: This annotation from Quarkus marks the class to be included in the reflection configuration of the native image, ensuring that it is available for reflection at runtime.</li></ul><p><strong>2. Applying </strong><strong>@RegisterForReflection to the Data Class</strong>:</p><pre>@RegisterForReflection<br>data class CreateProductInfoRequest(</pre><ul><li>The <strong>@RegisterForReflection</strong> annotation is applied to the <strong>CreateProductInfoRequest</strong> data class. This indicates to the Quarkus framework that the class and its members should be preserved for reflection in the native image. This is necessary for JSON serialization/deserialization, which uses reflection to access the fields.</li></ul><p><strong>3. Field-Level Annotations</strong>:</p><pre>@field:JsonProperty(&quot;code&quot;)<br>val code: String,</pre><ul><li><strong>@field:JsonProperty</strong>: This specifies that the <strong>code</strong> field should be mapped to the <strong>code</strong> property in the JSON object. Similar annotations are applied to other fields (<strong>itemRefNum</strong>, <strong>site</strong>, <strong>commercialName</strong>, <strong>packagedQuantity</strong>, <strong>shippedQuantity</strong>, <strong>state</strong>), ensuring that they are correctly mapped during JSON processing.</li></ul><p><strong>4. Method Implementation</strong>:</p><pre>fun toEntity(): ProductInfo {<br>    return ProductInfo().apply {<br>        this.code = this@CreateProductInfoRequest.code<br>        this.itemRefNum = this@CreateProductInfoRequest.itemRefNum<br>        this.site = this@CreateProductInfoRequest.site<br>        this.commercialName = this@CreateProductInfoRequest.commercialName<br>        this.packagedQuantity = this@CreateProductInfoRequest.packagedQuantity<br>        this.shippedQuantity = this@CreateProductInfoRequest.shippedQuantity<br>        this.state = this@CreateProductInfoRequest.state<br>    }<br>}</pre><ul><li><strong>toEntity Method</strong>: This method converts an instance of <strong>CreateProductInfoRequest</strong> into an instance of <strong>ProductInfo</strong>. The Kotlin <strong>apply</strong> function is used to set the properties of <strong>ProductInfo</strong> using the values from <strong>CreateProductInfoRequest</strong>.</li></ul><h3>Why Use @RegisterForReflection?</h3><ul><li><strong>GraalVM Native Image Compatibility</strong>: GraalVM’s native image compilation process removes unused code, including classes, methods, and fields that are only accessed via reflection. This can break functionalities like JSON serialization/deserialization, which rely on reflection. By using <strong>@RegisterForReflection</strong>, you ensure that the necessary metadata for reflection is retained in the native image.</li><li><strong>Avoiding Runtime Errors</strong>: Missing reflection metadata can cause runtime errors in native images, particularly in frameworks that depend heavily on reflection (like Jackson for JSON processing). The <strong>@RegisterForReflection</strong> annotation helps avoid these errors by explicitly marking the classes and members that need to be available for reflection.</li><li><strong>Maintaining Application Functionality</strong>: Ensuring that classes used in serialization/deserialization or other reflection-based operations are preserved in the native image maintains the correct functionality of your application.</li></ul><h3>Considerations</h3><ul><li><strong>Selective Use</strong>: Only use <strong>@RegisterForReflection</strong> for classes and members that are accessed via reflection. Overusing this annotation can lead to larger native images and potentially impact performance.</li><li><strong>Configuration Maintenance</strong>: As your application evolves, you need to keep the reflection configuration up-to-date to include new classes or members accessed via reflection.</li></ul><p>By understanding and applying the <strong>@RegisterForReflection</strong> annotation correctly, you can ensure that your Quarkus applications work seamlessly when compiled into native executables, preserving necessary reflection metadata and avoiding runtime issues.</p><h3>Overview of @Serializable</h3><p>The <strong>@Serializable</strong> annotation is part of Kotlin&#39;s serialization library (<strong>kotlinx.serialization</strong>). This annotation is used to mark a class as serializable, meaning that instances of the class can be converted to and from formats like JSON, ProtoBuf, and others. This is particularly useful for data transfer between different parts of an application or between different systems.</p><h3>Example Code</h3><p>Here’s a new Kotlin example with the <strong>@Serializable</strong> annotation:</p><pre>import kotlinx.serialization.Serializable<br><br>@Serializable<br>data class User(<br>    val id: Int,<br>    val name: String,<br>    val email: String,<br>    val isActive: Boolean<br>)</pre><h3>Detailed Explanation</h3><ol><li><strong>Importing the </strong><strong>@Serializable Annotation</strong>:</li></ol><pre>import kotlinx.serialization.Serializable</pre><ul><li>This import statement includes the <strong>@Serializable</strong> annotation from the Kotlin serialization library (<strong>kotlinx.serialization</strong>). This library provides tools for converting Kotlin objects to various formats like JSON.</li></ul><p><strong>2. Applying </strong><strong>@Serializable to the Data Class</strong>:</p><pre>@Serializable<br>data class User(</pre><ul><li>The <strong>@Serializable</strong> annotation is applied to the <strong>User</strong> data class. This marks the class as serializable, meaning that instances of this class can be converted to and from JSON (or other formats).</li></ul><p><strong>3. Fields in the Data Class</strong>:</p><pre>val id: Int,<br>val name: String,<br>val email: String,<br>val isActive: Boolean</pre><ul><li>The fields in the <strong>User</strong> class represent the data that can be serialized. Fields can be of various types:</li><li><strong>Primitive types</strong>: <strong>Int</strong>, <strong>Boolean</strong></li><li><strong>String type</strong>: <strong>String</strong></li></ul><h3>Serialization and Deserialization</h3><h3>Serialization</h3><p>Serialization is the process of converting an object into a format that can be easily stored or transmitted. For example, converting a <strong>User</strong> instance to a JSON string.</p><p>Example:</p><pre>import kotlinx.serialization.json.Json<br><br>val user = User(<br>    id = 1,<br>    name = &quot;John Doe&quot;,<br>    email = &quot;john.doe@example.com&quot;,<br>    isActive = true<br>)<br>val jsonString = Json.encodeToString(User.serializer(), user)<br>println(jsonString</pre><p>Output:</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;email&quot;: &quot;john.doe@example.com&quot;,<br>    &quot;isActive&quot;: true<br>}</pre><p>In this example:</p><ul><li><strong>Json.encodeToString</strong> is used to serialize the <strong>user</strong> object to a JSON string.</li><li>The <strong>User.serializer()</strong> method is used to obtain the serializer for the <strong>User</strong> class.</li></ul><h3>Deserialization</h3><p>Deserialization is the process of converting a format (like JSON) back into an object.</p><p>Example:</p><pre>val jsonString = &quot;&quot;&quot;<br>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;email&quot;: &quot;john.doe@example.com&quot;,<br>    &quot;isActive&quot;: true<br>}<br>&quot;&quot;&quot;<br><br>val user = Json.decodeFromString(User.serializer(), jsonString)<br>println(user)</pre><p>Output:</p><pre>User(id=1, name=John Doe, email=john.doe@example.com, isActive=true)</pre><p>In this example:</p><ul><li><strong>Json.decodeFromString</strong> is used to deserialize the JSON string back into a <strong>User</strong> object.</li><li>The <strong>User.serializer()</strong> method is used to obtain the serializer for the <strong>User</strong> class.</li></ul><h3>Integration with Quarkus</h3><p>Quarkus supports Kotlin serialization through extensions and integrates seamlessly with RESTful web services, making it easy to use data classes annotated with <strong>@Serializable</strong> in REST endpoints.</p><p>Example REST Endpoint:</p><pre>import javax.ws.rs.*<br>import javax.ws.rs.core.MediaType<br>import kotlinx.serialization.json.Json<br>import kotlinx.serialization.encodeToString<br>import kotlinx.serialization.decodeFromString<br><br>@Path(&quot;/users&quot;)<br>class UserResource {<br>    @POST<br>    @Consumes(MediaType.APPLICATION_JSON)<br>    @Produces(MediaType.APPLICATION_JSON)<br>    fun createUser(userJson: String): String {<br>        val user = Json.decodeFromString&lt;User&gt;(userJson)<br>        // Process the user object (e.g., save to database)<br>        return Json.encodeToString(user)<br>    }<br>    @GET<br>    @Path(&quot;/{id}&quot;)<br>    @Produces(MediaType.APPLICATION_JSON)<br>    fun getUser(@PathParam(&quot;id&quot;) id: Int): String {<br>        // Retrieve the user object based on the id (e.g., from database)<br>        val user = User(id, &quot;John Doe&quot;, &quot;john.doe@example.com&quot;, true)<br>        return Json.encodeToString(user)<br>    }<br>}</pre><p>In this example:</p><ul><li>The <strong>createUser</strong> method consumes a JSON string representing a <strong>User</strong> object, deserializes it, processes it, and then returns the serialized JSON string.</li><li>The <strong>getUser</strong> method retrieves a <strong>User</strong> object based on a provided ID and returns it as a JSON string.</li></ul><h3>Benefits of Using @Serializable</h3><ol><li><strong>Type-Safety</strong>: Ensures that the data being serialized and deserialized matches the structure defined in the data class.</li><li><strong>Ease of Use</strong>: Simplifies the process of converting objects to and from various formats, such as JSON.</li><li><strong>Integration</strong>: Works seamlessly with Quarkus and other frameworks for handling data transfer and persistence.</li><li><strong>Flexibility</strong>: Supports various formats (JSON, ProtoBuf, etc.) through different serialization modules.</li></ol><h3>Detailed Comparison</h3><h3>Purpose</h3><p><strong>@RegisterForReflection</strong>:</p><ul><li>Primarily used to register classes that require reflection at runtime.</li><li>Helps Quarkus optimize the application by reducing unnecessary reflection use.</li></ul><p><strong>@Serializable</strong>:</p><ul><li>Used to mark classes for serialization and deserialization.</li><li>Facilitates converting objects to and from formats like JSON.</li></ul><h3>Use Case</h3><p><strong>@RegisterForReflection</strong>:</p><ul><li>Needed when your application or libraries use reflection, and you want to explicitly specify which classes need to be registered for reflection.</li><li>Commonly used in native image generation (GraalVM) to ensure that reflection metadata is available at runtime.</li></ul><p><strong>@Serializable</strong>:</p><ul><li>Needed when you need to serialize and deserialize objects to/from JSON or other formats.</li><li>Useful for REST APIs, data persistence, and inter-service communication.</li></ul><h3>Example in Kotlin</h3><h3>Using @RegisterForReflection</h3><pre>import io.quarkus.runtime.annotations.RegisterForReflection<br><br>@RegisterForReflection<br>data class User(<br>    val id: Int,<br>    val name: String,<br>    val email: String<br>)<br>// Example usage in a Quarkus application<br>fun reflectUserClass() {<br>    val clazz = Class.forName(&quot;com.example.User&quot;)<br>    val constructor = clazz.getConstructor(Int::class.java, String::class.java, String::class.java)<br>    val user = constructor.newInstance(1, &quot;John Doe&quot;, &quot;john.doe@example.com&quot;)<br>    println(user)<br>}</pre><h3>Using @Serializable</h3><pre>import kotlinx.serialization.Serializable<br>import kotlinx.serialization.json.Json<br><br>@Serializable<br>data class User(<br>    val id: Int,<br>    val name: String,<br>    val email: String<br>)<br>// Serialization example<br>fun serializeUser() {<br>    val user = User(1, &quot;John Doe&quot;, &quot;john.doe@example.com&quot;)<br>    val jsonString = Json.encodeToString(User.serializer(), user)<br>    println(jsonString)<br>}<br>// Deserialization example<br>fun deserializeUser(jsonString: String) {<br>    val user = Json.decodeFromString(User.serializer(), jsonString)<br>    println(user)<br>}</pre><h3>Integration with Quarkus</h3><p><strong>@RegisterForReflection</strong>:</p><ul><li>Directly integrated with Quarkus to optimize reflection usage.</li><li>Useful in native image scenarios with GraalVM, where reflection metadata needs to be retained.</li></ul><p><strong>@Serializable</strong>:</p><ul><li>Requires <strong>kotlinx.serialization</strong> library.</li><li>Easily integrates with Quarkus REST endpoints for JSON (or other formats) data handling.</li><li>Needs additional setup for serialization configurations.</li></ul><h3>Performance</h3><ul><li><strong>@RegisterForReflection</strong>:</li><li>Helps improve performance by reducing unnecessary reflection.</li><li>Useful for optimizing startup times and memory usage, especially in native images.</li><li><strong>@Serializable</strong>:</li><li>Provides efficient serialization and deserialization mechanisms.</li><li>Optimized for performance in converting data to and from JSON (or other formats).</li></ul><h3>Summary</h3><ul><li><strong>@RegisterForReflection</strong> is used to register classes for reflection in Quarkus, optimizing reflection usage and improving performance, especially in native images.</li><li><strong>@Serializable</strong> is used to mark classes for serialization and deserialization, facilitating data conversion to and from formats like JSON.</li></ul><p>Both annotations serve different purposes and can be used together in a Quarkus application to handle reflection and serialization needs effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b32cfa91671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reordering a Linked List]]></title>
            <link>https://hemanthcse1.medium.com/reordering-a-linked-list-9cc131fa741a?source=rss-bbdb1d68a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cc131fa741a</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[sofware-development]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[linked-lists]]></category>
            <dc:creator><![CDATA[Hemanth Kumar N V]]></dc:creator>
            <pubDate>Tue, 21 May 2024 14:45:44 GMT</pubDate>
            <atom:updated>2024-05-21T14:45:44.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwh3VrV-PAG89ROdLj6oXg.png" /></figure><h3>Problem Statement</h3><p>The problem of reordering a linked list involves rearranging the elements of the list such that the nodes are reordered to follow a specific pattern. Given a singly linked list, the task is to reorder it such that the nodes are arranged in the order of <strong>L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → ...</strong>.</p><h3>Example</h3><p>Let’s consider an example to understand the reordering process:</p><ul><li><strong>Input:</strong> 4 -&gt; 8 -&gt; 15 -&gt; 16 -&gt; 23</li><li><strong>Output:</strong> 4 -&gt; 23 -&gt; 8 -&gt; 16 -&gt; 15</li></ul><h3>Solution Approach</h3><p>The solution to this problem can be broken down into three main steps:</p><ol><li><strong>Finding the Middle of the Linked List</strong></li><li><strong>Reversing the Second Half of the Linked List</strong></li><li><strong>Merging the Two Halves</strong></li></ol><h3>Detailed Steps</h3><h3>1. Finding the Middle of the Linked List</h3><p>To find the middle of the linked list, we can use the slow and fast pointer technique. The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. By the time the fast pointer reaches the end of the list, the slow pointer will be at the middle.</p><h3>2. Reversing the Second Half of the Linked List</h3><p>Once we have the middle of the list, we reverse the second half. This involves changing the next pointers of the nodes in the second half so that they point backwards.</p><h3>3. Merging the Two Halves</h3><p>Finally, we merge the two halves by alternating nodes from the first half and the reversed second half.</p><h3>Kotlin Implementation</h3><p>Here is the complete Kotlin implementation of the above approach:</p><pre>class ListNode(var value: Int) {<br>    var next: ListNode? = null<br>}<br><br>fun main() {<br>    val n1 = ListNode(4)<br>    val n2 = ListNode(8)<br>    val n3 = ListNode(15)<br>    val n4 = ListNode(16)<br>    val n5 = ListNode(23)<br>    n1.next = n2<br>    n2.next = n3<br>    n3.next = n4<br>    n4.next = n5<br>    n5.next = null<br>    val head = n1<br>    reorderList(head)<br>    printList(head)<br>}<br>fun reorderList(head: ListNode?) {<br>    if (head == null || head.next == null) {<br>        return<br>    }<br>    // Step 1: Find the middle of the linked list<br>    var slow: ListNode? = head<br>    var fast: ListNode? = head<br>    while (fast?.next != null &amp;&amp; fast.next?.next != null) {<br>        slow = slow?.next<br>        fast = fast.next?.next<br>    }<br>    // Step 2: Reverse the second half of the list<br>    val middle = slow<br>    var current = slow?.next<br>    while (current?.next != null) {<br>        val nextNode = current.next<br>        current.next = nextNode?.next<br>        nextNode?.next = middle?.next<br>        middle?.next = nextNode<br>    }<br>    // Step 3: Merge the two halves<br>    var first: ListNode? = head<br>    var second: ListNode? = middle?.next<br>    while (first != middle) {<br>        middle?.next = second?.next<br>        second?.next = first?.next<br>        first?.next = second<br>        first = second?.next<br>        second = middle?.next<br>    }<br>}<br>fun printList(head: ListNode?) {<br>    var current = head<br>    while (current != null) {<br>        print(&quot;${current.value} &quot;)<br>        current = current.next<br>    }<br>    println()<br>}</pre><h3>Explanation</h3><ol><li><strong>Finding the Middle:</strong></li></ol><ul><li>We initialize two pointers, <strong>slow</strong> and <strong>fast</strong>, both pointing to the head of the list.</li><li>We move <strong>slow</strong> one step at a time and <strong>fast</strong> two steps at a time.</li><li>When <strong>fast</strong> reaches the end, <strong>slow</strong> will be at the middle.</li></ul><p><strong>2. Reversing the Second Half:</strong></p><ul><li>We start reversing the second half from the node next to <strong>slow</strong>.</li><li>We change the <strong>next</strong> pointers to reverse the order of the nodes in the second half.</li></ul><p><strong>3.Merging the Halves:</strong></p><ul><li>We initialize two pointers, <strong>first</strong> pointing to the head and <strong>second</strong> pointing to the node next to <strong>middle</strong>.</li><li>We merge the nodes by alternating between nodes from the first half and the reversed second half.</li></ul><h3>Time Complexity</h3><ul><li><strong>Finding the Middle:</strong> O(n), where n is the number of nodes in the list.</li><li><strong>Reversing the Second Half:</strong> O(n/2) ≈ O(n).</li><li><strong>Merging the Halves:</strong> O(n).</li></ul><p>Overall, the time complexity of the algorithm is O(n).</p><h3>Space Complexity</h3><p>The algorithm uses a constant amount of extra space, making the space complexity O(1).</p><p>For the complete code, you can refer to the <a href="https://github.com/hemanthcse1/dsa-solutions/blob/main/src/main/java/linkedlist/problems/reorderllist/ReorderLinkedList.kt">GitHub repository</a>.</p><h3>Conclusion</h3><p>This approach efficiently reorders the linked list in linear time with constant space. The use of the slow and fast pointer technique to find the middle and the in-place reversal and merging ensure that the solution is both time and space efficient. This solution is well-suited for linked list problems where in-place modification is required.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cc131fa741a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Only Letters]]></title>
            <link>https://hemanthcse1.medium.com/reverse-only-letters-b3663c781abd?source=rss-bbdb1d68a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3663c781abd</guid>
            <category><![CDATA[dsa-courses]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Hemanth Kumar N V]]></dc:creator>
            <pubDate>Mon, 20 May 2024 15:32:03 GMT</pubDate>
            <atom:updated>2024-05-20T15:32:03.766Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s a detailed explanation of the provided code, including time complexity, space complexity, and a comparison of the two solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwh3VrV-PAG89ROdLj6oXg.png" /></figure><h3>Problem Statement</h3><p>LeetCode Problem 917: Reverse Only Letters</p><p>Given a string s, reverse the string according to the following rules:</p><ul><li>All characters that are not English letters remain in the same position.</li><li>All English letters (lowercase or uppercase) should be reversed.</li></ul><p>Return s after reversing it.</p><p>Example:</p><ul><li>Input: s = &quot;ab-cd&quot;</li><li>Output: dc-ba</li><li>Input: s = &quot;a-bC-dEf-ghIj&quot;</li><li>Output: j-Ih-gfE-dCba</li><li>Input: s = &quot;Test1ng-Leet=code-Q!&quot;</li><li>Output: Qedo1ct-eeLg=ntse-T!</li></ul><h3>Code Reference</h3><p>The complete code for the solutions can be found <a href="https://github.com/hemanthcse1/dsa-solutions/blob/main/src/main/java/problems/reverseonlyletters/ReverseOnlyLettersKotlin.kt">here</a>.</p><h3>Solutions</h3><h4>Solution 1: Using Stack</h4><pre>fun reverseOnlyLettersSolution1(s: String): String {<br>    val result = StringBuilder()<br>    val letters = Stack&lt;Char&gt;()<br>    val chars = s.toCharArray()<br><br>    // Push all letters onto the stack<br>    for (char in chars) {<br>        if (char.isLetter()) {<br>            letters.push(char)<br>        }<br>    }<br><br>    // Pop letters from the stack and append to result, keeping non-letters in place<br>    for (char in chars) {<br>        if (char.isLetter()) {<br>            result.append(letters.pop())<br>        } else {<br>            result.append(char)<br>        }<br>    }<br><br>    return result.toString()<br>}</pre><p>Explanation:</p><ul><li>Step 1: Traverse the string and push all letters onto a stack.</li><li>Step 2: Traverse the string again. For each letter, pop from the stack and append to the result. Append non-letters directly from the original string.</li></ul><p>Time Complexity:</p><ul><li>O(n), where n is the length of the string. Each character is processed twice.</li></ul><p>Space Complexity:</p><ul><li>O(n), for storing the characters in the stack and the result.</li></ul><h4>Solution 2: Using Two-Pointer Technique</h4><pre>fun reverseOnlyLettersSolution2(s: String): String {<br>    val chars = s.toCharArray()<br>    var i = 0<br>    var j = chars.size - 1<br><br>    // Two-pointer technique to reverse the letters<br>    while (i &lt; j) {<br>        if (!chars[i].isLetter()) {<br>            i++<br>        } else if (!chars[j].isLetter()) {<br>            j--<br>        } else {<br>            // Swap letters at i and j<br>            val temp = chars[i]<br>            chars[i] = chars[j]<br>            chars[j] = temp<br>            i++<br>            j--<br>        }<br>    }<br><br>    return String(chars)<br>}</pre><p>Explanation:</p><ul><li>Step 1: Convert the string to a char array.</li><li>Step 2: Use two pointers, i and j, starting from the beginning and end of the array.</li><li>Step 3: Move i forward and j backward until they point to letters. Swap the letters and move the pointers inward. Repeat until the pointers meet.</li></ul><p>Time Complexity:</p><ul><li>O(n), where n is the length of the string. Each character is processed at most once.</li></ul><p>Space Complexity:</p><ul><li>O(n), for the char array, but no additional data structures are used.</li></ul><h3>Conclusion</h3><p>Best Solution: reverseOnlyLettersSolution2 is generally better because:</p><ul><li>It has the same time complexity as Solution 1 (O(n)).</li><li>It has better space complexity (O(1) extra space compared to O(n) extra space).</li></ul><p>Solution 2 efficiently uses the two-pointer technique, making it more optimal in terms of memory usage, which is crucial for handling larger inputs effectively.</p><h3>Detailed Comments in Code</h3><pre>fun main() {<br>    val s = &quot;ab-cd&quot;<br>    println(&quot;Solution 1 -&gt; &quot; + reverseOnlyLettersSolution1(s))<br>    println(&quot;Solution 2 -&gt; &quot; + reverseOnlyLettersSolution2(s))<br>}<br><br>fun reverseOnlyLettersSolution1(s: String): String {<br>    val result = StringBuilder()<br>    val letters = Stack&lt;Char&gt;()<br>    val chars = s.toCharArray()<br><br>    // Push all letters onto the stack<br>    for (char in chars) {<br>        if (char.isLetter()) {<br>            letters.push(char)<br>        }<br>    }<br><br>    // Pop letters from the stack and append to result, keeping non-letters in place<br>    for (char in chars) {<br>        if (char.isLetter()) {<br>            result.append(letters.pop())<br>        } else {<br>            result.append(char)<br>        }<br>    }<br><br>    return result.toString()<br>}<br><br>fun reverseOnlyLettersSolution2(s: String): String {<br>    val chars = s.toCharArray()<br>    var i = 0<br>    var j = chars.size - 1<br><br>    // Two-pointer technique to reverse the letters<br>    while (i &lt; j) {<br>        if (!chars[i].isLetter()) {<br>            i++<br>        } else if (!chars[j].isLetter()) {<br>            j--<br>        } else {<br>            // Swap letters at i and j<br>            val temp = chars[i]<br>            chars[i] = chars[j]<br>            chars[j] = temp<br>            i++<br>            j--<br>        }<br>    }<br><br>    return String(chars)<br>}</pre><p>By analyzing both solutions, it is clear that Solution 2 is more efficient in terms of space, making it the preferable approach for this problem. For the complete code, you can refer to the <a href="https://github.com/hemanthcse1/dsa-solutions/blob/main/src/main/java/problems/reverseonlyletters/ReverseOnlyLettersKotlin.kt">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3663c781abd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Prefix of Word]]></title>
            <link>https://hemanthcse1.medium.com/reverse-prefix-of-word-1fbafdf623ff?source=rss-bbdb1d68a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fbafdf623ff</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <dc:creator><![CDATA[Hemanth Kumar N V]]></dc:creator>
            <pubDate>Sun, 19 May 2024 11:14:06 GMT</pubDate>
            <atom:updated>2024-05-19T11:14:37.750Z</atom:updated>
            <content:encoded><![CDATA[<p>Below is a problem statement from LeetCode, followed by explanations for each solution with detailed time and space complexity analyses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwh3VrV-PAG89ROdLj6oXg.png" /></figure><p><strong>Description:</strong> Given a 0-indexed string <strong>word</strong> and a character <strong>ch</strong>, reverse the segment of <strong>word</strong> that starts at the beginning of the string and ends at the first occurrence of <strong>ch</strong> (inclusive). If the character <strong>ch</strong> does not exist in <strong>word</strong>, return <strong>word</strong> as is.</p><p><strong>Example:</strong></p><pre>Input: word = &quot;abcdefd&quot;, ch = &#39;d&#39;<br>Output: &quot;dcbaefd&quot;<br>Explanation: The first occurrence of &#39;d&#39; is at index 3. Reverse the segment from the beginning to index 3: &quot;abcd&quot; -&gt; &quot;dcba&quot;. The result is &quot;dcbaefd&quot;.</pre><p>Code Reference: The complete code for the solutions can be found <a href="https://github.com/hemanthcse1/dsa-solutions/blob/feature/problems/src/main/java/problems/reverseprefixofword/ReversePrefixOfWordleetCode.kt">here</a>.</p><h3>Solutions</h3><h3>Solution 1: Using a Stack</h3><pre><br>fun reversePrefixSolution1(word: String, ch: Char): String {<br>    var result = StringBuilder()<br><br>    val firstOccurrence = word.indexOf(ch)<br>    if (firstOccurrence == -1) {<br>        return word<br>    }<br><br>    var letters: Stack&lt;Char&gt; = Stack()<br>    for (i in 0..firstOccurrence) {<br>        letters.push(word[i])<br>    }<br><br>    while (!letters.isEmpty()) {<br>        result.append(letters.pop())<br>    }<br><br>    for (i in (firstOccurrence + 1) until word.length) {<br>        result.append(word[i])<br>    }<br><br>    return result.toString()<br>}</pre><p><strong>Explanation:</strong></p><ul><li>This solution uses a <strong>Stack</strong> to reverse the prefix.</li><li>First, find the first occurrence of <strong>ch</strong>. If <strong>ch</strong> is not found, return the original word.</li><li>Push all characters from the start to the first occurrence of <strong>ch</strong> onto the stack.</li><li>Pop all characters from the stack and append them to the result to reverse the prefix.</li><li>Append the remaining characters of the word to the result.</li></ul><p><strong>Time Complexity:</strong></p><ul><li><strong>O(n)</strong>, where <strong>n</strong> is the length of the word. Each character is pushed and popped from the stack once.</li></ul><p><strong>Space Complexity:</strong></p><ul><li><strong>O(n)</strong>, for storing the characters in the stack and the result.</li></ul><h3>Solution 2: Using StringBuilder</h3><pre><br>fun reversePrefixSolution2(word: String, ch: Char): String {<br>    val result = StringBuilder()<br><br>    val firstOccurrence = word.indexOf(ch)<br>    if (firstOccurrence == -1) {<br>        return word<br>    }<br><br>    for (i in firstOccurrence downTo 0) {<br>        result.append(word[i])<br>    }<br><br>    for (i in (firstOccurrence + 1) until word.length) {<br>        result.append(word[i])<br>    }<br><br>    return result.toString()<br>}</pre><p><strong>Explanation:</strong></p><ul><li>This solution uses a <strong>StringBuilder</strong> to reverse the prefix.</li><li>Find the first occurrence of <strong>ch</strong>. If <strong>ch</strong> is not found, return the original word.</li><li>Append characters from the first occurrence down to the start to the <strong>StringBuilder</strong>.</li><li>Append the remaining characters of the word to the result.</li></ul><p><strong>Time Complexity:</strong></p><ul><li><strong>O(n)</strong>, where <strong>n</strong> is the length of the word. Each character is appended to the <strong>StringBuilder</strong> once.</li></ul><p><strong>Space Complexity:</strong></p><ul><li><strong>O(n)</strong>, for the <strong>StringBuilder</strong>.</li></ul><h3>Solution 3: Using a Character Array</h3><pre><br>fun reversePrefixSolution3(word: String, ch: Char): String {<br>    val firstOccurrence = word.indexOf(ch)<br>    if (firstOccurrence == -1){<br>        return word<br>    }<br><br>    val result = CharArray(word.length)<br><br>    for (i in 0..firstOccurrence){<br>        result[i] = word[firstOccurrence-i]<br>    }<br><br>    for (i in (firstOccurrence+1) until word.length){<br>        result[i] = word[i]<br>    }<br><br>    return String(result)<br>}</pre><p><strong>Explanation:</strong></p><ul><li>This solution uses a character array to reverse the prefix.</li><li>Find the first occurrence of <strong>ch</strong>. If <strong>ch</strong> is not found, return the original word.</li><li>Create a character array to store the result.</li><li>Fill the character array with the reversed prefix.</li><li>Copy the remaining characters of the word into the character array.</li><li>Convert the character array to a string and return it.</li></ul><p><strong>Time Complexity:</strong></p><ul><li><strong>O(n)</strong>, where <strong>n</strong> is the length of the word. Each character is processed once.</li></ul><p><strong>Space Complexity:</strong></p><ul><li><strong>O(n)</strong>, for the character array.</li></ul><h3>Conclusion</h3><p>All three solutions have the same time complexity of <strong>O(n)</strong>, but they differ in space complexity and efficiency. Solution 3 is the most memory-efficient, using a fixed-size character array instead of dynamic data structures like <strong>Stack</strong> or <strong>StringBuilder</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fbafdf623ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>