<?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 T Roshan Kumar Patro on Medium]]></title>
        <description><![CDATA[Stories by T Roshan Kumar Patro on Medium]]></description>
        <link>https://medium.com/@patro.roshan1997?source=rss-b230c0fdbe13------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yLOYZUOf7F3ATWWwYyoCEg.jpeg</url>
            <title>Stories by T Roshan Kumar Patro on Medium</title>
            <link>https://medium.com/@patro.roshan1997?source=rss-b230c0fdbe13------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:40:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patro.roshan1997/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[Why Your Java LeetCode Code Is Returning the Wrong Answer (Even Though It’s Correct)]]></title>
            <link>https://medium.com/@patro.roshan1997/why-your-java-leetcode-code-is-returning-the-wrong-answer-even-though-its-correct-c1386db980b1?source=rss-b230c0fdbe13------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1386db980b1</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[T Roshan Kumar Patro]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 16:09:59 GMT</pubDate>
            <atom:updated>2025-07-03T16:09:59.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCbKHfK2v_-p4Diam9Z43A.png" /></figure><p><strong>Why read this ❔</strong></p><p>Ever scratched your head wondering why your LeetCode Java solution works locally but fails online, or worse, returns old answers for new test cases?</p><p>This article unpacks a surprisingly common bug caused by static variables, explains how LeetCode really runs your code, and gives you clean, simple fixes.</p><p>If you’ve ever yelled “But it works on my machine!”, this one’s for you.</p><p><strong>Let’s go 🟢</strong></p><p>Ever written the perfect solution on LeetCode, but it somehow returns the wrong answer? And not just wrong, it’s mysteriously repeating the result of an earlier test case?</p><p>If this sounds familiar, especially when using static variables in Java, you’re not alone.</p><p>Let’s unravel this behavior and see how you can fix it (and avoid it entirely in the future).</p><h4><strong>The Mystery of the Stuck Output</strong></h4><p>Imagine this simple Java class:</p><pre>class Solution {<br>    static int maxValue = 0;<br><br>    public int solve(int[] nums) {<br>        for (int n : nums) {<br>            maxValue = Math.max(maxValue, n);<br>        }<br>        return maxValue;<br>    }<br>}</pre><p><strong>On LeetCode, let’s say this runs with two test cases:</strong></p><p>[1, 3, 2] → returns 3</p><p>[2, 1] → unexpectedly returns 3 again</p><p>Wait, what? The second test case doesn’t even have a 3.</p><p>Welcome to the world of <strong>static </strong>variable side effects in Java on platforms like <strong>LeetCode</strong>.</p><h4><strong>🤔 What’s Actually Happening?</strong></h4><p>The line causing this problem is:</p><pre>static int maxValue = 0;</pre><p>This line creates a class-level variable that:</p><ul><li>Persists for the entire lifecycle of the class.</li><li>Doesn’t reset between test cases on LeetCode.</li><li>Will continue to hold the value set in the first test case, unless you manually reset it.</li></ul><h4><strong>⚙️ Why LeetCode (and others) Reuse the Solution Class</strong></h4><p>When you hit Run or Submit on <strong>LeetCode</strong>, your Solution class is:</p><ul><li>Compiled once, and</li><li>Reused across all test cases</li></ul><p><strong>This isn’t a bug, it’s a deliberate design for performance:</strong></p><ul><li>Reduces memory usage</li><li>Minimizes garbage collection overhead</li><li>Speeds up evaluation for large batches of test cases</li></ul><p>🧠 <strong>Garbage collection</strong> is Java’s way of cleaning up unused objects. But creating and deleting thousands of objects (like a new Solution per test case) would slow things down. So instead, they reuse one object and just run different inputs through it.</p><h4><strong>🧼 So, How Do You Clean It Up?</strong></h4><p>Easy. Just reset your static variable at the start of your method:</p><pre>public int solve(int[] nums) {<br>    maxValue = 0;  // Always reset before starting<br>    for (int n : nums) {<br>        maxValue = Math.max(maxValue, n);<br>    }<br>    return maxValue;<br>}</pre><h4><strong>🔒 But Wait. Should You Even Use static?</strong></h4><p>Good question. While using static works if you’re careful, it’s often better to avoid it entirely in coding problems. Here’s how:</p><h4><strong>✅ Safer Alternatives to static in Recursion/DP Problems</strong></h4><ul><li>Use an int[] array as a mutable wrapper</li></ul><pre>int[] maxLen = new int[1];<br>recurse(..., maxLen);<br>return maxLen[0];</pre><ul><li>Create a custom wrapper class</li></ul><pre>class Result {<br>    int max = 0;<br>}</pre><ul><li>Use AtomicInteger</li></ul><pre>AtomicInteger max = new AtomicInteger(0);</pre><p>These approaches pass a reference to your recursive method, so updates made inside are visible outside too, just like you’d want.</p><h4><strong>🧠 Pro Tip: Know How Java Passes Variables</strong></h4><ul><li>Java is always <strong>pass-by-value</strong>.</li><li>When you pass a primitive like int, a copy is made.</li><li>So, updating int max inside a method does not affect the original.</li><li>But objects (like int[] or custom classes) are passed as copies of references, so updates do reflect outside.</li></ul><h4><strong>✨ Bonus Analogy: The Whiteboard</strong></h4><p>Let’s say you’re running a pizza shop and people place orders.</p><p><strong>🍕 Scenario 1: Passing a Primitive (int)</strong></p><ul><li>A customer tells you their favorite pizza is Pizza #5.</li><li>You write it on a sticky note and hand a copy of that note to your assistant.</li><li>Your assistant decides to change the note to Pizza #7.</li><li>But your original note still says Pizza #5, because they changed their own copy.</li></ul><blockquote>That’s how Java handles primitives. It passes a copy of the value.</blockquote><p><strong>🍕 Scenario 2: Passing a Reference (like int[] or a class)</strong></p><ul><li>Instead of a sticky note, you and your assistant both look at the same digital order screen.</li><li>When the assistant updates the order to Pizza #7, you immediately see the change on your screen, too.</li></ul><blockquote>That’s how Java handles objects. It passes a reference to the shared data, so changes are visible everywhere.</blockquote><h4><strong>🔚 Wrap Up</strong></h4><p>If you ever see your Java code on LeetCode mysteriously returning stale values:</p><p>✅ Check for static variables<br>✅ Reset them manually<br>✅ Or better, avoid them altogether</p><p>You now understand not just what happens, but why, and that makes all the difference.</p><p>Thank you so much for reading this so far by giving your valuable time. I am indeed thankful to each one of you 🙏🧡. Please, consider giving your feedback and suggestions in the comment section so that I can improve in many aspects. I would appreciate it if you put your query in the comment section and give me a chance to address and help you with it.</p><p>Wishing you become your best version for no reason. 🌈✌😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1386db980b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring Consistent Property Usage in Spring Boot: Best Practices]]></title>
            <link>https://medium.com/@patro.roshan1997/ensuring-consistent-property-usage-in-spring-boot-best-practices-ac0e2f823e5c?source=rss-b230c0fdbe13------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac0e2f823e5c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[T Roshan Kumar Patro]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 11:10:17 GMT</pubDate>
            <atom:updated>2024-11-21T11:33:46.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jPJpuXyzrbHX7BRmN1ZPOQ.png" /></figure><h4>Why read this ❔</h4><p>This article highlights the importance of consistent usage of configuration properties in Spring Boot applications. We’ll explore common pitfalls and provide best practices to improve code clarity, maintainability, and reduce potential bugs. Whether you’re a beginner or an experienced developer, these simple techniques will help you write cleaner, more scalable code.</p><h4><strong>Let’s go</strong> 🟢</h4><p>In Spring Boot applications, the configuration properties defined in the application.properties or application.yml file, play a crucial role in managing environment-specific configurations. These properties often represent critical elements like database URLs, external service endpoints, or queue identifiers. However, inconsistent usage of these properties across the codebase can lead to confusion, reduced maintainability, and potential bugs.</p><h4>The Problem: Inconsistent Variable Naming for the Same Property</h4><p>Imagine a scenario where a property (aws.sqs.booking.abandon) is defined in the application.properties file to represent the URL of an AWS SQS queue for booking abandonment:</p><pre>aws.sqs.booking.abandon=https://sqs.ap-south-1.amazonaws.com/254120170121/booking_abandon</pre><p>Now consider the following usage in different parts of the codebase:</p><pre>@Value(&quot;${aws.sqs.booking.abandon}&quot;)<br>String SQS_FOR_FAILED_BOOKINGS;</pre><pre>@Value(&quot;${aws.sqs.booking.abandon}&quot;)<br>String SQS_FOR_BOOKING_ABANDON;</pre><p>While this code works, the inconsistency in variable naming (SQS_FOR_FAILED_BOOKINGS vs. SQS_FOR_BOOKING_ABANDON) creates ambiguity. Developers might assume these refer to different queues or configurations when they both reference the same property.</p><h4>Why Is This a Problem?</h4><ol><li><strong>Confusion</strong>:<br>- The variable names suggest different purposes, making it unclear that both refer to the same queue URL.</li><li><strong>Reduced Maintainability</strong>:<br>- If the queue’s purpose or URL changes, updating the code becomes harder as you must trace and understand the inconsistent usage.</li><li><strong>Potential Bugs</strong>:<br>- Misunderstandings in naming can lead to errors in logic or unintended behavior when modifying the code.</li><li><strong>Code Smell</strong>:<br>- Such inconsistency violates coding best practices by failing to adhere to the principle of clarity and uniformity.</li></ol><h4>Best Practices for Consistent Property Management</h4><p>To ensure clarity and maintainability, follow these best practices for managing and using configuration properties in Spring Boot applications:</p><h4>1. Use Consistent Naming Conventions</h4><p>Ensure variable names reflect the property name and purpose consistently across all classes. For example:</p><pre>@Value(&quot;${aws.sqs.booking.abandon}&quot;)<br>String sqsBookingAbandonQueue;</pre><p>This makes it immediately clear that the variable represents the SQS queue for booking abandonment.</p><h4><strong>2. Define Constants for Common Properties</strong></h4><p>If the same property is used in multiple places, define a constant in a shared utility class. For instance:</p><p><strong>AppConstants.java</strong></p><pre>public class AppConstants {<br>    public static final String SQS_BOOKING_ABANDON_PROPERTY = &quot;aws.sqs.booking.abandon&quot;;<br>}</pre><p><strong>Usage in Code:</strong></p><pre>@Value(&quot;${&quot; + AppConstants.SQS_BOOKING_ABANDON_PROPERTY + &quot;}&quot;)<br>String sqsBookingAbandonQueue;</pre><p>This approach eliminates duplication and centralizes the property reference, making it easier to update in the future.</p><h4><strong>3. Leverage </strong><strong>@ConfigurationProperties for Grouped Properties</strong></h4><p>Group related properties using a dedicated class annotated with @ConfigurationProperties. This method allows for structured and reusable configuration management.</p><pre>aws.sqs.booking.abandon=https://sqs.ap-south-1.amazonaws.com/254120170121/booking_abandon<br>aws.sqs.booking.success=https://sqs.ap-south-1.amazonaws.com/254120170121/booking_success<br>aws.sqs.booking.failed=https://sqs.ap-south-1.amazonaws.com/254120170121/booking_failed</pre><p><strong>AwsSqsProperties.java</strong></p><pre>import org.springframework.boot.context.properties.ConfigurationProperties;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>@ConfigurationProperties(prefix = &quot;aws.sqs.booking&quot;)<br>public class AwsSqsProperties {<br><br>    private String abandon;<br>    private String success;<br>    private String failed;<br><br>    // Getters and Setters<br>    public String getAbandon() {<br>        return abandon;<br>    }<br><br>    public void setAbandon(String abandon) {<br>        this.abandon = abandon;<br>    }<br><br>    public String getSuccess() {<br>        return success;<br>    }<br><br>    public void setSuccess(String success) {<br>        this.success = success;<br>    }<br><br>    public String getFailed() {<br>        return failed;<br>    }<br><br>    public void setFailed(String failed) {<br>        this.failed = failed;<br>    }<br>}</pre><p>You need to enable configuration properties binding in your Spring Boot application. This can be done by adding @EnableConfigurationProperties in your main application class or by using the @Configuration annotation if needed.</p><pre>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.boot.context.properties.EnableConfigurationProperties;<br><br>@SpringBootApplication<br>@EnableConfigurationProperties(AwsSqsProperties.class) // Enable binding for AwsSqsProperties<br>public class YourApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(YourApplication.class, args);<br>    }<br>}</pre><p><strong>Usage in Code:</strong></p><p><strong>SqsService.java</strong></p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class SqsService {<br><br>    private final AwsSqsProperties awsSqsProperties;<br><br>    @Autowired<br>    public SqsService(AwsSqsProperties awsSqsProperties) {<br>        this.awsSqsProperties = awsSqsProperties;<br>    }<br><br>    public void processBookingAbandon() {<br>        String abandonQueueUrl = awsSqsProperties.getAbandon();<br>        // Use the abandonQueueUrl<br>        System.out.println(&quot;Processing SQS URL: &quot; + abandonQueueUrl);<br>    }<br><br>    public void processBookingSuccess() {<br>        String successQueueUrl = awsSqsProperties.getSuccess();<br>        // Use the successQueueUrl<br>        System.out.println(&quot;Processing SQS URL: &quot; + successQueueUrl);<br>    }<br><br>    public void processBookingFailed() {<br>        String failedQueueUrl = awsSqsProperties.getFailed();<br>        // Use the failedQueueUrl<br>        System.out.println(&quot;Processing SQS URL: &quot; + failedQueueUrl);<br>    }<br>}</pre><p>This approach provides a clear structure and eliminates the need to repeatedly use @Value annotations.</p><h4>4. Add Meaningful Comments</h4><p>Wherever properties are used, include comments to clarify their purpose, especially when their role might not be evident from the name alone.</p><pre>@Value(&quot;${aws.sqs.booking.abandon}&quot;) // Queue for booking abandonment checks<br>String sqsBookingAbandonQueue;</pre><h4>5. Use Descriptive Names for Property Keys</h4><p>Ensure property keys in application.properties are self-explanatory. For example:</p><ul><li>Prefer: aws.sqs.booking.abandon</li><li>Avoid: aws.sqs.bk.abdn</li></ul><p>Descriptive keys reduce cognitive load and make it easier to understand the configuration at a glance.</p><h4>Conclusion</h4><p>Managing configuration properties consistently is critical for building maintainable and robust Spring Boot applications. Avoiding inconsistent variable naming for the same property is a simple yet effective step toward clearer and cleaner code.</p><p>By following the practices outlined in this article — consistent naming conventions, shared constants, @ConfigurationProperties, meaningful comments, and descriptive property keys, you can eliminate confusion, improve maintainability, and ensure your application remains scalable and easy to work with.</p><p>Consistency isn’t just a nicety, it’s a cornerstone of professional software development. Start applying these best practices today!</p><p>Thank you so much for reading this so far by giving your valuable time. I am indeed thankful to each one of you 🙏🧡. Please, consider giving your feedback and suggestions in the comment section so that I can improve in all possible aspects. I would appreciate it if you put your query in the comment section and give me a chance to address and help you with it.</p><p>If you found this article value-adding, please acknowledge it by clapping on it. Your support means a lot! 👏</p><p><strong>Wish you become your best version for no reason. 🌈✌😃</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac0e2f823e5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why does MySQL Workbench open much faster than PgAdmin4 even though both are installed locally?]]></title>
            <link>https://medium.com/@patro.roshan1997/why-does-mysql-workbench-open-much-faster-than-pgadmin4-even-though-both-are-installed-locally-8255db4af117?source=rss-b230c0fdbe13------2</link>
            <guid isPermaLink="false">https://medium.com/p/8255db4af117</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[T Roshan Kumar Patro]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 12:37:58 GMT</pubDate>
            <atom:updated>2024-10-15T12:41:14.664Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rFAFiya8JuF91HfOcLZiNQ.png" /></figure><p><strong>Why read this ❔</strong></p><p>If you’ve ever wondered why MySQL Workbench seems to launch much faster than PgAdmin4, this article is for you. Whether you’re a developer or database administrator working with both MySQL and PostgreSQL, understanding the reasons behind the performance differences can help you choose the right tool for your workflow. In this article, we’ll explore the technical factors, such as resource usage, architecture, and underlying technologies, that contribute to this disparity.</p><p><strong>Let’s go 🟢</strong></p><p>The main reason <strong>MySQL Workbench</strong> opens much faster than <strong>PgAdmin4</strong> is due to their underlying architectures and how they handle the startup process. Here are the key factors contributing to PgAdmin4’s slower startup:</p><ol><li><strong>Web-Based vs. Native Desktop Application</strong></li></ol><ul><li><strong>PgAdmin4</strong> is built as a web-based application, even though it can run as a desktop app. When you open PgAdmin4, it Starts a <strong>local web server</strong> (usually a Python Flask server), initializes an <strong>embedded browser</strong> (such as Electron or QtWebEngine) to render the user interface, and loads web-based resources (HTML, CSS, JavaScript) to display the interface.</li><li>This multi-step process takes time because both the web server and the embedded browser need to start up and communicate with each other.</li><li><strong>MySQL Workbench</strong>, on the other hand, is a <strong>native desktop application</strong>. It doesn’t need to start a web server or browser engine. Everything, including the UI, is handled by a single application running natively on your system. This significantly reduces the startup time since there are fewer components to initialize.</li></ul><p><strong>2. Startup Overhead (Web Server Initialization)</strong></p><ul><li><strong>PgAdmin4</strong> needs to initialize a local Python environment to run its web server. This includes loading the Python interpreter and associated libraries, initializing the Flask server, and establishing communication between the front-end (UI) and the back-end (database connections).</li><li>These steps are inherently slower than just launching a native desktop application like MySQL Workbench.</li></ul><p><strong>3. Resource-Heavy Components</strong></p><ul><li><strong>PgAdmin4</strong> runs an embedded browser or uses a web-based UI framework (Electron or similar) to render its interface. This means it has to load web components like JavaScript, CSS, and HTML and render the UI inside the browser.</li><li>This browser-like rendering process is slower and more resource-intensive compared to MySQL Workbench’s native GUI toolkit, which doesn’t rely on web technologies for its UI.</li></ul><p><strong>4. Electron (If Used by PgAdmin4)</strong></p><ul><li>If <strong>PgAdmin4</strong> uses <strong>Electron</strong> (a popular framework for building cross-platform desktop apps using web technologies), it further adds to the startup time. Electron essentially bundles a web browser (Chromium) and Node.js, making applications heavier and slower to launch.</li><li><strong>MySQL Workbench</strong> is a more lightweight application in this respect because it’s compiled as a native executable, not a hybrid browser/JavaScript environment.</li></ul><p><strong>5. Initialization of Extensions and Plugins</strong></p><ul><li>PgAdmin4 might also take longer if it loads additional extensions or plugins at startup. Some of these may need to establish connections to the database, initialize their resources, or load specific configurations, adding more time to the startup process.</li><li><strong>MySQL Workbench</strong> is designed with a more optimized startup routine, focusing on fast initialization of core functionalities.</li></ul><p><strong>6. System Resources and Dependencies</strong></p><ul><li>PgAdmin4 may require more system resources like memory and CPU at startup due to the multiple layers it needs to initialize (web server, browser engine, etc.). On systems with limited resources, this can be more noticeable.</li><li>MySQL Workbench, being native and lightweight, consumes fewer resources, making the startup process faster.</li></ul><p><strong>Real-World Analogies 🤩: Understanding the Startup Differences:</strong></p><p>Imagine you’re setting up a movie night. Using PgAdmin4 is like setting up a projector: first, you need to plug it in, adjust the screen, and make sure everything is aligned (start the “web server”). Then, you need to connect your laptop to the projector (open the “browser”) before you can start watching the movie. It’s a bit of a setup process, even though it’s all happening in the same room.</p><p>On the other hand, using MySQL Workbench is like turning on your TV. You just press the power button, and the movie starts playing right away. No extra equipment or connections are needed.</p><p>This extra setup for PgAdmin4 is why it takes longer to get started, while MySQL Workbench, like a TV, is ready to go almost immediately.</p><p><strong>Summary:</strong></p><p>The key reasons <strong>PgAdmin4</strong> takes longer to open than <strong>MySQL Workbench</strong> are its web-based architecture, which requires starting a local web server and a browser engine, and the resource-heavy nature of web technologies like JavaScript and HTML rendering. In contrast, MySQL Workbench is a streamlined native desktop app, designed for fast startup and efficient resource usage.</p><p>Thank you so much for reading this so far by giving your valuable time. I am indeed thankful to each one of you 🙏🧡. Please, consider giving your feedback and suggestions in the comment section so that I can improve in all possible aspects. I would appreciate it if you put your query in the comment section and give me a chance to address and help you with it.</p><p><strong>Wish you become your best version for no reason. 🌈✌😃</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8255db4af117" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Resolving the ‘Cannot reference ‘SampleRecord.sampleMethod()’]]></title>
            <link>https://medium.com/@patro.roshan1997/understanding-and-resolving-the-cannot-reference-samplerecord-samplemethod-c0ead8886f9c?source=rss-b230c0fdbe13------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0ead8886f9c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[T Roshan Kumar Patro]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 19:17:14 GMT</pubDate>
            <atom:updated>2024-10-12T19:19:26.154Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding and Resolving the ‘Cannot reference ‘SampleRecord.sampleMethod()’ before supertype constructor has been called’ Error in Java</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75y0JAfG5FJRED_iSKEZQg.jpeg" /></figure><h3><strong>Why read this ❔</strong></h3><p>When faced with exceptions or error messages, deciphering the underlying issue can feel like navigating a labyrinth. Resolving such challenges often demands extensive analysis, consultation with various resources, and significant time investment. Unfortunately, these endeavors frequently consume valuable development time. The ‘Cannot reference…’ error exemplifies one such compile-time exception that can impede progress and productivity.</p><h3><strong>Let’s go 🟢</strong></h3><h3><strong>What does the error technically mean?</strong></h3><p>The error message “Cannot reference ‘SampleRecord.sampleMethod()’ before supertype constructor has been called” typically occurs in Java when a constructor in a record class attempts to reference an instance method before invoking the superclass constructor.</p><h3><strong>Code with error:</strong></h3><pre>public record SampleRecord(String userType, String txnId, String paymentId, String bookingStatus,<br>                           String userId) {<br><br>  public SampleRecord(Payment payment, String userType, String txnId) {<br>    this(userType, txnId, payment.getId().toString(), payment.getBooking().getStatus().toString(),<br>        computeUserId(payment, userType));<br>  }<br><br>  private String computeUserId(Payment payment, String userType) {<br>    if (&quot;CHARTER&quot;.equalsIgnoreCase(userType)) {<br>      return payment.getBooking().getUser().getCharterOperator().getId().toString();<br>    } else {<br>      return payment.getBooking().getUser().getId().toString();<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*bfRvhfwSm2FQSWZTD3DYRw.png" /></figure><p><strong>Error Explanation:</strong></p><p><strong>Cannot reference ‘SampleRecord.computeUserId()’ before supertype constructor has been called</strong> is a compilation error in Java that occurs when you try to use an instance method (like computeUserId()) or reference instance fields inside a constructor <strong>before the superclass constructor (implicitly or explicitly) has been called</strong>. This happens specifically in record classes due to their special construction behavior.</p><p>Here, computeUserId(payment, userType) is called before the this(...) constructor call completes, which triggers the error because:</p><ol><li>The this(...) constructor is invoking the <strong>record’s canonical constructor</strong>, which internally calls the superclass constructor (implicitly super()).</li><li>Until the <strong>record’s</strong> canonical constructor has been called and the superclass constructor finishes executing, the instance is not fully constructed.</li><li><strong>Instance methods</strong> (like computeUserId()) require the instance to be fully initialized, which hasn’t happened yet, because the constructor is still in progress.</li></ol><p>In simpler terms, <strong>we cannot use </strong><strong>this to call instance methods until all fields are initialized and the superclass constructor has run</strong>.</p><h3><strong>Solution 1: Make computeUserId(…) </strong><strong>static</strong>:</h3><p><strong>Fixed Code:</strong></p><pre>public record SampleRecord(String userType, String txnId, String paymentId, String bookingStatus,<br>                           String userId) {<br><br>  public SampleRecord(Payment payment, String userType, String txnId) {<br>    this(userType, txnId, payment.getId().toString(), payment.getBooking().getStatus().toString(),<br>        computeUserId(payment, userType));<br>  }<br><br>  private static String computeUserId(Payment payment, String userType) {<br>    if (&quot;CHARTER&quot;.equalsIgnoreCase(userType)) {<br>      return payment.getBooking().getUser().getCharterOperator().getId().toString();<br>    } else {<br>      return payment.getBooking().getUser().getId().toString();<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*d5AxREnH56-JZ-fa293XSg.png" /></figure><p><strong>Why </strong><strong>static works</strong>:</p><ul><li><strong>Static methods</strong> belong to the class rather than the instance of the class. This means they don’t rely on an object being constructed and can be called without creating an instance of the class.</li><li>When you mark computeUserId() as static, it no longer requires access to instance-specific data, so Java doesn’t need the object to be fully constructed to call it.</li></ul><h3><strong>Solution 2:</strong> <strong>Inline the logic</strong> <strong>directly in the constructor:</strong></h3><p><strong>Fixed Code:</strong></p><pre>public record SampleRecord(String userType, String txnId, String paymentId, String bookingStatus,<br>                           String userId) {<br><br>  public SampleRecord(Payment payment, String userType, String txnId) {<br>    this(userType, txnId, payment.getId().toString(), payment.getBooking().getStatus().toString(),<br>        &quot;CHARTER&quot;.equalsIgnoreCase(userType)<br>            ? payment.getBooking().getUser().getCharterOperator().getId().toString()<br>            : payment.getBooking().getUser().getId().toString());<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*cVHvzZXdon2llwiUKBRzwA.png" /></figure><p>In this approach, the logic for computing userId based on the userType is directly embedded into the constructor call instead of being placed in a separate method like computeUserId().</p><p>Thank you so much for reading this so far by giving your valuable time. I am indeed thankful to each one of you 🙏🧡. Please, consider giving your feedback and suggestions in the comment section so that I can improve in all possible aspects. I would appreciate it if you put your query in the comment section and give me a chance to address and help you with it.</p><p><strong>Wish you become your best version for no reason. 🌈✌😃</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0ead8886f9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rethinking Spring Boot: Unmasking the Dangers of @Autowired Field Injection]]></title>
            <link>https://medium.com/@patro.roshan1997/rethinking-spring-boot-unmasking-the-dangers-of-autowired-field-injection-c49aa0424054?source=rss-b230c0fdbe13------2</link>
            <guid isPermaLink="false">https://medium.com/p/c49aa0424054</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[T Roshan Kumar Patro]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 18:12:06 GMT</pubDate>
            <atom:updated>2024-01-16T18:12:06.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NaaBbbk46YUKhNAPd2gqHg.png" /></figure><p><strong>Why read this</strong>❔</p><p>We’ll delve into why you might want to reconsider using <a href="http://twitter.com/Autowired">@Autowired</a> field injection in your Spring Boot applications. Discover the potential drawbacks and pitfalls that could impact your application’s maintainability, testability, and overall code quality. Gain insights into alternative dependency injection strategies and best practices that lead to more robust and scalable Spring Boot projects. Whether you’re a seasoned developer or a newcomer to Spring Boot, this section will equip you with valuable knowledge to enhance the design and resilience of your application.</p><p><strong>Let’s go</strong> 🟢</p><p>As a Java developer, a strong command of the Spring framework is essential. Among its versatile features, Dependency Injection (DI) in Spring’s Inversion of Control (IoC) container stands out as both widely adopted and highly convenient for developers. This feature is pivotal in simplifying the coding process, making it an indispensable tool for programmers.</p><pre>@Service<br>public class ExampleServiceImpl implements ExampleService {<br><br>  @Autowired<br>  private ExampleRepository exampleRepository;<br><br>  @Autowired<br>  private UserService userService;<br>  <br>  // ........<br>}</pre><p>Like the above code example, many people use the @Autowired annotation to implement the Dependency injection function. Spring no longer recommends using @Autowired with fields after Spring Framework 4.0. Instead, Spring recommends constructor injection and setter injection.</p><h4><strong>Dependency injection types</strong></h4><p>In Spring, the @Autowired annotation is primarily used for dependency injection. Several types of dependency injection can be achieved using @Autowired:</p><ul><li><strong>Constructor Injection:</strong></li></ul><pre>@Component<br>public class MyService {<br><br>    private final MyDependency myDependency;<br><br>    @Autowired<br>    public MyService(MyDependency myDependency) {<br>        this.myDependency = myDependency;<br>    }<br><br>    // Other methods using myDependency...<br>}</pre><ul><li><strong>Setter Injection:</strong></li></ul><pre>public class MyClass {<br><br>    private MyDependency myDependency;<br><br>    @Autowired<br>    public void setMyDependency(MyDependency myDependency) {<br>        this.myDependency = myDependency;<br>    }<br><br>    // Other methods using myDependency...<br>}</pre><ul><li><strong>Field Injection:</strong></li></ul><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class MyService {<br><br>    @Autowired<br>    private MyDependency myDependency;<br><br>    // rest of the class...<br>}</pre><ul><li><strong>Method Injection (in Spring 4.3+):</strong></li></ul><pre>public class MyService {<br><br>    private MyDependency myDependency;<br><br>    // ...<br><br>    @Autowired<br>    public void injectDependency(MyDependency myDependency) {<br>        this.myDependency = myDependency;<br>    }<br><br>    public void performOperation() {<br>        // Use the injected dependency in your method logic<br>        if (myDependency != null) {<br>            myDependency.doSomething();<br>        } else {<br>            // Handle the case where the dependency is not injected<br>        }<br>    }<br><br>    // Other methods...<br><br>}</pre><h3><strong>Constructor Injection:</strong></h3><p>Constructor injection is a form of dependency injection in which dependencies are injected through a class constructor. In the context of the Spring framework, constructor injection is a preferred method for achieving inversion of control (IoC) and managing dependencies.</p><p>A constructor is a special method in a Java class that is invoked when an object of that class is created. Constructor injection involves defining one or more constructors in a class to receive dependencies as parameters.</p><p>Dependencies are declared as private fields in the class.<br>These fields represent the required dependencies that the class needs to perform its functionality.</p><pre>public class MyClass {<br><br>    private Dependency dependency;<br><br>    @Autowired<br>    public MyClass(Dependency dependency) {<br>        this.dependency = dependency;<br>    }<br><br>    // Other methods...<br>}</pre><p><strong>Benefits of Constructor Injection:</strong></p><ul><li><strong>Clear Dependency Declaration:</strong> Constructor parameters explicitly declare the dependencies, making it clear what is required for the class to function.</li><li><strong>Immutable Dependencies:</strong> Once set in the constructor, dependencies are usually immutable, promoting a safer and more predictable state.</li></ul><p>A class can have multiple constructors, each receiving different sets of dependencies. Spring can determine which constructor to use based on the available beans in the context.</p><pre>public class MyClass {<br><br>    private Dependency dependency;<br><br>    @Autowired<br>    public MyClass(Dependency dependency) {<br>        this.dependency = dependency;<br>    }<br><br>    // Another constructor without @Autowired<br>    public MyClass() {<br>        // No dependencies are injected here<br>    }<br><br>    // Other methods...<br>}</pre><p>Constructor injection is a clean and explicit way to express dependencies, and it aligns well with the principles of dependency injection and IoC. It makes classes more testable and facilitates better modularization of the code.</p><h3>Setter Injection:</h3><p>Setter injection is a type of dependency injection in Spring where dependencies are injected through setter methods of a class. This injection is typically done through the use of the <a href="http://twitter.com/Autowired">@Autowired</a> annotation on setter methods.</p><pre>public class MyService {<br><br>    private MyDependency myDependency;<br><br>    // Setter method for dependency<br>    @Autowired<br>    public void setMyDependency(MyDependency myDependency) {<br>        this.myDependency = myDependency;<br>    }<br><br>    // Other methods...<br>}</pre><p>Create a setter method for each dependency you want to inject. Annotate each setter method with <a href="http://twitter.com/Autowired">@Autowired</a> to indicate that Spring should inject the dependency through this method.</p><p><strong>Advantages of Setter Injection:</strong></p><ul><li>Provides flexibility in changing dependencies dynamically.</li><li>Allows for optional dependencies by not enforcing them in the constructor.</li><li>Easy to understand and use.</li></ul><h3>Field Injection:</h3><p>Field injection is a method of Dependency Injection in Spring where dependencies are injected directly into the fields of a class. It involves annotating the fields with the <a href="http://twitter.com/Autowired">@Autowired</a> annotation. Field injection is simple and concise, but it has some drawbacks and is considered less preferable in certain scenarios.</p><pre>@Service<br>public class MyService {<br><br>    @Autowired<br>    private MyDependency myDependency;<br><br>    // Rest of the class...<br><br>    public void performOperation() {<br>        // Use the injected dependency in your method logic<br>        if (myDependency != null) {<br>            myDependency.doSomething();<br>        } else {<br>            // Handle the case where the dependency is not injected<br>        }<br>    }<br><br>    // Other methods...<br><br>}</pre><p>In this example, the MyDependency field is annotated with <a href="http://twitter.com/Autowired">@Autowired</a>, and Spring will inject the corresponding bean into this field during the bean creation process.</p><p><strong>Advantages of Field Injection:</strong></p><ul><li><strong>Simplicity</strong>: Field injection is concise and requires less boilerplate code compared to constructor or setter injection.</li><li><strong>Readability</strong>: The code looks cleaner and more straightforward.</li></ul><p><strong>Drawbacks and Considerations:</strong></p><ul><li><strong>Testing</strong>: Field injection can make unit testing more challenging because you cannot easily substitute dependencies for testing.</li><li><strong>Readability in Tests</strong>: It might be less clear in tests which dependencies are being used because they are not explicitly settable via constructors or setters.</li><li><strong>Circular Dependencies</strong>: Field injection can lead to issues with circular dependencies, where beans depend on each other in a cycle.</li></ul><h3>Which one is the most favored and why?</h3><p>Constructor injection is generally considered the most favored form of dependency injection, and it is often recommended as a best practice in the Spring framework. There are several reasons for this perspective:</p><ul><li><strong>Readability</strong>: Constructor injection makes dependencies explicit in the class’s constructor, making it clear which dependencies are required.</li><li><strong>Immutable Instances</strong>: Constructor injection encourages immutability by allowing you to set dependencies only once during the object’s creation.</li><li><strong>Easier Testing</strong>: Constructor injection facilitates easier unit testing. You can create instances of the class with mock or test implementations of dependencies easily by passing them through the constructor.</li><li><strong>Circular Dependency Resolution</strong>: Constructor injection helps avoid issues related to circular dependencies. When dependencies are injected through the constructor, the order in which beans are created becomes less critical.</li><li><strong>Consistent State</strong>: Objects are constructed in a complete and consistent state. All required dependencies are available at the time of instantiation.</li><li><strong>Avoids Null Checks</strong>: Constructor injection avoids the need for null checks on injected dependencies within the class methods.</li><li><strong>Dependency Inversion Principle (DIP)</strong>: Constructor injection aligns with the Dependency Inversion Principle, which states that high-level modules should not depend on low-level modules but should depend on abstractions.</li><li><strong>Spring Guidelines</strong>: The Spring framework documentation and guidelines often recommend constructor injection as the primary and most readable form of dependency injection.</li></ul><h3>Which one is the least favored and why?</h3><p>Field injection is generally considered the least favored dependency injection method in Spring, and there are several reasons for this perspective:</p><ul><li><strong>Testing Challenges</strong>: Field injection makes it challenging to substitute dependencies during testing. In unit tests, it’s often beneficial to replace actual dependencies with mocks or stubs, and field injection provides less flexibility in achieving this.</li><li><strong>Readability in Tests</strong>: In tests, it might be less clear which dependencies are being used by a class because they are not explicitly settable via constructors or setters. This can make it harder to understand the test scenarios and the interactions between components.</li><li><strong>Circular Dependencies</strong>: Field injection can lead to issues with circular dependencies. Circular dependencies occur when two or more beans depend on each other, forming a cycle. Constructor injection is less prone to circular dependency problems.</li><li><strong>Immutable Classes</strong>: Field injection makes it harder to create immutable classes because dependencies are injected directly into fields. Immutable classes (those with final fields and no setters) are generally considered more thread-safe and easier to reason about.</li></ul><p>In summary, the “best” dependency injection method depends on the context and the specific needs of your application. Constructor injection is generally favored for its adherence to good design principles and ease of testing. However, the choice may vary based on specific use cases and design considerations.</p><p><strong>To explore more:</strong></p><ul><li><a href="https://spring.io/projects/spring-framework/">Spring Framework</a></li><li><a href="https://spring.io/projects/spring-boot/">Spring Boot</a></li></ul><p>Thank you so much for reading this so far by giving your valuable time. I am indeed thankful to each one of you 🙏🧡. Please, consider giving your feedback and suggestions in the comment section so that I can improve in many aspects. I would appreciate it if you put your query in the comment section and give me a chance to address and help you with it.</p><p><strong>Wish you become your best version for no reason. 🌈✌😃</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c49aa0424054" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Want to save a lot of time on Postman? Use Collections.]]></title>
            <link>https://medium.com/@patro.roshan1997/want-to-save-a-lot-of-time-on-postman-use-collections-4db4576e9b5e?source=rss-b230c0fdbe13------2</link>
            <guid isPermaLink="false">https://medium.com/p/4db4576e9b5e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[T Roshan Kumar Patro]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 19:52:35 GMT</pubDate>
            <atom:updated>2023-04-25T19:52:35.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*CD1l5DMt-kFb-n1yx-IjpQ.png" /></figure><p><strong>Why read this</strong>❔</p><p>Postman is most commonly used by developers and organizations to create, share, test, and document APIs. So, we developers spend a lot of time on Postman as a tool. In such cases, it is crucial to understand the tool better and get the best of it most efficiently. This not only enhances our productivity but also saves us time so that we can focus more on the logic building of our program and its optimization.</p><p><strong>Let’s go 🟢</strong></p><p><strong>What is Postman?</strong></p><p>Postman is a standalone software testing API (Application Programming Interface) platform to build, test, design, modify, and document APIs. It is a simple Graphic User Interface for sending and viewing HTTP requests and responses.</p><p><strong>We are <em>not</em> doing it right ❌</strong></p><p>Most developers who are new to the software/ web development domain use Postman in a very counter-productive manner. Instead of exploring tools simultaneously, they perform all relevant activities in a similar fashion they learn on day one.</p><p>But when the intensity of work and responsibilities increases, spending much time on such client tools becomes expensive rather than focusing on the business logic of the applications. But to get faster with such tools, we must be aware of the must-know features these tools contain.</p><p>If we address such an instance where a developer’s practice is inefficient, that can be how he/she plays with the APIs on Postman. Many developers don’t care about the clean and organized interactions with Postman. As per the requirements, momentarily they keep opening new tabs and writing URIs to send HTTP requests to the server. But this seems to be very time taking when the repetition of tasks comes into the picture.</p><p>If we have to send the same request multiple times, why select the type of request and enter the same URI manually again and again?</p><p>We can do that once and save the type and URI of the request for future reference so that from the second time onwards, we can make the same thing happen with just one click.</p><p>That is when the concept of Collections in Postman comes up with its significance.</p><p><strong>How to use Collections in Postman ❔</strong></p><blockquote><strong>Step 1: Click on the Collections tab present in the leftmost panel of the workspace</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OZWpdRPUiKKf12jhDBT4g.png" /></figure><blockquote><strong>Step 2: Click on the ➕ on the expanded area to create a new collection</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78Ia6EZCbG0v-bjYxJuVbg.png" /></figure><blockquote><strong>Step 3: Give a name to the collection (preferably the name of your application) and press enter</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5inpjMvMaaiGwmT5Fs3VPg.png" /></figure><blockquote><strong>Step 4: Expand the Meatballs menu (three dot menu) and click on the Add folder option</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6WVaFXMBRym_sAJBgsBaFg.png" /></figure><blockquote><strong>Step 5: Give a name to the folder (preferably a module/service name of your application) and press enter</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzlZD-4WsAuI7mOfoHtM2w.png" /></figure><blockquote><strong>Step 6: Expand the Meatballs Menu (three dot menu) and click on Add request option to add a request (URI)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnfD5sxsDfRFDMy736ARRA.png" /></figure><blockquote><strong>Step 7: Give the request name, select the request type, write the URI, and give the RequestBody (if applicable) and then click on the save button as mentioned in the snap below</strong></blockquote><p>Here, one request will be saved and added to the folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rChQv7yfqYh0Wts1LLAAIg.png" /></figure><p>With the above steps, we can create a maintainable folder structure for all the endpoints (URIs) of our applications. Then just by clicking on the request name we can open the whole request and send it to the server.</p><p>Below is a sample image of the folder structure of a Hotel Management System.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IAtFtyy4oH56eCVmDQv_Qw.png" /></figure><p>To explore more: <a href="https://www.postman.com/">https://www.postman.com/</a></p><p>Thank you so much for reading this so far by giving your valuable time. I am indeed thankful to each one of you 🙏🧡. Please, consider giving your feedback and suggestions in the comment section so that I can improve in many aspects. I would appreciate it if you put your query in the comment section and give me a chance to address and help you with it.</p><p><strong>Wish you become your best version for no reason. 🌈✌😃</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4db4576e9b5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing around with the double data type in Java]]></title>
            <link>https://medium.com/@patro.roshan1997/playing-around-with-the-double-data-type-in-java-b4ed9f8e8211?source=rss-b230c0fdbe13------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4ed9f8e8211</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[T Roshan Kumar Patro]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 11:05:13 GMT</pubDate>
            <atom:updated>2023-04-19T11:05:13.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*OopzQyIhCcrKILEnH1IuZQ.png" /></figure><p><strong>Why read this ❔</strong></p><p>In Java, the double data type plays a very significant role in code correctness and accuracy. This is what I feel and have experienced from my practices so far.</p><p>This is because we more often tend to commit mistakes with type casting and conversions while dealing with the double data type. On top of that debugging a code that includes double-type data members becomes more challenging when we don’t have access to the test cases.</p><p>Even little mistakes in proper type casting and conversions of data values of double type while performing operations on them lead to incorrect outputs despite the logic of the code being absolutely correct.</p><p><strong>Let’s go 🟢</strong></p><p><strong>What is a double data type in Java?</strong></p><p>The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is generally used for decimal values just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0d.</p><p><strong><em>Example</em></strong>: double d1 = 12.3;</p><p>Without flooding this space with more theories, we will go through a couple of implementations and scenarios around the double data type we all commonly come across while writing the logic in our codes.</p><blockquote><strong>Scenario 1: </strong>Dividing two integer type values and storing the result in a variable of double type</blockquote><pre>class PlayWithDouble {<br>    public static void main(String[] args) {<br>        int sum = 9;<br>        int length = 4;<br><br>        double avg1 = sum/length;<br>        System.out.println(avg1); // 2.0 --&gt; Incorrect output<br><br>        double avg2 = ((double)sum)/length;<br>        System.out.println(avg2); // 2.25 --&gt; Correct output<br>    }<br>}</pre><p>Here, in the avg1 calculation simply dividing the sum by length didn’t work. But, in the calculation of avg2, it gave the correct output because the sum was cast to double. Remember, <strong><em>(double)(sum/length)</em></strong> will also give 2.0 which is the wrong answer.</p><blockquote><strong>Scenario 2: </strong>Performing operations on a double data type and storing the result in a variable of double type</blockquote><pre>class PlayWithDouble {<br>    public static void main(String[] args) {<br>        double d = 12.374;<br><br>        double a1 = d*(3/100);<br>        System.out.println(a1); // 0.0  --&gt; Incorrect Output<br><br>        double a2 = (d*3)/100;<br>        System.out.println(a2); // 0.37122  --&gt; Correct Output<br>    }<br>}</pre><p>Here, placing brackets correctly was crucial.</p><blockquote><strong>Scenario 3: </strong>Multiplying two values of double type</blockquote><pre>class PlayWithDouble {<br>    public static void main(String[] args) {<br>        System.out.println(13.5*6.28); // 84.78  --&gt; Correct Output<br>    }<br>}</pre><blockquote><strong>Scenario 4: </strong>Multiplying an integer value with a double value and storing the result in a variable of double type</blockquote><pre>class PlayWithDouble {<br>    public static void main(String[] args) {<br>        double d = 12.374;<br>        int a = 4;<br>        <br>        double ans = a*d;<br>        System.out.println(ans); // 49.496 --&gt; Correct Output<br>    }<br>}</pre><p>If we multiply an integer value with a double value and store the result in a variable of double type, then no type casting is required.</p><blockquote><strong>Scenario 5: </strong>Multiplying an integer value with a double value and storing the result in a variable of int type</blockquote><pre>class PlayWithDouble {<br>    public static void main(String[] args) {<br>        double d = 12.374;<br>        int a = 4;<br><br>        int c = (int)(a*d);<br>        System.out.println(c); // 49 --&gt; The integer form of 49.496<br>    }<br>}</pre><p>Here, first, the multiplication (a*d) happened then the result got cast to the integer type.</p><blockquote><strong>Scenario 6: </strong>A little modified version of <strong>Scenario 5</strong></blockquote><pre>class PlayWithDouble {<br>    public static void main(String[] args) {<br>        double d = 12.374;<br>        int a = 4;<br><br>        int c = a*(int)d;<br>        System.out.println(c); // 48 --&gt; The integer form of 48<br>    }<br>}</pre><p>Here, first, d got cast to its integer form and then got multiplied with a. So, the result here came out to be 48.</p><p>These are some very common scenarios around the applications of the double data type every coder or developer very often come across while coding.</p><p>I am sure there are other different scenarios you might be facing while you code but these are some scenarios I could mention out of my experience. I will be more than happy if you consider mentioning some more helpful pointers out of your knowledge in the comment section.</p><p>To know more about primitive data types in Java, you may refer to:</p><p><a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html#:~:text=double%3A%20The%20double%20data%20type,is%20generally%20the%20default%20choice.">Oracle Java Documentation</a></p><p><a href="https://www.javatpoint.com/java-data-types">JavaTPoint Java Documentation</a></p><p>Thank you so much for reading this so far by giving your valuable time. I am indeed thankful to each one of you 🙏🧡. Please, consider giving your feedback and suggestions in the comment section so that I can improve in many aspects. I would appreciate it if you put your query in the comment section and give me a chance to address and help you with it.</p><p><strong>Wish you become your best version for no reason. 🌈✌😃</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4ed9f8e8211" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>