<?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 Jirapong Bualuang on Medium]]></title>
        <description><![CDATA[Stories by Jirapong Bualuang on Medium]]></description>
        <link>https://medium.com/@jirapong21?source=rss-aa90439f0744------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yUWaHFUXWpcGUL5SrMWFGA.jpeg</url>
            <title>Stories by Jirapong Bualuang on Medium</title>
            <link>https://medium.com/@jirapong21?source=rss-aa90439f0744------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:19:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jirapong21/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[Structured guide to learning Java Spring Boot from zero to hero topics]]></title>
            <link>https://medium.com/@jirapong21/structured-guide-to-learning-java-spring-boot-from-zero-to-hero-topics-6f7f9379ab88?source=rss-aa90439f0744------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f7f9379ab88</guid>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Jirapong Bualuang]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 00:54:30 GMT</pubDate>
            <atom:updated>2024-11-02T00:54:30.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSMsdMWRNu1tRgeUwVqgww.png" /><figcaption>Credit Image : <a href="https://spring.io/microservices">https://spring.io/microservices</a></figcaption></figure><h3>1. Basics of Spring Boot</h3><ul><li><strong>Introduction to Spring Boot</strong>: Learn what Spring Boot is and how it simplifies Spring application development.</li><li><strong>Setting Up Your Environment</strong>: Install Java, Maven/Gradle, and your preferred IDE (IntelliJ IDEA or Eclipse).</li><li><strong>Creating a Basic Project</strong>: Use Spring Initializr to set up a Spring Boot project. <a href="https://start.spring.io/">https://start.spring.io/</a></li><li><strong>Understanding Annotations</strong>: Learn about key annotations, such as @SpringBootApplication, @Controller, @RequestMapping, @RestController.</li><li><strong>Basic Application Structure</strong>: Familiarize yourself with the structure of a Spring Boot project (controller, service, repository, application properties, etc.).</li></ul><p><strong>Goal</strong>: Create a simple REST API (e.g., a “Hello World” application).</p><h3>2. REST API Development with Spring Boot</h3><ul><li><strong>REST Controller</strong>: Create endpoints using @RestController and @RequestMapping.</li><li><strong>HTTP Methods</strong>: Implement methods for GET, POST, PUT, DELETE.</li><li><strong>Path Variables and Request Parameters</strong>: Use @PathVariable and @RequestParam for dynamic routing.</li><li><strong>Response Entity</strong>: Use ResponseEntity to manage responses.</li><li><strong>Exception Handling</strong>: Implement global exception handling with @ControllerAdvice and @ExceptionHandler.</li></ul><p><strong>Goal</strong>: Build a CRUD API for managing a simple entity, such as a “Product” or “User.”</p><h3>3. Data Persistence with Spring Data JPA</h3><ul><li><strong>Database Configuration</strong>: Configure databases (H2, MySQL, PostgreSQL).</li><li><strong>Spring Data JPA</strong>: Learn to use JpaRepository and CrudRepository interfaces.</li><li><strong>Entity Relationships</strong>: Understand relationships like @OneToMany, @ManyToOne, @OneToOne, and @ManyToMany.</li><li><strong>JPA Query Methods</strong>: Create custom queries using method names and @Query.</li><li><strong>Database Migrations</strong>: Set up migrations with tools like Flyway or Liquibase.</li></ul><p><strong>Goal</strong>: Build an API with entities, repositories, and relationships, and integrate it with a database.</p><h3>4. Spring Boot Security</h3><ul><li><strong>Introduction to Spring Security</strong>: Set up Spring Security for basic authentication.</li><li><strong>JWT Authentication</strong>: Implement JWT (JSON Web Tokens) for stateless authentication.</li><li><strong>Role-Based Access Control</strong>: Implement roles and permissions using @PreAuthorize.</li><li><strong>OAuth2 and Social Login</strong>: Integrate with OAuth2 providers like Google, GitHub for login.</li></ul><p><strong>Goal</strong>: Secure your application with JWT authentication and role-based authorization.</p><h3>5. Advanced Spring Boot Concepts</h3><ul><li><strong>Custom Annotations</strong>: Create custom annotations to encapsulate cross-cutting concerns.</li><li><strong>Aspect-Oriented Programming (AOP)</strong>: Use AOP with @Aspect for logging, performance monitoring, and security.</li><li><strong>Caching</strong>: Implement caching with @Cacheable, @CacheEvict, and @CachePut.</li><li><strong>Scheduler Tasks</strong>: Use @Scheduled to automate tasks.</li><li><strong>File Uploads and Downloads</strong>: Implement file upload and download functionality.</li></ul><p><strong>Goal</strong>: Add custom logging and caching to your application, and create scheduled tasks.</p><h3>6. Testing in Spring Boot</h3><ul><li><strong>Unit Testing</strong>: Use JUnit and Mockito for unit tests.</li><li><strong>Integration Testing</strong>: Use @SpringBootTest for testing Spring Boot applications.</li><li><strong>MockMVC</strong>: Test your controllers and APIs with MockMVC.</li><li><strong>TestContainers</strong>: Use TestContainers for database integration tests.</li><li><strong>Mocking with Mockito</strong>: Mock service and repository layers to isolate tests.</li></ul><p><strong>Goal</strong>: Write unit and integration tests for all parts of your application.</p><h3>7. Microservices with Spring Boot</h3><ul><li><strong>Introduction to Microservices</strong>: Understand the basics of microservice architecture.</li><li><strong>Service Discovery with Eureka</strong>: Use Eureka Server for service registration and discovery.</li><li><strong>API Gateway</strong>: Use Spring Cloud Gateway or Netflix Zuul as an API Gateway.</li><li><strong>Circuit Breaker</strong>: Implement fault tolerance with Resilience4j or Hystrix.</li><li><strong>Distributed Tracing</strong>: Use Spring Cloud Sleuth and Zipkin for tracing requests.</li><li><strong>External Configuration</strong>: Use Spring Cloud Config for centralized configuration.</li></ul><p><strong>Goal</strong>: Build a simple microservice application with two or three services that communicate with each other.</p><h3>8. Containerization and Deployment</h3><ul><li><strong>Docker</strong>: Containerize your Spring Boot applications using Docker.</li><li><strong>Docker Compose</strong>: Manage multi-container applications with Docker Compose.</li><li><strong>Kubernetes</strong>: Deploy and manage Spring Boot applications on Kubernetes.</li><li><strong>CI/CD Pipelines</strong>: Automate builds and deployments using Jenkins, GitHub Actions, or GitLab CI/CD.</li></ul><p><strong>Goal</strong>: Create Docker images for your application and deploy them to a Kubernetes cluster.</p><h3>9. Monitoring and Performance Optimization</h3><ul><li><strong>Actuator</strong>: Use Spring Boot Actuator for health checks and application monitoring.</li><li><strong>Micrometer</strong>: Integrate with Micrometer to export metrics to monitoring tools (e.g., Prometheus).</li><li><strong>Logging</strong>: Configure logging with Logback or log aggregators like ELK Stack (Elasticsearch, Logstash, Kibana).</li><li><strong>Profiling and Optimization</strong>: Use JProfiler or VisualVM to analyze and improve performance.</li></ul><p><strong>Goal</strong>: Set up monitoring, logging, and performance profiling for your application.</p><h3>10. Reactive Programming in Spring Boot</h3><ul><li><strong>Introduction to Reactive Programming</strong>: Learn the basics of reactive programming with Project Reactor.</li><li><strong>Spring WebFlux</strong>: Use Spring WebFlux for building reactive, non-blocking applications.</li><li><strong>Reactive Repositories</strong>: Implement reactive repositories with Spring Data R2DBC or MongoDB.</li><li><strong>Reactive Streams</strong>: Work with reactive streams using Mono and Flux.</li></ul><p><strong>Goal</strong>: Build a non-blocking, reactive API using Spring WebFlux.</p><h3>Additional Resources</h3><ul><li><strong>Documentation</strong>: Read the official <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/">Spring Boot documentation</a>.</li><li><strong>Books</strong>: “Spring Boot in Action” by Craig Walls, and “Spring in Action” for more comprehensive coverage.</li><li><strong>Courses</strong>: Look for Spring Boot courses on platforms like Udemy, Pluralsight, or Coursera.</li></ul><p>Following this structured approach, from basic REST API creation to deploying microservices with monitoring, will give you a solid understanding of Spring Boot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f7f9379ab88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Generate Excel with React fetch blob.]]></title>
            <link>https://medium.com/@jirapong21/spring-boot-generate-excel-with-react-fetch-blob-814938510b23?source=rss-aa90439f0744------2</link>
            <guid isPermaLink="false">https://medium.com/p/814938510b23</guid>
            <category><![CDATA[blob]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[fetch]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jirapong Bualuang]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 14:59:22 GMT</pubDate>
            <atom:updated>2023-09-11T14:59:22.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*wVsZxcuKQnRRhAs4mX82sw.png" /></figure><p>To create a Spring Boot backend that allows you to fetch an Excel file and then fetch that file from a React frontend, you can follow these steps:</p><p><strong><em>Spring Boot Backend:</em></strong></p><ol><li><strong>Create a Spring Boot Project:</strong></li></ol><p>You can use Spring Initializer or your preferred method to create a new Spring Boot project with the necessary dependencies. You’ll need dependencies like Spring Web, Spring Data JPA (if you want to interact with a database), and any other dependencies specific to your application.</p><p>2. <strong>Create a Controller to Generate Excel:</strong></p><p>Create a controller that generates the Excel file. You can use a library like Apache POI to create the Excel file. Here’s a basic example:</p><pre>import org.apache.poi.ss.usermodel.*;<br>import org.apache.poi.xssf.usermodel.XSSFWorkbook;<br>import org.springframework.http.HttpHeaders;<br>import org.springframework.http.MediaType;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import java.io.ByteArrayOutputStream;<br>import java.io.IOException;<br><br>@RestController<br>public class ExcelController {<br><br>    @GetMapping(&quot;/download-excel&quot;)<br>    public ResponseEntity&lt;byte[]&gt; downloadExcel() throws IOException {<br>        // Create a new Excel workbook and sheet<br>        Workbook workbook = new XSSFWorkbook();<br>        Sheet sheet = workbook.createSheet(&quot;SampleSheet&quot;);<br><br>        // Create sample data (you can replace this with your own data)<br>        Row row = sheet.createRow(0);<br>        row.createCell(0).setCellValue(&quot;Name&quot;);<br>        row.createCell(1).setCellValue(&quot;Age&quot;);<br>        row = sheet.createRow(1);<br>        row.createCell(0).setCellValue(&quot;Meduim&quot;);<br>        row.createCell(1).setCellValue(30);<br><br>        // Write the workbook to a ByteArrayOutputStream<br>        ByteArrayOutputStream stream = new ByteArrayOutputStream();<br>        workbook.write(stream);<br><br>        // Set response headers<br>        HttpHeaders headers = new HttpHeaders();<br>        headers.setContentType(MediaType.parseMediaType(&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&quot;));<br>        headers.setContentDispositionFormData(&quot;attachment&quot;, &quot;sample.xlsx&quot;);<br><br>        return ResponseEntity.ok()<br>                .headers(headers)<br>                .body(stream.toByteArray());<br>    }<br>}</pre><p>3. <strong>Configure CORS (if needed):</strong></p><p>If your frontend is hosted on a different domain, configure CORS (Cross-Origin Resource Sharing) in your Spring Boot application to allow cross-origin requests.</p><p>4. <strong>Run Your Spring Boot Application:</strong></p><p>Start your Spring Boot application. You should be able to access the Excel file at <a href="http://localhost:8080/download-excel">http://localhost:8080/download-excel</a></p><p><strong><em>React Frontend:</em></strong></p><ol><li><strong>Create a React Project:</strong></li></ol><p>Create a new React project using Create React App or your preferred method.</p><p>2. <strong>Fetch the Excel File:</strong></p><p>In your React component, you can use the fetch API to fetch the Excel file from your Spring Boot backend and convert it to a blob.</p><pre>import React, { useEffect } from &#39;react&#39;;<br><br>function App() {<br>    const downloadExcel = () =&gt; {<br>        // Fetch the Excel file with .xls extension<br>        fetch(&#39;http://localhost:8080/download-excel-xls&#39;, {<br>            method: &#39;GET&#39;,<br>            responseType: &#39;blob&#39;, // This is not a standard option; you might need to handle it differently<br>        })<br>            .then((response) =&gt; response.blob())<br>            .then((blob) =&gt; {<br>                // Create a blob URL and create a link element to trigger the download<br>                const blobUrl = window.URL.createObjectURL(blob);<br>                const a = document.createElement(&#39;a&#39;);<br>                a.style.display = &#39;none&#39;;<br>                a.href = blobUrl;<br>                a.download = &#39;sample.xls&#39;; // Set the desired file name with .xls extension<br>                document.body.appendChild(a);<br>                a.click();<br>                window.URL.revokeObjectURL(blobUrl);<br>            })<br>            .catch((error) =&gt; {<br>                console.error(&#39;Error fetching Excel file:&#39;, error);<br>            });<br>    };<br><br>    useEffect(() =&gt; {<br>        downloadExcel();<br>    }, []);<br><br>    return (<br>        &lt;div className=&quot;App&quot;&gt;<br>            &lt;h1&gt;Fetch Excel File Example&lt;/h1&gt;<br>        &lt;/div&gt;<br>    );<br>}<br><br>export default App;</pre><p>3. We fetch the Excel file from the server using the URL http://localhost:8080/download-excel-xls. Ensure that your Spring Boot backend has a new endpoint (/download-excel-xls) that generates and returns an Excel file with the .xls extension.</p><p>4. After fetching the blob, we create a blob URL using window.URL.createObjectURL(blob).</p><p>5. We create a hidden &lt;a&gt; element and set its href to the blob URL, specify the download attribute with the desired file name including the .xls extension, and trigger a click event to initiate the download.</p><p>6. Finally, we revoke the blob URL to release resources.</p><p>Remember to update your Spring Boot backend to generate and serve the Excel file with the .xls extension when requested from the /download-excel-xls endpoint. You&#39;ll need to use a library like Apache POI with the .xls format for this purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=814938510b23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Two Sum for Java]]></title>
            <link>https://medium.com/@jirapong21/leetcode-two-sum-for-java-a88cf670a354?source=rss-aa90439f0744------2</link>
            <guid isPermaLink="false">https://medium.com/p/a88cf670a354</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Jirapong Bualuang]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 11:26:18 GMT</pubDate>
            <atom:updated>2023-08-05T11:26:18.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-todlqFTZ-J3bpaZuomjg.png" /><figcaption><a href="https://leetcode.com/problems/two-sum/">https://leetcode.com/problems/two-sum/</a></figcaption></figure><p>This code is a solution to the Two Sum problem, which is a classic algorithmic problem. The problem statement is as follows: Given an array of integers nums and an integer target, find two distinct indices i and j in the array such that nums[i] + nums[j] equals target. The function twoSum takes the array nums and the target as input and returns an array of two indices that satisfy the condition.</p><p>Now let’s go through the code and explain each part:</p><pre>class Solution {<br>    public int[] twoSum(int[] nums, int target) {<br>        // Create a HashMap to store each number and its index in the array<br>        Map&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();<br>        <br>        // Loop through the array to find the two elements that add up to the target<br>        for (int i = 0; i &lt; nums.length; i++) {<br>            // Calculate the complement needed to reach the target<br>            int complement = target - nums[i];<br>            <br>            // If the complement is present in the map, return the indices of the two elements<br>            if (map.containsKey(complement)) {<br>                return new int[] { map.get(complement), i };<br>            }<br>            <br>            // If the complement is not present, add the current number and its index to the map<br>            map.put(nums[i], i);<br>        }<br>        <br>        // If no solution is found, throw an exception with an error message<br>        throw new IllegalArgumentException(&quot;No two sum solution&quot;);<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ol><li>The code defines a class named Solution, which contains a single public method twoSum. The method takes two parameters: an integer array nums and an integer target.</li><li>Inside the twoSum method, a HashMap named map is created to store each number from the nums array along with its index. The HashMap will allow efficient lookup of the complement for each number.</li><li>The code then loops through the nums array using a for loop with the index i.</li><li>For each element at index i, it calculates the complement, which is the difference between the target and the current element (target - nums[i]).</li><li>It then checks if the complement exists in the map. If it does, that means we have found two elements whose sum is equal to the target. In this case, it returns a new array containing the indices of the two elements as {map.get(complement), i}.</li><li>If the complement is not present in the map, it means the current element cannot form a pair with any previous elements to achieve the target sum. So, it adds the current element nums[i] along with its index i to the map for future reference.</li><li>If the loop completes without finding a solution (i.e., no two elements that sum up to the target), it throws an IllegalArgumentException with the error message &quot;No two sum solution.&quot;</li></ol><p><strong>Comment:</strong></p><p>This solution is efficient with a time complexity of O(n) because it only requires a single pass through the array. By using a HashMap, the code efficiently stores and looks up elements in constant time, allowing for fast checks for the complement. Overall, the algorithm is optimal and works well for large arrays.</p><p><strong>Remember</strong> that the solution assumes there will always be a valid answer (i.e., there are exactly two distinct indices that sum up to the target). If the input array is not guaranteed to have a valid answer, the code can be modified to handle such cases accordingly.</p><p><a href="https://medium.com/@jirapong21/spring-boot-interview-questions-advanced-4fbe8a8c4ca1">Spring Boot Interview Questions Advanced.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a88cf670a354" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Interview Questions Advanced.]]></title>
            <link>https://medium.com/@jirapong21/spring-boot-interview-questions-advanced-4fbe8a8c4ca1?source=rss-aa90439f0744------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fbe8a8c4ca1</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[advanced]]></category>
            <dc:creator><![CDATA[Jirapong Bualuang]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 04:27:17 GMT</pubDate>
            <atom:updated>2023-04-15T04:27:17.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0YKb_VC9FoBLjs6rj5Ymw.png" /><figcaption>Spring framework and Spring boot for Java. #credit image edureka.</figcaption></figure><h3>13. What Are the Basic Annotations that Spring Boot Offers?</h3><p>Spring Boot offers several annotations that simplify the development of Spring-based applications. Here are some of the basic annotations that Spring Boot provides:</p><p><strong>@SpringBootApplication</strong>: This annotation is used to mark the main class of a Spring Boot application. It enables component scanning, auto-configuration, and starts the embedded web server.</p><p><strong>@Controller</strong>: This annotation is used to mark a class as a Spring MVC controller. It handles HTTP requests and returns HTTP responses.</p><p><strong>@RestController</strong>: This annotation is a combination of @Controller and <strong>@ResponseBody</strong>. It is used to mark a class as a RESTful controller. It handles HTTP requests and returns JSON/XML responses.</p><p><strong>@Service</strong>: This annotation is used to mark a class as a service. It encapsulates the business logic of an application.</p><p><strong>@Repository</strong>: This annotation is used to mark a class as a repository. It is used to interact with a database.</p><p><strong>@Component</strong>: This annotation is the base annotation for all Spring-managed components. It is used to mark a class as a bean.</p><p><strong>@Autowired</strong>: This annotation is used to inject dependencies into a Spring-managed bean.</p><p><strong>@Qualifier</strong>: This annotation is used to specify which bean to inject when multiple beans of the same type are available.</p><p><strong>@Value</strong>: This annotation is used to inject values from the properties file into a Spring-managed bean.</p><p><strong>@Configuration</strong>: This annotation is used to mark a class as a configuration class. It provides configuration to the Spring application context.</p><p><strong>@Profile</strong>: This annotation is used to activate/deactivate a bean based on the specified profile.</p><p><strong>@RequestMapping</strong>: This annotation is used to map an HTTP request to a method in a controller.</p><p><strong>@PathVariable</strong>: This annotation is used to extract a variable from the URL path.</p><p>These are some of the basic annotations that Spring Boot provides. There are many more annotations available that you can explore in the Spring documentation.</p><h3>14. What is Spring Boot dependency management?</h3><p>Spring Boot dependency management is used to manage dependencies and configuration automatically without you specifying the version for any of that dependencies.</p><h3>15. Can we create a non-web application in Spring Boot?</h3><p>Yes, it is possible to create a non-web application in Spring Boot. Although Spring Boot is often used to develop web applications, it can be used for non-web applications as well.</p><p>Spring Boot provides several features that are not related to web development. For example, Spring Boot provides support for data access, caching, messaging, scheduling, and batch processing. These features can be used to develop non-web applications such as command-line applications, standalone applications, background tasks, and batch jobs.</p><p>To create a non-web application in Spring Boot, you can exclude the web-related dependencies from your project. You can do this by adding the spring-boot-starter dependency to your pom.xml file and excluding the web-related dependencies using the exclude tag.</p><p>For example, to create a command-line application, you can add the spring-boot-starter dependency to your pom.xml file and exclude the web-related dependencies as follows:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter&lt;/artifactId&gt;<br>    &lt;exclusions&gt;<br>        &lt;exclusion&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>        &lt;/exclusion&gt;<br>    &lt;/exclusions&gt;<br>&lt;/dependency&gt;</pre><p>Once you have excluded the web-related dependencies, you can use the Spring Boot features to develop your non-web application. For example, you can use Spring Data to access a database, use Spring Batch to process large volumes of data, or use Spring Integration to integrate with other systems.</p><p>In summary, Spring Boot can be used to develop non-web applications as well, and it provides several features that are not related to web development.</p><h3>16. Is it possible to change the port of the embedded Tomcat server in Spring Boot?</h3><p>Yes, it is possible to change the port of the embedded Tomcat server in Spring Boot. By default, Spring Boot applications run on port 8080. However, you can change the port by modifying the application.properties or application.yml file.</p><p>To change the port of the embedded Tomcat server in Spring Boot, you can add the following line to your application.properties file:</p><pre>server.port=8081</pre><p>In the above example, the server will start on port 8081 instead of the default port 8080.</p><p>Alternatively, you can also specify the port in the application.yml file as follows:</p><pre>server:<br>  port: 8081</pre><p>In addition to the server.port property, you can also specify other properties related to the Tomcat server in the application.properties or application.yml file. For example, you can set the maximum number of threads, the maximum size of the request, or the timeout for idle connections.</p><p>In summary, it is possible to change the port of the embedded Tomcat server in Spring Boot by modifying the application.properties or application.yml file. This provides flexibility and allows you to run your Spring Boot application on a different port than the default port 8080.</p><h3>17. What is the default port of tomcat in spring boot?</h3><p>The default port of the tomcat server-id 8080. It can be changed by adding <strong>sever.port</strong> properties in the <strong>application.property</strong> file.</p><h3>18. Can we override or replace the Embedded tomcat server in Spring Boot?</h3><p>Yes, we can replace the Embedded Tomcat server with any server by using the Starter dependency in the <strong>pom.xml</strong> file. Like you can use spring-boot-starter-jetty as a dependency for using a jetty server in your project.</p><h3>19. Can we disable the default web server in the Spring boot application?</h3><p>Yes, we can use <strong>application.properties</strong> to configure the web application type i.e <strong>spring.main.web-application-type=none.</strong></p><h3>20. How to disable a specific auto-configuration class?</h3><p>You can use exclude attribute of @EnableAutoConfiguration if you want auto-configuration not to apply to any specific class.</p><pre>//use of exclude<br>@EnableAutoConfiguration(exclude={className})</pre><h3>21. Explain @RestController annotation in Sprint boot?</h3><p>It is a combination of @Controller and @ResponseBody, used for creating a restful controller. It converts the response to JSON or XML. It ensures that data returned by each method will be written straight into the response body instead of returning a template</p><h3>22. What is the difference between @RestController and @Controller in Spring Boot?</h3><p>@Controller Map of the model object to view or template and make it human readable but @RestController simply returns the object and object data is directly written in HTTP response as JSON or XML.</p><h3>23. Describe the flow of HTTPS requests through the Spring Boot application?</h3><p>When an HTTPS request is made to a Spring Boot application, the request flows through a series of components and processes. The flow of HTTPS requests through a Spring Boot application can be described as follows:</p><ul><li>The client sends an HTTPS request to the Spring Boot application.</li><li>The request is received by the embedded Tomcat server in the Spring Boot application.</li><li>The SSL/TLS handshake process is initiated by the Tomcat server. The server presents its digital certificate to the client to authenticate itself.</li><li>If the client trusts the server’s certificate, it sends a message indicating that the handshake was successful. If the client does not trust the server’s certificate, it will reject the connection.</li><li>Once the SSL/TLS handshake is complete, the request is passed to the Spring MVC DispatcherServlet.</li><li>The DispatcherServlet analyzes the request and maps it to the appropriate controller and handler method.</li><li>The controller processes the request and returns a ModelAndView object to the DispatcherServlet.</li><li>The DispatcherServlet then resolves the view, generates the response, and sends it back to the client over the encrypted HTTPS connection.</li><li>If the client needs to make another request, the process repeats from step 1.</li></ul><p>In summary, the flow of HTTPS requests through a Spring Boot application involves the SSL/TLS handshake process, the Spring MVC DispatcherServlet, and the controller and view components. This flow ensures that requests and responses are transmitted securely over an encrypted connection, protecting sensitive data from eavesdropping and tampering.</p><h3>24. What is the difference between RequestMapping and GetMapping?</h3><p>RequestMapping can be used with GET, POST, PUT, and many other request methods using the method attribute on the annotation. Whereas getMapping is only an extension of RequestMapping which helps you to improve on clarity on request.</p><h3>25. What is the use of Profiles in spring boot?</h3><p>While developing the application we deal with multiple environments such as dev, QA, Prod, and each environment requires a different configuration. For eg., we might be using an embedded H2 database for dev but for prod, we might have proprietary Oracle or DB2. Even if DBMS is the same across the environment, the URLs will be different.</p><p>To make this easy and clean, Spring has the provision of Profiles to keep the separate configuration of environments.</p><h3>26. What is Spring Actuator? What are its advantages?</h3><p>An actuator is an additional feature of Spring that helps you to monitor and manage your application when you push it to production. These actuators include auditing, health, CPU usage, HTTP hits, and metric gathering, and many more that are automatically applied to your application.</p><h3>27. How to enable Actuator in Spring boot application?</h3><p>Actuator is a set of Spring Boot modules that provides production-ready features to help you monitor and manage your application. To enable Actuator in a Spring Boot application, you can follow these steps:</p><ol><li>Add the Actuator dependency to your pom.xml file or build.gradle file. For example, if you are using Maven, add the following dependency:</li></ol><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>2. Once the dependency is added, Actuator endpoints will be enabled by default. You can access them by visiting the URL http://localhost:8080/actuator in your browser.</p><p>Note that the actual port number may be different depending on the configuration of your application.</p><p>3. You can also customize the Actuator endpoints by modifying the application.properties or application.yml file. For example, to enable the /health endpoint, you can add the following line to your application.properties file:</p><pre>management.endpoints.web.exposure.include=health</pre><p>This will expose the /health endpoint, which will provide information about the health of your application.</p><p>4. You can also add custom Actuator endpoints by creating a new class that implements the Endpoint interface. For example, to create a custom endpoint that provides information about the number of active sessions in your application, you can create a class like this:</p><pre>@Endpoint(id = &quot;session-count&quot;)<br>public class SessionCountEndpoint {<br><br>    private final HttpSession httpSession;<br><br>    public SessionCountEndpoint(HttpSession httpSession) {<br>        this.httpSession = httpSession;<br>    }<br><br>    @ReadOperation<br>    public int getSessionCount() {<br>        return httpSession.getActiveSessions().size();<br>    }<br>}</pre><p>This class creates a new endpoint with the ID session-count and provides information about the number of active sessions in the application. You can then access this endpoint by visiting the URL http://localhost:8080/actuator/session-count in your browser.</p><p>In summary, to enable Actuator in a Spring Boot application, you need to add the Actuator dependency to your project, and then you can access the Actuator endpoints at http://localhost:8080/actuator. You can customize the Actuator endpoints by modifying the application.properties or application.yml file, and you can also add custom endpoints by creating a new class that implements the Endpoint interface.</p><h3>29. How to check the environment properties in your Spring boot application?</h3><p>Spring Boot actuator “/env” returns the list of all the environment properties of running the spring boot application.</p><h3>30. What is dependency Injection?</h3><p>Dependency Injection (DI) is a design pattern used in software engineering and a fundamental concept in Spring Framework and Spring Boot. DI is a process of providing dependencies (objects) to a class, rather than the class creating its own dependencies. In other words, DI is a way of removing the hard-coded dependencies from the code and providing them externally.</p><p>The core idea behind DI is to decouple the classes in an application by removing hard-coded dependencies between them. Instead, dependencies are passed to a class via constructors, methods, or fields. This makes the code more modular, easier to test, and easier to maintain.</p><p>DI is typically implemented using an Inversion of Control (IoC) container, such as the Spring Framework. The container manages the lifecycle of objects and their dependencies, and automatically injects the necessary dependencies into objects at runtime. The dependencies are configured using a set of rules or configurations, which are typically stored in XML, Java annotations, or Java code.</p><p>In Spring Boot, DI is a key concept that is used throughout the framework. For example, when you use @Autowired annotation in your code, Spring Boot automatically injects the necessary dependencies into your objects, making it easier to write modular, testable, and maintainable code.</p><p>In summary, Dependency Injection is a design pattern used in software engineering to remove hard-coded dependencies between classes and to provide dependencies externally. It is a fundamental concept in Spring Framework and Spring Boot, and is typically implemented using an Inversion of Control container.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fbe8a8c4ca1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Interview Questions Basic.]]></title>
            <link>https://medium.com/@jirapong21/spring-boot-interview-questions-basic-fc40cb804593?source=rss-aa90439f0744------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc40cb804593</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Jirapong Bualuang]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 03:48:29 GMT</pubDate>
            <atom:updated>2023-04-22T16:40:34.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*o5FmjKTPdJTbhGE2MIjo6w.jpeg" /></figure><p><strong>Spring Boot</strong> is an open-source Java-based framework that simplifies the process of creating standalone, production-grade Spring-based applications that can be deployed easily. It provides a comprehensive set of features and tools for quickly building enterprise-level web applications with minimal setup and configuration.</p><p><strong>Features of Spring Boot that make it different?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6boRa18Xao5ptU10uiKdg.png" /></figure><h3>1. What are the advantages of using Spring Boot?</h3><ul><li>Faster development: Spring Boot provides an opinionated approach to application development, which means that it offers default settings and configurations for many aspects of the application, reducing the amount of time spent on boilerplate code and configurations.</li><li>Easy configuration: Spring Boot offers a flexible configuration model that allows developers to easily configure various aspects of the application, including databases, security, logging, and more.</li><li>Reduced complexity: With Spring Boot, developers can focus on writing business logic instead of worrying about low-level infrastructure details, such as managing dependencies and configuring web servers.</li><li>Enhanced productivity: Spring Boot offers several tools and features that can help developers be more productive, including auto-configuration, code generation, and a robust set of libraries and APIs.</li><li>Increased scalability: Spring Boot’s modular design and dependency injection approach make it easy to scale applications as needed, without requiring extensive changes to the codebase.</li><li>Comprehensive testing: Spring Boot provides a suite of testing tools and features that make it easy to write and execute unit and integration tests for your application.</li></ul><h3>2. What are the Spring Boot key components?</h3><ul><li>Spring Boot auto-configuration.</li><li>Spring Boot CLI.</li><li>Spring Boot starter POMs.</li><li>Spring Boot Actuators.</li></ul><h3>3. Why Spring Boot over Spring?</h3><ul><li>Starter POM.</li><li>Version Management.</li><li>Auto Configuration.</li><li>Component Scanning.</li><li>Embedded server.</li><li>InMemory DB.</li><li>Actuators</li></ul><p>Spring Boot simplifies the spring feature for the user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VN89oa0Jz_FiB0vZBtztxw.png" /></figure><h3>4. What is the starter dependency of the Spring boot module?</h3><p>Spring boot provides numbers of starter dependency, here are the most commonly used -</p><ul><li>Data JPA starter.</li><li>Test Starter.</li><li>Security starter.</li><li>Web starter.</li><li>Mail starter.</li><li>Thymeleaf starter.</li></ul><h3>5. How does Spring Boot works?</h3><p>Spring Boot automatically configures your application based on the dependencies you have added to the project by using annotation. The entry point of the spring boot application is the class that contains @SpringBootApplication annotation and the main method.</p><p>Spring Boot automatically scans all the components included in the project by using @ComponentScan annotation.</p><h3>6. What does the @SpringBootApplication annotation do internally?</h3><p>The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes. Spring Boot enables the developer to use a single annotation instead of using multiple. But, as we know, Spring provided loosely coupled features that we can use for each annotation as per our project needs.</p><h3>7. What is the purpose of using @ComponentScan in the class files?</h3><p>Spring Boot application scans all the beans and package declarations when the application initializes. You need to add the @ComponentScan annotation for your class file to scan your components added to your project.</p><h3>8. How does a spring boot application get started?</h3><p>Just like any other Java program, a Spring Boot application must have a main method. This method serves as an entry point, which invokes the SpringApplication#run method to bootstrap the application.</p><pre>@SpringBootApplication <br>public class MyApplication { <br>   <br>       public static void main(String[] args) {    <br>    <br>             SpringApplication.run(MyApplication.class);        <br>               // other statements     <br>       } <br>}</pre><h3>9. What are starter dependencies?</h3><p>Spring boot starter is a maven template that contains a collection of all the relevant transitive dependencies that are needed to start a particular functionality.<br>Like we need to import spring-boot-starter-web dependency for creating a web application.</p><pre>&lt;dependency&gt;<br>&lt;groupId&gt; org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt; spring-boot-starter-web &lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h3>10. What is Spring Initializer?</h3><p>Spring Initializer is a web application that helps you to create an initial spring boot project structure and provides a maven or gradle file to build your code. It solves the problem of setting up a framework when you are starting a project from scratch.</p><p><a href="https://start.spring.io/">Spring Initializr</a></p><h3>11. What is Spring Boot CLI and what are its benefits?</h3><p>Spring Boot CLI is a command-line interface that allows you to create a spring-based java application using Groovy.</p><p>Example: You don’t need to create getter and setter method or access modifier, return statement. If you use the JDBC template, it automatically loads for you.</p><h3>12. What are the most common Spring Boot CLI commands?</h3><p>Spring Boot CLI (Command Line Interface) provides several commands to create, run, test, and package Spring Boot applications. Here are some of the most commonly used Spring Boot CLI commands:</p><p>spring init: This command is used to initialize a new Spring Boot project. It creates a new Spring Boot application with the specified dependencies and generates the required project structure.</p><p>spring run: This command is used to run a Spring Boot application. It starts the embedded Tomcat server and deploys the application.</p><p>spring test: This command is used to run the unit tests in a Spring Boot application.</p><p>spring jar: This command is used to package a Spring Boot application into a standalone executable JAR file.</p><p>spring install: This command is used to install a Spring Boot application as a command-line tool.</p><p>spring help: This command displays the list of available Spring Boot CLI commands and their usage.</p><p>spring shell: This command is used to launch the Spring Shell. The Spring Shell is an interactive shell that provides a command-line interface for interacting with a Spring Boot application.</p><p>spring stop: This command is used to stop a running Spring Boot application.</p><p>spring restart: This command is used to restart a running Spring Boot application.</p><p>These are some of the most common Spring Boot CLI commands. There are many more commands available that you can explore by using the spring help command.</p><h3>Spring Boot Interview Questions Advanced.</h3><p><a href="https://medium.com/@jirapong21/spring-boot-interview-questions-advanced-4fbe8a8c4ca1">Spring Boot Interview Questions Advanced.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc40cb804593" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Algorithms Chapter 1]]></title>
            <link>https://medium.com/@jirapong21/java-algorithms-chapter-1-1be5c23d11c8?source=rss-aa90439f0744------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be5c23d11c8</guid>
            <category><![CDATA[java-algorithm]]></category>
            <category><![CDATA[sorting]]></category>
            <dc:creator><![CDATA[Jirapong Bualuang]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 17:31:08 GMT</pubDate>
            <atom:updated>2023-04-14T17:31:08.243Z</atom:updated>
            <content:encoded><![CDATA[<p>Java is a popular programming language that is widely used for developing various types of software applications. It has a vast collection of built-in data structures and algorithms that can be used to solve complex problems efficiently. In this answer, I’ll provide an overview of some of the common algorithms in Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*HflKk5hcuMfOy3o-KRcPoQ.png" /></figure><p><strong>Sorting Algorithms</strong>: Sorting algorithms are used to arrange elements in a particular order. Java has several built-in sorting algorithms that can be used to sort arrays and collections. Some of the popular sorting algorithms in Java are:</p><ol><li><strong>Bubble sort</strong> is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. It has a worst-case and average complexity of O(n²), where n is the number of items being sorted.</li></ol><pre>public static void bubbleSort(int[] arr) {<br>    int n = arr.length;<br>    // Step through the array n-1 times<br>    for (int i = 0; i &lt; n-1; i++) {<br>        // Last i elements are already sorted<br>        for (int j = 0; j &lt; n-i-1; j++) {<br>            // Compare adjacent elements and swap if they are in the wrong order<br>            if (arr[j] &gt; arr[j+1]) {<br>                int temp = arr[j];<br>                arr[j] = arr[j+1];<br>                arr[j+1] = temp;<br>            }<br>        }<br>    }<br>}</pre><p>In this implementation, arr is the array to be sorted. The outer loop iterates over the array n-1 times, where n is the length of the array. The inner loop iterates over the unsorted portion of the array and compares adjacent elements, swapping them if they are in the wrong order. The if statement checks if arr[j] is greater than arr[j+1], and if so, the elements are swapped using a temporary variable temp. After each iteration of the inner loop, the largest element is guaranteed to be at the end of the unsorted portion of the array, so the next iteration of the outer loop can start one element earlier.</p><p><strong>2. Selection sort</strong> is an in-place comparison sorting algorithm that divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. It has a worst-case and average complexity of O(n²).</p><pre>public static void selectionSort(int[] arr) {<br>    int n = arr.length;<br>    // Step through the array<br>    for (int i = 0; i &lt; n-1; i++) {<br>        int minIndex = i;<br>        // Find the index of the smallest element in the unsorted portion of the array<br>        for (int j = i+1; j &lt; n; j++) {<br>            if (arr[j] &lt; arr[minIndex]) {<br>                minIndex = j;<br>            }<br>        }<br>        // Swap the smallest element with the first element in the unsorted portion of the array<br>        int temp = arr[minIndex];<br>        arr[minIndex] = arr[i];<br>        arr[i] = temp;<br>    }<br>}</pre><p>In this implementation, arr is the array to be sorted. The outer loop iterates over the array n-1 times, where n is the length of the array. The inner loop finds the index of the smallest element in the unsorted portion of the array. The if statement checks if arr[j] is less than arr[minIndex], and if so, minIndex is updated to j. After the inner loop completes, the smallest element in the unsorted portion of the array is found, and it is swapped with the first element in the unsorted portion of the array using a temporary variable temp. After each iteration of the outer loop, the sorted portion of the array grows by one element, and the unsorted portion of the array shrinks by one element.</p><p><strong>3. Insertion sort</strong> is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. It has a worst-case and average complexity of O(n²).</p><pre>public static void insertionSort(int[] arr) {<br>    int n = arr.length;<br>    // Step through the array<br>    for (int i = 1; i &lt; n; i++) {<br>        int key = arr[i];<br>        int j = i - 1;<br>        // Move elements that are greater than the key to one position ahead of their current position<br>        while (j &gt;= 0 &amp;&amp; arr[j] &gt; key) {<br>            arr[j+1] = arr[j];<br>            j--;<br>        }<br>        arr[j+1] = key;<br>    }<br>}</pre><p>In this implementation, arr is the array to be sorted. The outer loop iterates over the array starting from the second element (i=1). The key variable is used to store the current element that needs to be inserted into the correct position in the sorted portion of the array. The inner loop moves elements that are greater than the key to one position ahead of their current position until a smaller element is encountered or the beginning of the array is reached. The while loop continues to execute as long as j is greater than or equal to 0 (to avoid an out-of-bounds exception) and arr[j] is greater than key. After the inner loop completes, key is inserted into the correct position in the sorted portion of the array using arr[j+1] = key. After each iteration of the outer loop, the sorted portion of the array grows by one element.</p><p><strong>4. Merge sort</strong> is a divide-and-conquer algorithm that divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves. It has a worst-case and average complexity of O(n log n). Java code insert comment.</p><pre>public static void mergeSort(int[] arr) {<br>    int n = arr.length;<br>    // Base case: If the array has fewer than two elements, it is already sorted<br>    if (n &lt; 2) {<br>        return;<br>    }<br>    // Divide the array into two halves<br>    int mid = n / 2;<br>    int[] left = new int[mid];<br>    int[] right = new int[n - mid];<br>    System.arraycopy(arr, 0, left, 0, mid);<br>    System.arraycopy(arr, mid, right, 0, n - mid);<br>    // Recursively sort each half<br>    mergeSort(left);<br>    mergeSort(right);<br>    // Merge the sorted halves<br>    merge(left, right, arr);<br>}<br><br>private static void merge(int[] left, int[] right, int[] arr) {<br>    int i = 0, j = 0, k = 0;<br>    // Compare the first elements of the left and right halves and copy the smaller element to the output array<br>    while (i &lt; left.length &amp;&amp; j &lt; right.length) {<br>        if (left[i] &lt;= right[j]) {<br>            arr[k++] = left[i++];<br>        } else {<br>            arr[k++] = right[j++];<br>        }<br>    }<br>    // Copy any remaining elements from the left or right halves to the output array<br>    while (i &lt; left.length) {<br>        arr[k++] = left[i++];<br>    }<br>    while (j &lt; right.length) {<br>        arr[k++] = right[j++];<br>    }<br>}</pre><p>In this implementation, arr is the array to be sorted. The mergeSort method recursively divides the input array into two halves, and then calls itself for each half. The base case occurs when the array has fewer than two elements, in which case the method returns without doing anything. The two halves of the array are created using System.arraycopy, and the merge method is called to merge the sorted halves. The merge method compares the first elements of the left and right halves and copies the smaller element to the output array. The while loops continue to execute as long as there are elements remaining in the left or right halves. After both while loops complete, the output array arr contains the sorted elements of the input array.</p><p><strong>5. Quick sort</strong> is a divide-and-conquer algorithm that picks an element as a pivot and partitions the array around the pivot, placing smaller elements to the left of the pivot and larger elements to the right of the pivot. It then recursively sorts the left and right subarrays. It has a worst-case complexity of O(n²) but an average complexity of O(n log n). Java code insert comment.</p><pre>public static void quickSort(int[] arr) {<br>    quickSort(arr, 0, arr.length - 1);<br>}<br><br>private static void quickSort(int[] arr, int left, int right) {<br>    // Base case: If the array has fewer than two elements, it is already sorted<br>    if (left &gt;= right) {<br>        return;<br>    }<br>    // Choose a pivot element and partition the array<br>    int pivotIndex = partition(arr, left, right);<br>    // Recursively sort the left and right subarrays<br>    quickSort(arr, left, pivotIndex - 1);<br>    quickSort(arr, pivotIndex + 1, right);<br>}<br><br>private static int partition(int[] arr, int left, int right) {<br>    // Choose the rightmost element as the pivot<br>    int pivotValue = arr[right];<br>    int i = left - 1;<br>    for (int j = left; j &lt; right; j++) {<br>        // If the current element is less than or equal to the pivot, swap it with the element at index i+1<br>        if (arr[j] &lt;= pivotValue) {<br>            i++;<br>            swap(arr, i, j);<br>        }<br>    }<br>    // Swap the pivot element with the element at index i+1<br>    swap(arr, i + 1, right);<br>    // Return the index of the pivot element<br>    return i + 1;<br>}<br><br>private static void swap(int[] arr, int i, int j) {<br>    int temp = arr[i];<br>    arr[i] = arr[j];<br>    arr[j] = temp;<br>}</pre><p>In this implementation, arr is the array to be sorted. The quickSort method calls a helper method quickSort with additional arguments left and right, which indicate the indices of the leftmost and rightmost elements in the subarray to be sorted. The base case occurs when left &gt;= right, in which case the method returns without doing anything. The partition method chooses the rightmost element as the pivot and partitions the subarray around the pivot using a for loop. The swap method is used to swap elements in the array. After partitioning the array, pivotIndex is returned as the index of the pivot element, and quickSort is called recursively on the left and right subarrays.</p><p><strong>6. Heap sort</strong> is a comparison-based sorting algorithm that uses a binary heap data structure to sort the elements. It has a worst-case and average complexity of O(n log n). Java Code insert comment.</p><pre>public static void heapSort(int[] arr) {<br>    // Build a max heap from the array<br>    buildMaxHeap(arr);<br>    // Swap the root node (largest element) with the last element in the heap, and heapify the new root<br>    for (int i = arr.length - 1; i &gt; 0; i--) {<br>        swap(arr, 0, i);<br>        maxHeapify(arr, 0, i);<br>    }<br>}<br><br>private static void buildMaxHeap(int[] arr) {<br>    // Start from the last non-leaf node and heapify each node in reverse level order<br>    int n = arr.length;<br>    for (int i = (n / 2) - 1; i &gt;= 0; i--) {<br>        maxHeapify(arr, i, n);<br>    }<br>}<br><br>private static void maxHeapify(int[] arr, int i, int heapSize) {<br>    // Find the largest element among the node and its two children<br>    int leftChild = 2 * i + 1;<br>    int rightChild = 2 * i + 2;<br>    int largest = i;<br>    if (leftChild &lt; heapSize &amp;&amp; arr[leftChild] &gt; arr[largest]) {<br>        largest = leftChild;<br>    }<br>    if (rightChild &lt; heapSize &amp;&amp; arr[rightChild] &gt; arr[largest]) {<br>        largest = rightChild;<br>    }<br>    // If the largest element is not the node itself, swap the node with the largest element and heapify the new subtree<br>    if (largest != i) {<br>        swap(arr, i, largest);<br>        maxHeapify(arr, largest, heapSize);<br>    }<br>}<br><br>private static void swap(int[] arr, int i, int j) {<br>    int temp = arr[i];<br>    arr[i] = arr[j];<br>    arr[j] = temp;<br>}</pre><p>In this implementation, arr is the array to be sorted. The heapSort method first builds a max heap from the array using the buildMaxHeap method. The maxHeapify method is used to heapify a subtree rooted at the given node index i, assuming that the subtrees rooted at the left and right children of i are already max heaps. The buildMaxHeap method starts from the last non-leaf node in the heap and calls maxHeapify on each node in reverse level order. After building the max heap, the heapSort method repeatedly swaps the root node (which contains the largest element) with the last element in the heap and heapifies the new root. Finally, the sorted array is obtained by iterating over the heap from the end to the beginning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be5c23d11c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding Algorithm exercises for java interview.]]></title>
            <link>https://medium.com/@jirapong21/coding-algorithm-exercises-for-java-interview-21ddd9e221bb?source=rss-aa90439f0744------2</link>
            <guid isPermaLink="false">https://medium.com/p/21ddd9e221bb</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <dc:creator><![CDATA[Jirapong Bualuang]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 10:59:12 GMT</pubDate>
            <atom:updated>2023-02-25T10:59:12.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCb5sK7cBEIGLva6BcUshw.png" /></figure><ol><li><strong>Reverse a string: Write a Java function that takes a string as input and return a new string with the characters reversed. For example, if the input is “hello”, the function should return “olleh”.</strong></li></ol><pre>public static String reverseString(String str) {<br>    // Create a StringBuilder object to store the reversed string<br>    StringBuilder sb = new StringBuilder();<br>    <br>    // Loop through the input string from the end to the beginning<br>    for (int i = str.length() -1; i &gt;= 0; i--) {<br>        // Append each character to the StringBuilder object<br>        sb.append(str.charAt(i));<br>    }<br><br>    // Return the reversed string as a String object<br>    return sb.toString();<br>}</pre><p>To use this function to reverse the string “hello”, you would call it like this:</p><pre>String reversedString = reverseString(&quot;hello&quot;);<br>System.out.println(reversedString);</pre><p>This would output “olleh” to the console.</p><p>In the function, we first create a StringBuilder object to store the reversed string. We then loop through the input string from the end to the beginning using a for loop, and append each character to the StringBuilder object. Finally we return the reversed string by calling the toString() method on the StringBuilder object.</p><p><strong>2. Check if a string is a palindrome: Write a Java function that takes a string as input and returns true if the string is a palindrome (reads the same forwards and backwards), and false otherwise.</strong></p><pre>public static boolean isPalindrome(String str) {<br>    // Convert the input string to lowercase and remove all non-letter characters<br>    String cleanStr = str.toLowerCase().replaceAll(&quot;[^a-z]&quot;, &quot;&quot;);<br>    <br>    // Loop through the string from both ends towards the middle<br>    for (int i = 0, j = cleanStr.length() - 1; i &lt; j; i++, j--) {<br>        // If the characters at the two ends of the string are not equal, it&#39;s not a palindrome<br>        if (cleanStr.charAt(i) != cleanStr.charAt(j)) {<br>            return false;<br>        }<br>    }<br>    <br>    // If we have looped through the whole string without returning false, it&#39;s a palindrome<br>    return true;<br>}</pre><p>To use this function to check if the string “racecar” is a palindrome, you would call it like this:</p><pre>boolean isPal = isPalindrome(&quot;racecar&quot;);<br>System.out.println(isPal);</pre><p>This would output true to the console.</p><p>In the function, we first convert the input string to lowercase and remove all non-letter characters using the toLowerCase() and replaceAll() methods. We then loop through the cleaned string from both ends towards the middle using a for loop, comparing the characters at each end using the charAt() method. If any pair of characters are not equal, we immediately return false as it is not a palindrome. If we have looped through the whole string without returning false, we return true as it is a palindrome.</p><p>Note that this approach assumes that the string contains only alphabetic characters (A-Z, a-z), and ignores case (i.e., treats “Racecar” and “racecar” as palindromes). If you want to include other characters in the palindrome check or preserve case, you can modify the function accordingly.</p><p><strong>3. Find the nth Fibonacci number: Write a Java function that takes an integer n as input and returns the nth number in the Fibonacci sequence. The Fibonacci sequence is defined as follows: the first two numbers are 0 and 1, and each subsequent number is the sum of the previous two.</strong></p><pre>public static int fibonacci(int n) {<br>    if (n &lt;= 1) {<br>        // Base case: if n is 0 or 1, return n<br>        return n;<br>    }<br>    <br>    // Initialize variables to store the previous two Fibonacci numbers<br>    int prev1 = 0, prev2 = 1;<br>    <br>    // Loop through the Fibonacci sequence up to the nth number<br>    for (int i = 2; i &lt;= n; i++) {<br>        // Calculate the current Fibonacci number as the sum of the previous two<br>        int curr = prev1 + prev2;<br>        <br>        // Update the previous two Fibonacci numbers for the next iteration<br>        prev1 = prev2;<br>        prev2 = curr;<br>    }<br>    <br>    // Return the nth Fibonacci number<br>    return prev2;<br>}</pre><p>To use this function to find the 7th Fibonacci number, you would call it like this:</p><pre>int fib = fibonacci(7);<br>System.out.println(fib);</pre><p>This would output 13 to the console.</p><p>In the function, we first check if the input n is 0 or 1, which are the base cases for the Fibonacci sequence, and return n in those cases. We then initialize variables prev1 and prev2 to the first two Fibonacci numbers, 0 and 1. We then loop through the sequence up to the nth number using a for loop, calculating each number as the sum of the previous two and updating the previous two numbers for the next iteration. Finally, we return the nth Fibonacci number, which is stored in the prev2 variable after the loop completes.</p><p>Note that this approach calculates the Fibonacci sequence iteratively using a loop, which is more efficient than the recursive approach for larger values of n. However, if n is small, the recursive approach may be simpler and easier to understand.</p><p><strong>4. Merge two sorted arrays: Write a Java function that takes two sorted arrays as input and returns a new array that contains all the elements of both arrays, also sorted in ascending order.</strong></p><pre>public static int[] mergeSortedArrays(int[] arr1, int[] arr2) {<br>    // Initialize a new array to hold the merged result<br>    int[] merged = new int[arr1.length + arr2.length];<br>    <br>    // Initialize variables to keep track of the current index in each input array and the merged array<br>    int i = 0, j = 0, k = 0;<br>    <br>    // Loop through both input arrays until we reach the end of one of them<br>    while (i &lt; arr1.length &amp;&amp; j &lt; arr2.length) {<br>        // Compare the current elements in both arrays and add the smaller one to the merged array<br>        if (arr1[i] &lt; arr2[j]) {<br>            merged[k] = arr1[i];<br>            i++;<br>        } else {<br>            merged[k] = arr2[j];<br>            j++;<br>        }<br>        k++;<br>    }<br>    <br>    // If there are any remaining elements in the first input array, add them to the merged array<br>    while (i &lt; arr1.length) {<br>        merged[k] = arr1[i];<br>        i++;<br>        k++;<br>    }<br>    <br>    // If there are any remaining elements in the second input array, add them to the merged array<br>    while (j &lt; arr2.length) {<br>        merged[k] = arr2[j];<br>        j++;<br>        k++;<br>    }<br>    <br>    // Return the merged array<br>    return merged;<br>}</pre><p>To use this function to merge the sorted arrays [1, 3, 5, 7] and [2, 4, 6, 8], you would call it like this:</p><pre>int[] arr1 = {1, 3, 5, 7};<br>int[] arr2 = {2, 4, 6, 8};<br>int[] merged = mergeSortedArrays(arr1, arr2);<br>System.out.println(Arrays.toString(merged));</pre><p>This would output [1, 2, 3, 4, 5, 6, 7, 8] to the console.</p><p>In the function, we first initialize a new array to hold the merged result with a length equal to the sum of the lengths of the input arrays. We also initialize variables i, j, and k to keep track of the current index in each input array and the merged array, respectively. We then loop through both input arrays using a while loop until we reach the end of one of them, comparing the current elements in both arrays and adding the smaller one to the merged array. We increment the appropriate index variables after adding an element to the merged array.</p><p>After looping through both input arrays, we check if there are any remaining elements in either array using two more while loops and add them to the merged array. Finally, we return the merged array.</p><p>Note that this approach assumes that the input arrays are already sorted in ascending order. If they are not, you would need to sort them first before merging them.</p><p><strong>5. Determine if two strings are anagrams: Write a Java function that takes two strings as input and returns true if the two strings are anagrams (contain the same letters in a different order), and false otherwise.</strong></p><pre>public static boolean areAnagrams(String str1, String str2) {<br>    // If the two strings have different lengths, they cannot be anagrams<br>    if (str1.length() != str2.length()) {<br>        return false;<br>    }<br>    <br>    // Convert both strings to lowercase and convert them to character arrays<br>    char[] arr1 = str1.toLowerCase().toCharArray();<br>    char[] arr2 = str2.toLowerCase().toCharArray();<br>    <br>    // Sort both character arrays<br>    Arrays.sort(arr1);<br>    Arrays.sort(arr2);<br>    <br>    // If the sorted character arrays are equal, the two strings are anagrams<br>    return Arrays.equals(arr1, arr2);<br>}</pre><p>To use this function to check if the strings &quot;listen&quot; and &quot;silent&quot; are anagrams, you would call it like this:</p><pre>String str1 = &quot;listen&quot;;<br>String str2 = &quot;silent&quot;;<br>boolean areAnagrams = areAnagrams(str1, str2);<br>System.out.println(areAnagrams);</pre><p>This would output true to the console.</p><p>In the function, we first check if the two input strings have different lengths. If they do, they cannot be anagrams, so we immediately return false. If they have the same length, we convert both strings to lowercase using the toLowerCase() method and convert them to character arrays using the toCharArray() method.</p><p>We then sort both character arrays using the Arrays.sort() method, which sorts the array in ascending order. Finally, we compare the two sorted arrays using the Arrays.equals() method. If the sorted arrays are equal, the two input strings are anagrams and we return true. Otherwise, they are not anagrams and we return false.</p><p>Note that this approach assumes that the input strings are made up of ASCII characters. If the input strings can contain non-ASCII characters, you would need to use a more sophisticated approach to sort the character arrays, such as using the Collator class</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21ddd9e221bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[History of the Java language (Java)]]></title>
            <link>https://medium.com/@jirapong21/%E0%B8%9B%E0%B8%A3%E0%B8%B0%E0%B8%A7%E0%B8%B1%E0%B8%95%E0%B8%B4%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B9%80%E0%B8%9B%E0%B9%87%E0%B8%99%E0%B8%A1%E0%B8%B2%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2%E0%B8%88%E0%B8%B2%E0%B8%A7%E0%B8%B2-java-a5da22372949?source=rss-aa90439f0744------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5da22372949</guid>
            <dc:creator><![CDATA[Jirapong Bualuang]]></dc:creator>
            <pubDate>Fri, 10 Feb 2017 16:29:47 GMT</pubDate>
            <atom:updated>2023-12-28T13:55:24.083Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*kEQFD6lw8ux1PN7H2vxEHw.jpeg" /></figure><p>In 1991, a team of Sun Microsystems engineers led by James Gosling developed the “Green Project” to research and create intelligent electronic devices that could be controlled by remote control.</p><p>Gosling was tasked with creating a new language for devices. The language created must be small. So that the device will not have to use a very high processing unit.</p><p>Another important thing is that it must be a language that does not depend on just one type of hardware device. (Platform-independent)</p><p>Later it was developed until it was successful and it was named “Oak” but after inspection It was discovered that someone had already registered the name “Oak” as a programming language. Therefore, the name was changed from “Oak” to “Java” instead.</p><p>The next problem was when this project was actually launched. No one is paying attention as they should. causing this project to be stopped</p><p>Later in 1994, Bill Joy proposed the idea that Let’s use the Java language for use on the Internet. This is the beginning of change. Because later “WebRunner” was developed, later the name was changed to “HotJava”</p><p>WebRunner is more of a browser than a viewer. Because you can call Java applet to run on web pages.</p><p>Later in 1995, the Netscape Company incorporated Java technology with the Netscape browser. Since then, Java has grown in popularity. until now</p><p>Currently, Oracle has purchased Java from Sun Microsystems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5da22372949" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>