<?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 Articles Media on Medium]]></title>
        <description><![CDATA[Stories by Articles Media on Medium]]></description>
        <link>https://medium.com/@articlesmedia?source=rss-526562577041------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CfriQidHRklE6IbJM7HOgw.png</url>
            <title>Stories by Articles Media on Medium</title>
            <link>https://medium.com/@articlesmedia?source=rss-526562577041------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 02:21:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@articlesmedia/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[PayPal Auto-Transfer Time to India]]></title>
            <link>https://articlesmedia.medium.com/paypal-auto-transfer-time-to-india-456713520b73?source=rss-526562577041------2</link>
            <guid isPermaLink="false">https://medium.com/p/456713520b73</guid>
            <category><![CDATA[paypal-account]]></category>
            <category><![CDATA[paypal]]></category>
            <category><![CDATA[paypal-money]]></category>
            <dc:creator><![CDATA[Articles Media]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 16:00:37 GMT</pubDate>
            <atom:updated>2026-10-04T16:00:37.223Z</atom:updated>
            <content:encoded><![CDATA[<p>An automatic transfer from <strong>PayPal to a linked Indian bank account takes up to 5 business days</strong> to completely clear and reflect in your bank statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VN6E0OmlBc0_MaMduG0jsA.jpeg" /></figure><h4>Understanding PayPal Auto-Transfers to India — Timing, Rules, and What to Expect</h4><p>If you are a freelancer, exporter, or business owner in India receiving international payments, PayPal is likely a staple in your toolkit. However, if you are new to the platform, you might notice something unusual: you cannot keep your earnings sitting in your PayPal wallet, and the money seems to move on its own.</p><p>This is known as the PayPal auto-transfer (or auto-sweep) system. Here is a transparent breakdown of exactly how long it takes for your money to reach your Indian bank account and why the process works the way it does.</p><h4>The Short Answer: Up to 5 Business Days</h4><p>As a general rule, it takes up to <strong>5 business days</strong> for funds to completely clear from PayPal and reflect in your linked Indian bank account balance.</p><p>While the transaction might say “Completed” on your PayPal dashboard much sooner, that status simply means PayPal has successfully pushed the money out of its system. It does not mean it has cleared your local bank’s processing network yet.</p><p>The Daily “Auto-Sweep” Routine</p><p>Unlike users in many Western countries, PayPal users in India cannot hold foreign currency balances or use their PayPal wallet to make domestic purchases. Due to strict regulatory mandates from the Reserve Bank of India (RBI), PayPal must export all foreign earnings out of its digital ecosystem daily.</p><p>Here is the step-by-step timeline of that journey:</p><ul><li><strong>Step 1: The Daily Sweep (Within 24 Hours):</strong> At the end of every business day, PayPal automatically bundles your received payments and initiates a transfer to your primary linked bank account.</li><li><strong>Step 2: PayPal Processing (24 to 72 Hours):</strong> PayPal handles the currency conversion (from USD, EUR, GBP, etc., into INR) and routes the funds to the local clearing network.</li><li><strong>Step 3: Bank Settlement (1 to 2 Business Days):</strong> Your local Indian bank receives the electronic transfer, verifies the transaction, and credits it to your savings or current account.</li></ul><h3>Why Is My Payment Delayed?</h3><p>If your money is taking longer than usual, it is almost always due to one of three common bottlenecks:</p><h4>1. Weekends and Bank Holidays</h4><p>PayPal’s timeline relies heavily on “business days.” If a client pays you on a Friday night, the auto-sweep might occur over the weekend, but Indian banks will not begin processing the inbound local transfer until Monday morning. Public or national bank holidays will add an extra 24-to-48-hour delay.</p><h4>2. Purpose Code Mismatches</h4><p>To legally receive international funds in India, you must select a valid <strong>Purpose Code</strong> in your PayPal account settings. This code tells the RBI exactly what type of work you did to earn that foreign currency. If your purpose code is missing, incorrect, or mismatched, your bank may temporarily freeze the incoming credit until you provide manual clarification.</p><h4>3. Account Review or Verification Flags</h4><p>If you suddenly receive a payout that is significantly larger than your usual transaction history, PayPal’s risk management system may place a temporary hold on the funds. This hold pauses the auto-sweep mechanism until they verify the legitimacy of the payment.</p><h4>Can You Speed Up the Process?</h4><p>The short answer is <strong>no</strong>. Because of the RBI regulations governing cross-border trade, manual or instant transfers are disabled for Indian PayPal merchants. The automatic daily sweep is the mandatory, default method for extracting your funds.</p><p>To ensure your transfers happen as smoothly as possible, always double-check that your bank account is fully verified on PayPal, your PAN card details match perfectly, and your chosen Purpose Code accurately reflects your business activities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=456713520b73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collections Framework in Java]]></title>
            <link>https://medium.com/illumination/collections-framework-in-java-62ac90d9d8f9?source=rss-526562577041------2</link>
            <guid isPermaLink="false">https://medium.com/p/62ac90d9d8f9</guid>
            <category><![CDATA[collections-framework]]></category>
            <category><![CDATA[java-collection]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[collections-in-java]]></category>
            <dc:creator><![CDATA[Articles Media]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 05:40:46 GMT</pubDate>
            <atom:updated>2026-09-25T05:40:46.260Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Java Collections Framework (JCF) is one of the most important concepts in Java programming.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*F1an7G0K1wr4kHuUrJPFzA.png" /><figcaption><strong>Java Collections Framework</strong></figcaption></figure><p>Almost every real-world application needs to manage multiple pieces of data — such as employee records, product lists, usernames, orders, messages, or tasks.</p><p>Instead of creating separate variables or building data structures from scratch, Java provides a well-designed framework containing <strong>interfaces, classes, and utility methods</strong> to store and manipulate groups of objects efficiently.</p><p>The image below represents the basic hierarchy of some important interfaces and implementations in the Java Collections Framework:</p><p><strong>Iterable → Collection → List / Set / Queue → Implementation Classes</strong></p><p>Let’s understand the Collections Framework from scratch.</p><h3>What is the Java Collections Framework?</h3><p>The <strong>Java Collections Framework</strong> is a unified architecture that provides:</p><ul><li>Interfaces for defining different types of collections</li><li>Classes that implement those interfaces</li><li>Methods for adding, removing, searching, and sorting data</li><li>Algorithms for performing common operations</li></ul><p>In simple words:</p><blockquote><strong><em>The Collections Framework provides ready-made data structures to store and manage groups of objects.</em></strong></blockquote><p>For example, instead of creating many variables:</p><pre>String student1 = &quot;Ali&quot;;<br>String student2 = &quot;John&quot;;<br>String student3 = &quot;Sara&quot;;<br>String student4 = &quot;David&quot;;</pre><p>We can use a collection:</p><pre>ArrayList&lt;String&gt; students = new ArrayList&lt;&gt;();<br>students.add(&quot;Ali&quot;);<br>students.add(&quot;John&quot;);<br>students.add(&quot;Sara&quot;);<br>students.add(&quot;David&quot;);</pre><p>Now all student objects are managed inside one collection.</p><h3>Why Do We Need Collections?</h3><p>Before Collections, programmers often used arrays to store multiple values.</p><pre>String[] names = new String[5];</pre><p>Arrays are useful, but they have some limitations.</p><h3>Limitations of Arrays</h3><ul><li>Fixed size</li><li>Difficult insertion and deletion</li><li>Limited built-in methods</li><li>Cannot easily change size dynamically</li></ul><p>For example:</p><pre>int[] numbers = new int[5];</pre><p>The size is fixed at 5. If you need more space, you need to create another array.</p><p>Collections solve many of these problems.</p><pre>ArrayList&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();<br>numbers.add(10);<br>numbers.add(20);<br>numbers.add(30);</pre><p>The ArrayList can grow dynamically as elements are added.</p><h3>Understanding the Hierarchy</h3><p>The basic structure shown in the diagram is:</p><pre>                   Iterable<br>                       |<br>                   Collection<br>                       |<br>        --------------------------------<br>        |              |               |<br>       List           Set            Queue<br>        |              |               |<br>   ArrayList       HashSet       PriorityQueue<br>   LinkedList      TreeSet<br>                   LinkedHashSet</pre><p>The diagram represents an important concept:</p><blockquote><strong><em>As we move downward, we go from general interfaces to more specific interfaces and finally to concrete implementation classes.</em></strong></blockquote><p>Let’s understand each level.</p><h3>1. Iterable Interface</h3><p>At the top of the hierarchy is the <strong>Iterable</strong> interface.</p><p>The main purpose of Iterable is to allow an object to be traversed or looped through.</p><p>For example:</p><pre>for (String name : names) {<br>    System.out.println(name);<br>}</pre><p>This enhanced for-loop works because collections implement the Iterable interface.</p><p>The Iterable interface provides the iterator() method.</p><p>Conceptually:</p><pre>Iterator&lt;T&gt; iterator();</pre><p>An iterator allows us to access elements one by one.</p><p>Example:</p><pre>ArrayList&lt;String&gt; names = new ArrayList&lt;&gt;();names.add(&quot;Ali&quot;);<br>names.add(&quot;John&quot;);<br>names.add(&quot;Sara&quot;);Iterator&lt;String&gt; iterator = names.iterator();<br>while (iterator.hasNext()) {<br>    System.out.println(iterator.next());<br>}</pre><p>Output:</p><pre>Ali<br>John<br>Sara</pre><h3>Why is Iterable important?</h3><p>Because it provides a standard way to traverse different collections.</p><p>Whether you are working with:</p><ul><li>ArrayList</li><li>LinkedList</li><li>HashSet</li><li>TreeSet</li></ul><p>You can iterate through their elements.</p><h3>2. Collection Interface</h3><p>The next major interface is <strong>Collection</strong>.</p><p>The Collection interface represents a <strong>group of objects</strong>.</p><p>It provides common operations that most collections need.</p><p>Some commonly used methods are:</p><pre>add()<br>remove()<br>size()<br>isEmpty()<br>contains()<br>clear()</pre><p>For example:</p><pre>Collection&lt;String&gt; names = new ArrayList&lt;&gt;();<br>names.add(&quot;Ali&quot;);<br>names.add(&quot;John&quot;);<br>System.out.println(names.size());</pre><p>Output:</p><pre>2</pre><p>The Collection interface acts as the parent for major collection types such as:</p><ul><li>List</li><li>Set</li><li>Queue</li></ul><p>Each of these has different rules and behavior.</p><h3>Collection vs Collections</h3><p>Beginners often confuse these two terms.</p><h3>Collection</h3><p>Collection is an <strong>interface</strong>.</p><pre>Collection&lt;String&gt; names;</pre><p>It represents a group of objects.</p><h3>Collections</h3><p>Collections is a <strong>utility class</strong> containing useful static methods.</p><p>For example:</p><pre>Collections.sort(list);<br>Collections.reverse(list);<br>Collections.max(list);<br>Collections.min(list);</pre><p>So remember:</p><blockquote><strong><em>Collection = Interface</em></strong><em><br></em><strong><em>Collections = Utility class</em></strong></blockquote><h3>3. List Interface</h3><p>A <strong>List</strong> is an ordered collection of elements.</p><p>The most important characteristics of a List are:</p><ul><li>Maintains insertion order</li><li>Allows duplicate elements</li><li>Supports index-based access</li><li>Can contain multiple null values depending on implementation</li></ul><p>Example:</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();names.add(&quot;Ali&quot;);<br>names.add(&quot;John&quot;);<br>names.add(&quot;Ali&quot;);<br>names.add(&quot;Sara&quot;);<br>System.out.println(names);</pre><p>Output:</p><pre>[Ali, John, Ali, Sara]</pre><p>Notice that &quot;Ali&quot; appears twice.</p><p>This is allowed because Lists allow duplicates.</p><h3>Common List Implementations</h3><p>The diagram shows two major implementations:</p><ul><li>ArrayList</li><li>LinkedList</li></ul><p>Let’s understand them.</p><h3>ArrayList</h3><p>ArrayList is one of the most commonly used collection classes in Java.</p><p>It uses a <strong>dynamic array</strong> internally.</p><p>Example:</p><pre>ArrayList&lt;String&gt; students = new ArrayList&lt;&gt;();students.add(&quot;Ali&quot;);<br>students.add(&quot;John&quot;);<br>students.add(&quot;Sara&quot;);<br>System.out.println(students);</pre><h3>Important characteristics</h3><ul><li>Maintains insertion order</li><li>Allows duplicates</li><li>Allows index-based access</li><li>Dynamically grows</li><li>Fast for accessing elements</li><li>Slower for frequent insertion or deletion in the middle</li></ul><p>Example of accessing by index:</p><pre>System.out.println(students.get(1));</pre><p>Output:</p><pre>John</pre><h3>When should you use ArrayList?</h3><p>Use ArrayList when:</p><ul><li>You frequently access elements by index</li><li>You mostly add elements at the end</li><li>You need an ordered collection</li><li>Duplicates are allowed</li></ul><h3>LinkedList</h3><p>LinkedList is another implementation of the List interface.</p><p>Unlike ArrayList, it does not store elements in a simple continuous array structure.</p><p>Conceptually, elements are connected as nodes.</p><pre>[Ali] → [John] → [Sara] → [David]</pre><p>Each node maintains connections to neighboring nodes.</p><p>Example:</p><pre>LinkedList&lt;String&gt; names = new LinkedList&lt;&gt;();<br>names.add(&quot;Ali&quot;);<br>names.add(&quot;John&quot;);<br>names.add(&quot;Sara&quot;);</pre><h3>Characteristics</h3><ul><li>Maintains insertion order</li><li>Allows duplicates</li><li>Can grow dynamically</li><li>Efficient for insertion and deletion at suitable positions</li><li>Slower for random index access compared to ArrayList</li></ul><h3>When should you use LinkedList?</h3><p>Use LinkedList when your program performs frequent:</p><ul><li>Insertions</li><li>Deletions</li><li>Additions at the beginning or end</li></ul><h3>ArrayList vs LinkedList</h3><p>A simple rule:</p><blockquote><em>Use </em><strong><em>ArrayList</em></strong><em> for frequent reading/accessing.<br> Consider </em><strong><em>LinkedList</em></strong><em> when your workload benefits from frequent structural insertions/removals.</em></blockquote><h3>4. Set Interface</h3><p>A <strong>Set</strong> is a collection that does <strong>not allow duplicate elements</strong>.</p><p>Example:</p><pre>Set&lt;String&gt; names = new HashSet&lt;&gt;();names.add(&quot;Ali&quot;);<br>names.add(&quot;John&quot;);<br>names.add(&quot;Ali&quot;);<br>names.add(&quot;Sara&quot;);<br>System.out.println(names);</pre><p>Even though &quot;Ali&quot; was added twice, it will only appear once.</p><h3>Main characteristics of Set</h3><ul><li>Does not allow duplicates</li><li>Does not support index-based access</li><li>Different implementations handle ordering differently</li></ul><p>The diagram includes:</p><ul><li>HashSet</li><li>TreeSet</li><li>LinkedHashSet</li></ul><p>Let’s explore each one.</p><h3>HashSet</h3><p>HashSet stores unique elements.</p><p>Example:</p><pre>HashSet&lt;String&gt; names = new HashSet&lt;&gt;();names.add(&quot;Ali&quot;);<br>names.add(&quot;John&quot;);<br>names.add(&quot;Sara&quot;);<br>names.add(&quot;Ali&quot;);<br>System.out.println(names);</pre><h3>Characteristics</h3><ul><li>No duplicate elements</li><li>Does not guarantee insertion order</li><li>Generally provides fast add, remove, and search operations</li><li>Uses hashing internally</li></ul><p>Important:</p><pre>HashSet ≠ Sorted collection<br>HashSet ≠ Insertion ordered collection</pre><p>The order of elements should not be relied upon.</p><h3>When to use HashSet?</h3><p>Use HashSet when:</p><ul><li>You need unique elements</li><li>Order is not important</li><li>Fast lookup is important</li></ul><p>For example, storing unique email addresses:</p><pre>Set&lt;String&gt; emails = new HashSet&lt;&gt;();</pre><h3>LinkedHashSet</h3><p>LinkedHashSet is similar to HashSet, but it maintains insertion order.</p><p>Example:</p><pre>LinkedHashSet&lt;String&gt; names = new LinkedHashSet&lt;&gt;();names.add(&quot;Ali&quot;);<br>names.add(&quot;John&quot;);<br>names.add(&quot;Sara&quot;);<br>System.out.println(names);</pre><p>Output:</p><pre>[Ali, John, Sara]</pre><h3>Characteristics</h3><ul><li>No duplicates</li><li>Maintains insertion order</li><li>Slightly more overhead than HashSet</li></ul><h3>When to use LinkedHashSet?</h3><p>Use it when:</p><blockquote><em>You need unique elements </em><strong><em>and</em></strong><em> want to remember the order in which they were inserted.</em></blockquote><h3>TreeSet</h3><p>TreeSet stores unique elements in sorted order.</p><p>Example:</p><pre>TreeSet&lt;Integer&gt; numbers = new TreeSet&lt;&gt;();numbers.add(50);<br>numbers.add(10);<br>numbers.add(30);<br>numbers.add(20);<br>System.out.println(numbers);</pre><p>Output:</p><pre>[10, 20, 30, 50]</pre><h3>Characteristics</h3><ul><li>No duplicates</li><li>Automatically sorts elements</li><li>Does not maintain insertion order</li><li>Typically slower than HashSet for basic operations because ordering must be maintained</li></ul><h3>When should you use TreeSet?</h3><p>Use TreeSet when:</p><ul><li>Duplicate values are not allowed</li><li>You need sorted data</li></ul><p>For example:</p><pre>Set&lt;Integer&gt; scores = new TreeSet&lt;&gt;();</pre><h3>HashSet vs LinkedHashSet vs TreeSet</h3><p>A useful way to remember:</p><blockquote><strong><em>HashSet → Unique elements</em></strong><em><br> </em><strong><em>LinkedHashSet → Unique + insertion order</em></strong><em><br> </em><strong><em>TreeSet → Unique + sorted</em></strong></blockquote><h3>5. Queue Interface</h3><p>A <strong>Queue</strong> is designed for processing elements in a particular order.</p><p>The most common principle associated with queues is:</p><blockquote><strong><em>FIFO — First In, First Out</em></strong></blockquote><p>Imagine a line at a ticket counter.</p><pre>Person 1 → Person 2 → Person 3</pre><p>The person who enters first gets served first.</p><p>Example:</p><pre>Queue&lt;String&gt; queue = new LinkedList&lt;&gt;();queue.add(&quot;Ali&quot;);<br>queue.add(&quot;John&quot;);<br>queue.add(&quot;Sara&quot;);<br>System.out.println(queue.poll());</pre><p>Output:</p><pre>Ali</pre><p>The first element is removed first.</p><h3>Important Queue Methods</h3><h3>add()</h3><p>Adds an element.</p><pre>queue.add(&quot;Task&quot;);</pre><h3>offer()</h3><p>Adds an element and is designed for capacity-restricted queues to report failure without throwing an exception.</p><pre>queue.offer(&quot;Task&quot;);</pre><h3>poll()</h3><p>Retrieves and removes the head of the queue.</p><pre>queue.poll();</pre><h3>peek()</h3><p>Retrieves the head without removing it.</p><pre>queue.peek();</pre><h3>PriorityQueue</h3><p>PriorityQueue is a special type of Queue.</p><p>Unlike a normal FIFO queue, elements are processed according to their <strong>priority</strong>.</p><p>Example:</p><pre>PriorityQueue&lt;Integer&gt; numbers = new PriorityQueue&lt;&gt;();numbers.add(30);<br>numbers.add(10);<br>numbers.add(20);<br>System.out.println(numbers.poll());</pre><p>Output:</p><pre>10</pre><p>The highest-priority element according to the queue’s ordering is processed first. With Java’s default ordering for numbers, the smallest value has the highest priority.</p><h3>Example use cases</h3><p>Priority queues are useful for:</p><ul><li>Task scheduling</li><li>Hospital emergency systems</li><li>CPU scheduling</li><li>Graph algorithms</li><li>Job processing systems</li></ul><h3>Important Note: Map Interface</h3><p>Although Map is part of the broader Java Collections Framework, it is <strong>not a child of the Collection interface</strong>.</p><p>This is because a Map stores <strong>key-value pairs</strong> rather than individual elements.</p><p>Conceptually:</p><pre>Key → Value</pre><p>Example:</p><pre>Map&lt;Integer, String&gt; students = new HashMap&lt;&gt;();students.put(101, &quot;Ali&quot;);<br>students.put(102, &quot;John&quot;);<br>students.put(103, &quot;Sara&quot;);</pre><p>Here:</p><pre>101 → Ali<br>102 → John<br>103 → Sara</pre><p>You can retrieve a value using its key:</p><pre>System.out.println(students.get(102));</pre><p>Output:</p><pre>John</pre><h3>Common Map Implementations</h3><p>Some important implementations include:</p><ul><li>HashMap</li><li>LinkedHashMap</li><li>TreeMap</li></ul><h3>HashMap</h3><ul><li>Stores key-value pairs</li><li>Keys must be unique</li><li>Does not guarantee insertion order</li></ul><h3>LinkedHashMap</h3><ul><li>Stores key-value pairs</li><li>Maintains insertion order</li></ul><h3>TreeMap</h3><ul><li>Stores key-value pairs</li><li>Sorts entries based on keys</li></ul><h3>Understanding Interfaces and Classes</h3><p>One of the most important concepts in the Collections Framework is the difference between an <strong>interface</strong> and an <strong>implementation class</strong>.</p><p>For example:</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><p>Here:</p><pre>List        → Interface<br>ArrayList   → Implementation Class</pre><p>Why is this useful?</p><p>Because you can change the implementation without significantly changing the rest of your code.</p><p>For example:</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><p>Later:</p><pre>List&lt;String&gt; names = new LinkedList&lt;&gt;();</pre><p>The reference type remains List.</p><p>This follows the programming principle:</p><blockquote><strong><em>Program to interfaces, not implementations.</em></strong></blockquote><h3>Common Methods in Collections</h3><p>Most collection classes provide useful methods.</p><h3>add()</h3><p>Adds an element.</p><pre>list.add(&quot;Java&quot;);</pre><h3>remove()</h3><p>Removes an element.</p><pre>list.remove(&quot;Java&quot;);</pre><h3>size()</h3><p>Returns the number of elements.</p><pre>System.out.println(list.size());</pre><h3>contains()</h3><p>Checks whether an element exists.</p><pre>System.out.println(list.contains(&quot;Java&quot;));</pre><h3>isEmpty()</h3><p>Checks whether a collection is empty.</p><pre>System.out.println(list.isEmpty());</pre><h3>clear()</h3><p>Removes all elements.</p><pre>list.clear();</pre><h3>Iterating Through Collections</h3><p>Collections can be traversed in multiple ways.</p><h3>Enhanced For Loop</h3><pre>for (String name : names) {<br>    System.out.println(name);<br>}</pre><h3>Using Iterator</h3><pre>Iterator&lt;String&gt; iterator = names.iterator();<br>while (iterator.hasNext()) {<br>    System.out.println(iterator.next());<br>}</pre><h3>Using forEach()</h3><pre>names.forEach(name -&gt; System.out.println(name));</pre><p>These different approaches provide flexibility when processing collection data.</p><h3>The Collections Utility Class</h3><p>Java provides the Collections utility class containing helpful methods.</p><h3>Sorting</h3><pre>List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();numbers.add(30);<br>numbers.add(10);<br>numbers.add(20);Collections.sort(numbers);System.out.println(numbers);</pre><p>Output:</p><pre>[10, 20, 30]</pre><h3>Reversing</h3><pre>Collections.reverse(numbers);</pre><h3>Finding Maximum Value</h3><pre>System.out.println(Collections.max(numbers));</pre><h3>Finding Minimum Value</h3><pre>System.out.println(Collections.min(numbers));</pre><h3>Shuffling</h3><pre>Collections.shuffle(numbers);</pre><p>The Collections class saves developers from writing these common algorithms manually.</p><h3>Choosing the Right Collection</h3><p>Choosing the correct collection depends on the requirement.</p><h3>Use ArrayList when:</h3><ul><li>Order matters</li><li>Duplicates are allowed</li><li>Frequent index access is needed</li></ul><h3>Use LinkedList when:</h3><ul><li>Frequent additions/removals are needed</li><li>Queue/deque-style operations are required</li></ul><h3>Use HashSet when:</h3><ul><li>Only unique elements are needed</li><li>Order is not important</li></ul><h3>Use LinkedHashSet when:</h3><ul><li>Unique elements are needed</li><li>Insertion order should be preserved</li></ul><h3>Use TreeSet when:</h3><ul><li>Unique elements are needed</li><li>Automatic sorting is required</li></ul><h3>Use PriorityQueue when:</h3><ul><li>Elements must be processed according to priority</li></ul><h3>Use HashMap when:</h3><ul><li>Data needs to be stored as key-value pairs</li><li>Fast lookup by key is needed</li></ul><h3>A Real-World Example</h3><p>Imagine building an e-commerce application.</p><p>Different situations require different collections.</p><h3>Shopping Cart</h3><pre>List&lt;String&gt; cart = new ArrayList&lt;&gt;();</pre><p>A customer may add the same product multiple times, and order matters.</p><h3>Unique Product Categories</h3><pre>Set&lt;String&gt; categories = new HashSet&lt;&gt;();</pre><p>Duplicate categories should not exist.</p><h3>Processing Orders</h3><pre>Queue&lt;String&gt; orders = new LinkedList&lt;&gt;();</pre><p>Orders may be processed in sequence.</p><h3>Emergency Delivery Priority</h3><pre>PriorityQueue&lt;Integer&gt; priorityOrders = new PriorityQueue&lt;&gt;();</pre><p>Higher-priority orders can be processed according to defined priority.</p><h3>Product Lookup</h3><pre>Map&lt;Integer, String&gt; products = new HashMap&lt;&gt;();</pre><p>A product ID can act as the key.</p><p>This demonstrates why understanding collections is essential for real-world software development.</p><h3>Final Thoughts</h3><p>The <strong>Java Collections Framework</strong> is much more than a collection of classes. It provides a standardized way to organize and manipulate data efficiently.</p><p>The key to mastering Collections is not memorizing every class. Instead, focus on understanding three important questions:</p><ol><li><strong>Do I need duplicates?</strong></li><li><strong>Does the order of elements matter?</strong></li><li><strong>Do I need fast access, insertion, deletion, or sorting?</strong></li></ol><p>Once you can answer these questions, choosing the right collection becomes much easier.</p><p>The hierarchy starts broadly with <strong>Iterable</strong>, moves to <strong>Collection</strong>, and then branches into specialized interfaces such as <strong>List, Set, and Queue</strong>. Each branch provides different behavior and implementation classes designed for specific use cases.</p><blockquote><strong><em>The real power of the Java Collections Framework is choosing the right data structure for the right problem.</em></strong></blockquote><p>Mastering Collections is a major step toward becoming a strong Java developer, because efficient data management is at the heart of almost every real-world application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62ac90d9d8f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illumination/collections-framework-in-java-62ac90d9d8f9">Collections Framework in Java</a> was originally published in <a href="https://medium.com/illumination">ILLUMINATION</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stateful vs Stateless Components in React]]></title>
            <link>https://articlesmedia.medium.com/stateful-vs-stateless-components-in-react-04f9458ec0e9?source=rss-526562577041------2</link>
            <guid isPermaLink="false">https://medium.com/p/04f9458ec0e9</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[stateful-component]]></category>
            <category><![CDATA[stateless-component]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Articles Media]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 13:58:19 GMT</pubDate>
            <atom:updated>2026-08-06T13:58:19.388Z</atom:updated>
            <content:encoded><![CDATA[<p>React components can be broadly classified into two categories:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0P9jQEC7oPsOTyL38ZHmIQ.png" /></figure><ol><li><strong>Stateful Components</strong></li><li><strong>Stateless Components</strong></li></ol><p>The difference is <strong>whether the component manages its own state</strong>.</p><h3>1. Stateful Components</h3><p>A <strong>stateful component</strong> is a component that has its own <strong>state</strong> using hooks like useState (or state in class components).</p><p>Since it owns state, it can:</p><ul><li>Store data</li><li>Update data</li><li>Re-render when the data changes</li><li>Respond to user interactions</li></ul><h3>Example</h3><pre>import { useState } from &quot;react&quot;;<br>function Counter() {<br>  const [count, setCount] = useState(0);<br>  return (<br>    &lt;&gt;<br>      &lt;h2&gt;{count}&lt;/h2&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        Increment<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Flow</h3><h3>Step 1</h3><p>Component renders.</p><pre>count = 0</pre><p>UI:</p><pre>0</pre><h3>Step 2</h3><p>User clicks</p><pre>Increment</pre><h3>Step 3</h3><p>React executes</p><pre>setCount(count + 1);</pre><p>which becomes</p><pre>setCount(1);</pre><h3>Step 4</h3><p>React updates the state.</p><pre>count = 1</pre><h3>Step 5</h3><p>React re-renders the component.</p><p>UI:</p><pre>1</pre><p>Flow Diagram</p><pre>Component Renders<br>        │<br>        ▼<br>State Created<br>        │<br>        ▼<br>User Action<br>        │<br>        ▼<br>setState()<br>        │<br>        ▼<br>State Changes<br>        │<br>        ▼<br>React Re-renders</pre><p>Because this component stores and updates its own state, it is <strong>stateful</strong>.</p><h3>2. Stateless Components</h3><p>A <strong>stateless component</strong> does <strong>not</strong> manage its own state.</p><p>It simply receives data through <strong>props</strong> and displays it.</p><p>It cannot change its own data unless its parent sends new props.</p><h3>Example</h3><pre>function Greeting({ name }) {<br>  return &lt;h1&gt;Hello, {name}&lt;/h1&gt;;<br>}</pre><p>Parent Component</p><pre>function App() {<br>  return &lt;Greeting name=&quot;Qayyum&quot; /&gt;;<br>}</pre><h3>Flow</h3><p>Parent renders.</p><pre>name = &quot;Qayyum&quot;</pre><p>↓</p><p>Passes prop</p><pre>&lt;Greeting name=&quot;Qayyum&quot; /&gt;</pre><p>↓</p><p>Child receives prop</p><pre>function Greeting({ name })</pre><p>↓</p><p>Displays</p><pre>Hello, Qayyum</pre><p>The child never changes the value.</p><p>It only displays what it receives.</p><p>Flow Diagram</p><pre>Parent<br> │<br> ▼<br>Props<br> │<br> ▼<br>Child Displays Data</pre><p>No state.</p><p>No updates.</p><p>No useState.</p><h3>Comparison</h3><h3>Stateful Component</h3><pre>function Counter() {<br>  const [count, setCount] = useState(0);<br>return (<br>    &lt;&gt;<br>      &lt;h2&gt;{count}&lt;/h2&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        +<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Owns the data.</p><p>Can change the data.</p><h3>Stateless Component</h3><pre>function CounterDisplay({ count }) {<br>  return &lt;h2&gt;{count}&lt;/h2&gt;;<br>}</pre><p>Receives the data.</p><p>Displays the data.</p><p>Cannot change it.</p><h3>Visual Comparison</h3><h3>Stateful</h3><pre>Component<br>    │<br>    ▼<br>Own State<br>    │<br>    ▼<br>Updates State<br>    │<br>    ▼<br>Re-renders</pre><h3>Stateless</h3><pre>Parent<br>   │<br>   ▼<br>Props<br>   │<br>   ▼<br>Child Displays</pre><h3>Can a Stateless Component Re-render?</h3><p><strong>Yes.</strong></p><p>A stateless component <strong>can re-render</strong>, but <strong>not because of its own state</strong>.</p><p>It re-renders when:</p><ul><li>Its parent re-renders.</li><li>It receives new props.</li></ul><p>Example:</p><pre>function Greeting({ name }) {<br>  return &lt;h1&gt;Hello {name}&lt;/h1&gt;;<br>}</pre><p>If the parent changes</p><pre>&lt;Greeting name=&quot;Qayyum&quot; /&gt;</pre><p>to</p><pre>&lt;Greeting name=&quot;Abdul&quot; /&gt;</pre><p>React re-renders Greeting with the new prop.</p><h3>Modern React Note</h3><p>In older React terminology:</p><ul><li>Class components were usually called <strong>stateful</strong>.</li><li>Function components were usually called <strong>stateless</strong>.</li></ul><p>However, since the introduction of <strong>Hooks</strong> (React 16.8), function components can also use useState, useEffect, and other hooks.</p><p>For example:</p><pre>function Counter() {<br>  const [count, setCount] = useState(0);<br>return &lt;h1&gt;{count}&lt;/h1&gt;;<br>}</pre><p>This is a <strong>function component</strong>, but it is <strong>stateful</strong> because it uses state.</p><p>So today:</p><ul><li>A <strong>function component can be stateful or stateless</strong>.</li><li>Being a function component does <strong>not</strong> automatically mean it is stateless.</li></ul><h3>Quick Comparison Table</h3><p>FeatureStateful ComponentStateless ComponentHas state (useState)✅❌Receives props✅✅Can update its own data✅❌Can re-render due to state changes✅❌Can re-render due to new props✅✅Main purposeManage data and behaviorDisplay data</p><h3>Interview Answer (Short Version)</h3><p>A <strong>stateful component</strong> is a component that manages its own state using hooks like useState. It can update its data and re-render itself when the state changes.</p><p>A <strong>stateless component</strong> does not manage its own state. It receives data through props and displays it. It re-renders only when its parent re-renders or when it receives new props.</p><p><strong>Simple Rule to Remember:</strong></p><ul><li><strong>Stateful = Owns and updates data.</strong></li><li><strong>Stateless = Receives and displays data.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04f9458ec0e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Pick a Random Winner from YouTube Comments for Free ?]]></title>
            <link>https://articlesmedia.medium.com/how-to-pick-a-random-winner-from-youtube-comments-for-free-complete-guide-028722e758a9?source=rss-526562577041------2</link>
            <guid isPermaLink="false">https://medium.com/p/028722e758a9</guid>
            <category><![CDATA[youtube-tool]]></category>
            <category><![CDATA[youtube-giveaway]]></category>
            <category><![CDATA[random-comment-picker]]></category>
            <category><![CDATA[youtube-comment-picker]]></category>
            <category><![CDATA[content-creator-tips]]></category>
            <dc:creator><![CDATA[Articles Media]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 09:53:43 GMT</pubDate>
            <atom:updated>2026-06-23T09:54:11.899Z</atom:updated>
            <content:encoded><![CDATA[<p>Running a giveaway on YouTube is one of the easiest ways to increase engagement, attract new subscribers, and reward loyal viewers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jop8H9ei2rfG1VtM" /><figcaption>Photo by <a href="https://unsplash.com/@christianw?utm_source=medium&amp;utm_medium=referral">Christian Wiediger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>However, selecting a winner manually can be time-consuming and may raise questions about fairness.</p><h3>How to Pick a Random Winner from YouTube Comments for Free (Complete Guide)</h3><p>YouTube giveaways have become one of the most effective ways for creators, brands, and businesses to increase engagement, grow subscribers, and reward loyal viewers. Whether you’re running a small giveaway for 50 subscribers or a large contest with thousands of participants, choosing a winner fairly is crucial.</p><p>The biggest challenge? Manually scrolling through hundreds or thousands of comments to select a winner.</p><p>That’s where a YouTube Comment Picker comes in.</p><p>In this guide, you’ll learn how to randomly select a winner from YouTube comments for free, why using an automated tool is important, and how to simplify the entire process using the free tool available at:</p><p><a href="https://youtubecommentpickerthumbnaildownload.online/"><strong>https://youtubecommentpickerthumbnaildownload.online/</strong></a></p><h3>Why You Should Use a Random YouTube Comment Picker</h3><p>When you manually select giveaway winners, participants may question the fairness of the process.</p><p>A random comment picker solves this problem by:</p><ul><li>Selecting winners randomly</li><li>Eliminating human bias</li><li>Saving hours of manual work</li><li>Increasing trust and transparency</li><li>Supporting giveaways of any size</li><li>Making winner selection fast and professional</li></ul><p>Whether you’re a YouTuber, influencer, educator, business owner, or content creator, using a random comment picker helps ensure every participant gets an equal chance to win.</p><h3>Introducing YouTube Comment Picker &amp; Thumbnail Downloader</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NsuThyLZnzKCk-2D" /><figcaption>Photo by <a href="https://unsplash.com/@eyestetix_studio?utm_source=medium&amp;utm_medium=referral">Eyestetix Studio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The <a href="https://youtubecommentpickerthumbnaildownload.online/"><strong>YouTube Comment Picker</strong></a><strong> &amp; Thumbnail Downloader</strong> is a free online tool designed specifically for YouTube creators.</p><p>Website:</p><p><a href="https://youtubecommentpickerthumbnaildownload.online/"><strong>https://youtubecommentpickerthumbnaildownload.online/</strong></a></p><p>Unlike many tools that focus on a single feature, this platform combines multiple YouTube utilities into one easy-to-use website.</p><h3>Key Features</h3><h4>1. Random YouTube Comment Picker</h4><p>The primary feature allows users to:</p><ul><li>Fetch comments from YouTube videos</li><li>Select winners randomly</li><li>Run fair giveaway draws</li><li>Save time during contests</li><li>Conduct transparent winner selection</li></ul><p>This is especially useful for creators running:</p><ul><li>Subscriber giveaways</li><li>Product giveaways</li><li>Gift card contests</li><li>Community engagement campaigns</li><li>Promotional events</li></ul><h4>2. YouTube Thumbnail Downloader</h4><p>Another useful feature is the built-in thumbnail downloader.</p><p>With this tool, users can:</p><ul><li>Download YouTube video thumbnails</li><li>Access high-quality thumbnail versions</li><li>Save thumbnails for reference and inspiration</li><li>Analyze successful thumbnail designs</li></ul><h4>This feature is particularly helpful for:</h4><ul><li>Content creators</li><li>Digital marketers</li><li>SEO professionals</li><li>Graphic designers</li><li>YouTube channel managers</li></ul><h4>3. Simple User Interface</h4><p>One of the biggest advantages of the platform is its clean and beginner-friendly design.</p><p>Users do not need:</p><ul><li>Technical skills</li><li>Coding knowledge</li><li>Complex software installations</li><li>Browser extensions</li></ul><p>Simply visit the website, paste a YouTube URL, and start using the tool.</p><h4>4. Fast Processing</h4><p>The platform is designed for speed.</p><p>Instead of waiting several minutes for results, users can quickly:</p><ul><li>Enter a video URL</li><li>Load available comments</li><li>Pick a winner</li><li>Download thumbnails</li></ul><p>This makes the tool suitable for both casual creators and professional marketers.</p><h4>5. Completely Free to Use</h4><p>Many online giveaway tools limit features behind subscriptions or premium plans.</p><p>The YouTube Comment Picker &amp; Thumbnail Downloader provides its core functionality without requiring users to purchase expensive plans.</p><p>This makes it ideal for:</p><ul><li>New YouTubers</li><li>Small creators</li><li>Students</li><li>Freelancers</li><li>Startups</li></ul><h3>Step-by-Step Guide: How to Pick a Random Winner</h3><h3>Step 1: Open Your YouTube Video</h3><p>Navigate to the YouTube video containing your giveaway comments.</p><p>Copy the video’s URL.</p><p>Example:</p><p><a href="https://www.youtube.com/watch?v=VIDEO_ID">https://www.youtube.com/watch?v=VIDEO_ID</a></p><h3>Step 2: Visit the Tool</h3><p>Go to:</p><p><a href="https://youtubecommentpickerthumbnaildownload.online/"><strong>https://youtubecommentpickerthumbnaildownload.online/</strong></a></p><p>You will find an easy-to-use interface designed specifically for YouTube-related tasks.</p><h3>Step 3: Paste the Video Link</h3><p>Paste your YouTube video URL into the provided input field.</p><p>The system will process the video and prepare the comments for selection.</p><h3>Step 4: Load Comments</h3><p>Allow the tool to retrieve comments from the video.</p><p>Depending on the number of comments, this process may take only a few seconds.</p><h3>Step 5: Start the Random Draw</h3><p>Click the button to randomly select a winner.</p><p>The tool will automatically choose a comment from the eligible entries.</p><h3>Step 6: Verify the Winner</h3><p>Before announcing the winner:</p><ul><li>Check giveaway requirements</li><li>Confirm eligibility</li><li>Ensure the participant followed the rules</li></ul><p>Once verified, you can publicly announce the winner.</p><h3>Tips for Running Successful YouTube Giveaways</h3><h3>Clearly Explain Entry Requirements</h3><p>Specify exactly what users must do.</p><p>For example:</p><ul><li>Subscribe</li><li>Like the video</li><li>Leave a comment</li></ul><p>Clear rules reduce confusion and disputes.</p><h3>Set a Giveaway End Date</h3><p>Always mention:</p><ul><li>Start date</li><li>End date</li><li>Winner announcement date</li></ul><p>This helps participants understand the timeline.</p><h3>Keep the Selection Process Transparent</h3><p>Consider recording your screen while using the comment picker.</p><p>Showing the random selection process increases audience trust.</p><h3>Follow YouTube Policies</h3><p>Make sure your giveaway complies with YouTube’s official contest and giveaway guidelines.</p><p>Transparency and honesty are essential for maintaining credibility.</p><h3>Benefits for Content Creators</h3><p>Using a dedicated YouTube comment picker offers several advantages:</p><h3>Increased Trust</h3><p>Participants know the winner was selected fairly.</p><h3>Better Community Engagement</h3><p>Viewers are more likely to participate in future giveaways.</p><h3>Faster Workflow</h3><p>No more scrolling through hundreds of comments manually.</p><h3>Professional Appearance</h3><p>Your giveaways look organized and trustworthy.</p><h3>Improved Audience Retention</h3><p>Regular giveaways can encourage viewers to stay engaged with your channel.</p><h3>Who Can Use This Tool?</h3><p>The platform is useful for:</p><ul><li>YouTubers</li><li>Influencers</li><li>Affiliate marketers</li><li>Businesses</li><li>Agencies</li><li>Teachers</li><li>Coaches</li><li>Content creators</li><li>Social media managers</li></ul><p>Anyone managing YouTube giveaways can benefit from using it.</p><p>If you’re searching for a free and easy way to pick a random winner from YouTube comments, a dedicated comment picker is the most efficient solution.</p><p>The <strong>YouTube Comment Picker &amp; Thumbnail Downloader</strong> provides multiple useful features in a single platform, including random winner selection and YouTube thumbnail downloading.</p><p>Whether you’re running your first giveaway or managing a growing YouTube channel, this tool can help streamline the process while maintaining fairness and transparency.</p><p>Try it today:</p><p><a href="https://youtubecommentpickerthumbnaildownload.online/"><strong>https://youtubecommentpickerthumbnaildownload.online/</strong></a></p><p>Make your giveaways faster, fairer, and more professional.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=028722e758a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is JWT? How to Implement JWT Authentication in Spring Boot?]]></title>
            <link>https://articlesmedia.medium.com/what-is-jwt-aaf41c99a5cb?source=rss-526562577041------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaf41c99a5cb</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[json-web-token]]></category>
            <dc:creator><![CDATA[Articles Media]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 14:00:22 GMT</pubDate>
            <atom:updated>2026-06-03T14:13:17.681Z</atom:updated>
            <content:encoded><![CDATA[<p>JWT stands for JSON Web Token. Let’s learn more about it</p><p>Every modern application needs a secure authentication system.</p><p>Whether you’re building:</p><ul><li>E-commerce websites</li><li>Banking applications</li><li>Social media platforms</li><li>SaaS products</li></ul><p>you need a way to identify users and protect sensitive resources.</p><p>This is where JWT (JSON Web Token) comes in.</p><p>In this tutorial, you’ll learn how to implement JWT Authentication in Spring Boot from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOtSEbAJVIr0sus5CytUAQ.png" /></figure><p>JWT Authentication, It is a secure way of transmitting user information between a client and a server.</p><p>Instead of storing sessions on the server, JWT stores user identity inside a signed token.</p><h3>Why Use JWT?</h3><p>JWT offers several advantages:</p><ul><li>Stateless authentication</li><li>Better scalability</li><li>Suitable for REST APIs</li><li>Works well with mobile applications</li><li>Supports microservices architecture</li><li>Reduced server memory usage</li></ul><p>Because of these benefits, JWT has become the industry standard for API authentication.</p><h3>JWT Structure</h3><p>A JWT consists of three parts separated by dots:</p><pre>xxxxx.yyyyy.zzzzz</pre><h3>1. Header</h3><p>The header contains information about the token type and signing algorithm.</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><h3>2. Payload</h3><p>The payload contains user information known as claims.</p><pre>{<br>  &quot;sub&quot;: &quot;qay&quot;,<br>  &quot;role&quot;: &quot;USER&quot;<br>}</pre><h3>3. Signature</h3><p>The signature verifies that the token has not been tampered with.</p><h3>How JWT Authentication Works</h3><p>The authentication flow looks like this:</p><pre>User Login<br>     ↓<br>Spring Boot Validates Credentials<br>     ↓<br>JWT Token Generated<br>     ↓<br>Token Sent To Client<br>     ↓<br>Client Stores Token<br>     ↓<br>Client Sends Token With Requests<br>     ↓<br>Protected Resources Accessed</pre><p>Once the user is authenticated, every request includes the token.</p><p>The server validates the token before processing the request.</p><h3>Create a Spring Boot Project</h3><p>Go to Spring Initializr and create a project with the following dependencies:</p><ul><li>Spring Web</li><li>Spring Security</li><li>Spring Data JPA</li><li>MySQL Driver</li><li>Lombok</li><li>Validation</li></ul><p>Generate and download the project.</p><h3>Add JWT Dependencies</h3><p>Open your pom.xml file and add:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>    &lt;version&gt;0.12.5&lt;/version&gt;<br>&lt;/dependency&gt;<br><br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;<br>    &lt;version&gt;0.12.5&lt;/version&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;<br>    &lt;version&gt;0.12.5&lt;/version&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>These libraries help create and validate JWT tokens.</p><h3>Configure Database</h3><p>Add the following configuration to application.properties:</p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/jwtdb<br>spring.datasource.username=root<br>spring.datasource.password=password<br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.show-sql=true</pre><h3>Create User Entity</h3><p>Create a User class.</p><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>public class User {<br>@Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String username;<br>    private String password;<br>    private String role;<br>}</pre><p>This table stores registered users.</p><h3>Create Repository Layer</h3><pre>@Repository<br>public interface UserRepository<br>        extends JpaRepository&lt;User, Long&gt; {<br>Optional&lt;User&gt; findByUsername(String username);<br>}</pre><p>The repository provides database access methods.</p><h3>Create JWT Utility Class</h3><p>The JWT utility class is responsible for:</p><ul><li>Generating tokens</li><li>Validating tokens</li><li>Extracting user information</li></ul><pre>@Component<br>public class JwtUtil {<br>private final String SECRET_KEY =<br>            &quot;your-secret-key&quot;;<br>    public String generateToken(String username) {<br>        return Jwts.builder()<br>                .subject(username)<br>                .issuedAt(new Date())<br>                .expiration(<br>                    new Date(<br>                        System.currentTimeMillis()<br>                        + 86400000<br>                    )<br>                )<br>                .signWith(<br>                    Keys.hmacShaKeyFor(<br>                        SECRET_KEY.getBytes()<br>                    )<br>                )<br>                .compact();<br>    }<br>}</pre><p>This creates a JWT token that expires after 24 hours.</p><h3>Create Authentication Request DTO</h3><pre>public class AuthRequest {<br>private String username;<br>    private String password;<br>}</pre><p>The DTO receives login credentials from users.</p><h3>Create Authentication Controller</h3><pre>@RestController<br>@RequestMapping(&quot;/auth&quot;)<br>public class AuthController {<br><br>@Autowired<br>    private AuthenticationManager<br>            authenticationManager;<br>    @Autowired<br>    private JwtUtil jwtUtil;<br>    @PostMapping(&quot;/login&quot;)<br>    public String login(<br>            @RequestBody AuthRequest request) {<br>        authenticationManager.authenticate(<br>                new UsernamePasswordAuthenticationToken(<br>                        request.getUsername(),<br>                        request.getPassword()<br>                )<br>        );<br>        return jwtUtil.generateToken(<br>                request.getUsername()<br>        );<br>    }<br>}</pre><p>This endpoint authenticates users and generates a JWT token.</p><h3>Configure Spring Security</h3><p>Create a Security Configuration class.</p><pre>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfig {<br>@Bean<br>    public SecurityFilterChain securityFilterChain(<br>            HttpSecurity http)<br>            throws Exception {<br>        return http<br>                .csrf(csrf -&gt; csrf.disable())<br>                .authorizeHttpRequests(auth -&gt;<br>                        auth<br>                                .requestMatchers(<br>                                        &quot;/auth/**&quot;)<br>                                .permitAll()<br>                                .anyRequest()<br>                                .authenticated()<br>                )<br>                .build();<br>    }<br>}</pre><p>This allows authentication endpoints while protecting all other APIs.</p><h3>Test Login Endpoint</h3><p>Use Postman.</p><h3>Request</h3><pre>POST /auth/login</pre><pre>{<br>  &quot;username&quot;:&quot;qayyum&quot;,<br>  &quot;password&quot;:&quot;password&quot;<br>}</pre><h3>Response</h3><pre>{<br>  &quot;token&quot;:&quot;eyJhbGciOiJIUzI1NiJ9...&quot;<br>}</pre><p>The returned token must be stored by the client.</p><h3>Access Protected APIs</h3><p>Include the token in request headers:</p><pre>Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...</pre><p>Spring Security validates the token before granting access.</p><h3>Common JWT Errors</h3><h3>401 Unauthorized</h3><p>Occurs when:</p><ul><li>Token is missing</li><li>Token is invalid</li><li>User is not authenticated</li></ul><h3>Expired Token</h3><p>Occurs when:</p><ul><li>Token validity period has ended</li></ul><p>Solution:</p><p>Generate a new token.</p><h3>Invalid Signature</h3><p>Occurs when:</p><ul><li>Secret key differs from the one used to generate the token</li></ul><h3>JWT Best Practices</h3><p>When implementing JWT in production:</p><ul><li>Always use HTTPS</li><li>Store secret keys securely</li><li>Set token expiration times</li><li>Use refresh tokens</li><li>Encrypt sensitive information</li><li>Never expose secret keys in source code</li></ul><p>Following these practices significantly improves application security.</p><p>JWT Authentication is one of the most widely used authentication mechanisms in modern software development. It provides a secure, scalable, and efficient way to protect APIs and authenticate users.</p><p>In this tutorial, you learned:</p><ul><li>What JWT is</li><li>How JWT works</li><li>How to configure Spring Security</li><li>How to generate tokens</li><li>How to validate users</li><li>How to secure REST APIs</li></ul><p>By implementing JWT Authentication in Spring Boot, you can build secure applications that are ready for real-world deployment.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaf41c99a5cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Connect MongoDB to Spring Boot?]]></title>
            <link>https://medium.com/illumination/how-to-connect-mongodb-to-spring-boot-b8df407f12ca?source=rss-526562577041------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8df407f12ca</guid>
            <category><![CDATA[nosql-database]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Articles Media]]></dc:creator>
            <pubDate>Sun, 31 May 2026 19:32:09 GMT</pubDate>
            <atom:updated>2026-05-31T19:32:09.850Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications often require flexible databases that can handle large volumes of unstructured data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iq43p50okEvB4hnAoOIzoQ.png" /><figcaption><strong><em>Connect MongoDB to Spring Boot</em></strong></figcaption></figure><p>MongoDB is one of the most popular NoSQL databases used by developers worldwide. When combined with Spring Boot, it becomes incredibly easy to build scalable and high-performance applications.</p><p>In this guide, you’ll learn how to connect MongoDB to a Spring Boot application from scratch. By the end of this tutorial, you’ll be able to store and retrieve data from MongoDB using Spring Boot.<br>What is MongoDB?</p><p>MongoDB is a NoSQL database that stores data in JSON-like documents instead of traditional tables and rows.</p><h3>Key Features of MongoDB</h3><ul><li>Document-oriented storage</li><li>Flexible schema design</li><li>High scalability</li><li>Fast performance</li><li>Easy integration with Java applications</li></ul><h3>Example MongoDB Document</h3><pre>{<br>  &quot;_id&quot;: &quot;1&quot;,<br>  &quot;name&quot;: &quot;Qay&quot;,<br>  &quot;email&quot;: &quot;qay@example.com&quot;,<br>  &quot;city&quot;: &quot;Chennai&quot;<br>}</pre><p>Unlike MySQL, you don’t need to define a fixed table structure before storing data.</p><h3>Prerequisites</h3><p>Before starting, make sure you have:</p><ul><li>Java 17 or later</li><li>MongoDB installed</li><li>IntelliJ IDEA or Eclipse</li><li>Maven</li><li>Spring Boot</li></ul><h3>Step 1: Install MongoDB</h3><p>Download MongoDB Community Server from the official MongoDB website.</p><p>After installation, verify it is running.</p><p>Open Command Prompt:</p><pre>mongod --version</pre><p>You should see version information if MongoDB is installed correctly.</p><h3>Step 2: Create a Spring Boot Project</h3><p>Visit Spring Initializr and create a project with:</p><h3>Project Metadata</h3><ul><li>Project: Maven</li><li>Language: Java</li><li>Spring Boot: Latest Stable Version</li></ul><h3>Dependencies</h3><ul><li>Spring Web</li><li>Spring Data MongoDB</li><li>Lombok (Optional)</li></ul><p>Generate and extract the project.</p><h3>Step 3: Configure MongoDB Connection</h3><p>Open:</p><pre>src/main/resources/application.properties</pre><p>Add:</p><pre>spring.application.name=mongodb-demo<br>spring.data.mongodb.uri=mongodb://localhost:27017/studentdb</pre><h3>Explanation</h3><ul><li>localhost → MongoDB server location</li><li>27017 → Default MongoDB port</li><li>studentdb → Database name</li></ul><p>Spring Boot automatically creates the database if it doesn’t exist.</p><h3>Step 4: Create a MongoDB Document Class</h3><p>Create:</p><pre>package com.example.demo.model;<br><br>import org.springframework.data.annotation.Id;<br>import org.springframework.data.mongodb.core.mapping.Document;<br>@Document(collection = &quot;students&quot;)<br>public class Student {<br>    @Id<br>    private String id;<br>    private String name;<br>    private String email;<br>    public Student() {<br>    }<br>    public Student(String id, String name, String email) {<br>        this.id = id;<br>        this.name = name;<br>        this.email = email;<br>    }<br>    public String getId() {<br>        return id;<br>    }<br>    public void setId(String id) {<br>        this.id = id;<br>    }<br>    public String getName() {<br>        return name;<br>    }<br>    public void setName(String name) {<br>        this.name = name;<br>    }<br>    public String getEmail() {<br>        return email;<br>    }<br>    public void setEmail(String email) {<br>        this.email = email;<br>    }<br>}</pre><h3>What Does @Document Do?</h3><pre>@Document(collection = &quot;students&quot;)</pre><p>This annotation tells Spring Boot to store documents inside the “students” collection.</p><h3>Step 5: Create Repository Layer</h3><p>Create:</p><pre>package com.example.demo.repository;<br><br>import org.springframework.data.mongodb.repository.MongoRepository;<br>import com.example.demo.model.Student;<br>public interface StudentRepository<br>        extends MongoRepository&lt;Student, String&gt; {<br>}</pre><h3>Benefits</h3><p>MongoRepository automatically provides:</p><ul><li>save()</li><li>findAll()</li><li>findById()</li><li>deleteById()</li></ul><p>No SQL queries required.</p><h3>Step 6: Create REST Controller</h3><p>Create:</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.web.bind.annotation.*;<br>import com.example.demo.model.Student;<br>import com.example.demo.repository.StudentRepository;<br>@RestController<br>@RequestMapping(&quot;/students&quot;)<br>public class StudentController {<br>    @Autowired<br>    private StudentRepository repository;<br>    @PostMapping<br>    public Student addStudent(@RequestBody Student student) {<br>        return repository.save(student);<br>    }<br>    @GetMapping<br>    public List&lt;Student&gt; getStudents() {<br>        return repository.findAll();<br>    }<br>}</pre><h3>Step 7: Run the Application</h3><p>Run:</p><pre>mvn spring-boot:run</pre><p>You should see:</p><pre>Started DemoApplication</pre><p>This indicates Spring Boot has connected successfully to MongoDB.</p><h3>Step 8: Test Using Postman</h3><h3>Add Student</h3><p>POST</p><pre>http://localhost:8080/students</pre><p>Request Body:</p><pre>{<br>  &quot;name&quot;: &quot;Qayyum&quot;,<br>  &quot;email&quot;: &quot;qayyum@example.com&quot;<br>}</pre><p>Expected Response:</p><pre>{<br>  &quot;id&quot;: &quot;6842abc123&quot;,<br>  &quot;name&quot;: &quot;Qayyum&quot;,<br>  &quot;email&quot;: &quot;qayyum@example.com&quot;<br>}</pre><h3>Retrieve Students</h3><p>GET</p><pre>http://localhost:8080/students</pre><p>Response:</p><pre>[<br>  {<br>    &quot;id&quot;: &quot;6842abc123&quot;,<br>    &quot;name&quot;: &quot;Qayyum&quot;,<br>    &quot;email&quot;: &quot;qayyum@example.com&quot;<br>  }<br>]</pre><h3>Verify Data in MongoDB</h3><p>Open Mongo Shell:</p><pre>mongosh</pre><p>Switch database:</p><pre>use studentdb</pre><p>View documents:</p><pre>db.students.find()</pre><p>Output:</p><pre>{<br>  &quot;_id&quot;: ObjectId(&quot;6842abc123&quot;),<br>  &quot;name&quot;: &quot;Qay&quot;,<br>  &quot;email&quot;: &quot;qay@example.com&quot;<br>}</pre><h3>Common Errors and Solutions</h3><h3>Error 1: Connection Refused</h3><pre>MongoTimeoutException</pre><p>Solution:</p><p>Make sure MongoDB service is running.</p><h3>Error 2: Wrong Port Number</h3><p>Check:</p><pre>spring.data.mongodb.uri=mongodb://localhost:27017/studentdb</pre><p>Ensure MongoDB is listening on port 27017.</p><h3>Error 3: Missing Dependency</h3><p>Make sure your pom.xml contains:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-data-mongodb&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8df407f12ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illumination/how-to-connect-mongodb-to-spring-boot-b8df407f12ca">How to Connect MongoDB to Spring Boot?</a> was originally published in <a href="https://medium.com/illumination">ILLUMINATION</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A JWT Token Example]]></title>
            <link>https://articlesmedia.medium.com/a-jwt-token-example-8a6fd28f2a49?source=rss-526562577041------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a6fd28f2a49</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[json-web-token]]></category>
            <category><![CDATA[jwt-example]]></category>
            <dc:creator><![CDATA[Articles Media]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 18:17:56 GMT</pubDate>
            <atom:updated>2025-12-19T18:17:56.409Z</atom:updated>
            <content:encoded><![CDATA[<p>A JWT (JSON Web Token) is a string with three parts separated by dots (.).</p><p>A common example of a full, encoded JWT is:<br>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNzA4MzQ1MTIzLCJleHAiOjE3MDgzNTUxMjN9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</p><p>Breaking Down the JWT</p><p>The token consists of three Base64url-encoded parts: the Header, the Payload, and the Signature. You can decode and verify tokens using online tools like <a href="https://jwt.io/">jwt.io</a>.</p><p><strong>1. Header</strong></p><p>The header is a JSON object that specifies the token type and the signing algorithm used (e.g., HMAC SHA256).</p><p><strong>Example Header (decoded JSON):</strong></p><p>json</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><ul><li>lg: The algorithm used for the signature.</li><li>typ: The type of token (JWT).</li></ul><p><strong>2. Payload (Claims)</strong></p><p>The payload contains “claims” — statements about an entity (typically the user) and additional data.</p><p><strong>Example Payload (decoded JSON):</strong></p><p>json</p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;iat&quot;: 1708345123,<br>  &quot;exp&quot;: 1708355123<br>}</pre><ul><li>sub (subject): A unique identifier for the user.</li><li>name: The user&#39;s name (a public claim).</li><li>iat (issued at): The time the token was issued (a registered claim).</li><li>exp (expiration time): The time after which the token is invalid.</li></ul><p><strong>3. Signature</strong></p><p>The signature is used to verify that the sender is who they say they are and that the token hasn’t been tampered with. It is created by combining the encoded header, the encoded payload, and a secret key known only to the server.</p><p><strong>Signature Formula (conceptual):</strong><br>HMACSHA256( base64UrlEncode(header) + &quot;.&quot; + base64UrlEncode(payload), secret)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a6fd28f2a49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Connect MySQL to Spring Boot?]]></title>
            <link>https://articlesmedia.medium.com/how-to-connect-mysql-to-spring-boot-48c2bd0b4783?source=rss-526562577041------2</link>
            <guid isPermaLink="false">https://medium.com/p/48c2bd0b4783</guid>
            <category><![CDATA[spring-mysql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Articles Media]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 04:40:59 GMT</pubDate>
            <atom:updated>2025-12-01T04:40:59.919Z</atom:updated>
            <content:encoded><![CDATA[<p>A detailed, practical, and simplified guide for developers who want a clear understanding of MySQL–Spring Boot integration.</p><h4>📌 Source : <a href="https://value2read.blogspot.com/2025/11/how-to-connect-mysql-to-spring-boot.html">https://value2read.blogspot.com/2025/11/how-to-connect-mysql-to-spring-boot.html</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgg-fh99G9d64oM3iTJxYw.png" /></figure><p>The design adheres to the fundamental principle of <strong>Separation of Concerns (SoC)</strong> by dividing the application into distinct layers, each with a specific responsibility.</p><ul><li><strong>Request Flow </strong>→<strong> Spring Boot Application:</strong> The request enters the application container.</li><li><strong>Controller</strong>→ <strong>Service:</strong> The <strong>Controller</strong> handles the web aspect (HTTP, routing, request/response formats) and immediately delegates the core task to the <strong>Service</strong> layer. This keeps the Controller “light.”</li><li><strong>Service </strong>→<strong> Repository:</strong> The <strong>Service</strong> layer contains the actual <strong>business logic</strong>. It determines <em>what</em> needs to be done and then tells the <strong>Repository</strong> layer <em>how</em> to save or retrieve the data.</li><li><strong>Repository </strong>→<strong> JPA </strong>→<strong> MySQL Database:</strong> The <strong>Repository</strong> layer, often implemented using <strong>JPA (Java Persistence API)</strong> via Spring Data, acts as the data access bridge. It manages the persistence details (like SQL commands) and maps application objects to the <strong>Database</strong> tables.</li></ul><p>Connecting MySQL to a Spring Boot application is one of the most essential skills for any backend or full-stack developer. Whether you’re building a simple CRUD application, a large enterprise project, or a microservice, your app will need a robust and reliable relational database — MySQL fits perfectly for that role.</p><p>Many beginners get confused with configuration errors, driver issues, JDBC URL formatting, or entity mapping problems. This guide aims to eliminate those confusions.</p><p>Below is a <strong>clear, structured, deeply explained</strong> guide that walks you from installation → configuration → coding → testing → troubleshooting.</p><h3>1. Understanding Why Spring Boot and MySQL Are Commonly Used Together</h3><p>Before jumping into setup, it’s important to understand <em>why</em> these two technologies complement each other so well:</p><h3>Spring Boot advantages:</h3><ul><li>Auto-configuration reduces boilerplate code.</li><li>Built-in support for Spring Data JPA.</li><li>Simplifies dependency handling.</li><li>Production-ready features (metrics, health checks).</li><li>Highly scalable for enterprise applications.</li></ul><h3>MySQL advantages:</h3><ul><li>Lightweight, fast, and free.</li><li>Stores structured relational data.</li><li>Supports indexing, ACID compliance, and transactions.</li><li>Works seamlessly with Hibernate ORM.</li></ul><p>Together, Spring Boot + MySQL provide a <strong>clean architecture, high productivity, and strong performance</strong>, making them one of the most popular backend stacks worldwide.</p><h3>2. Prerequisites You Must Have Before Starting</h3><p>Make sure you have:</p><p>✔ <strong>Java 17+</strong><br> ✔ <strong>Maven</strong><br> ✔ <strong>Spring Boot (recommended: 3.x)</strong><br> ✔ <strong>MySQL Server installed</strong><br> ✔ A database tool like MySQL Workbench / DBeaver<br> ✔ An IDE like IntelliJ IDEA / Eclipse / VS Code</p><p>If you are missing any, install them before continuing.</p><h3>3. Creating the Spring Boot Project (Step-by-Step)</h3><h3>Option 1: Using Spring Initializr</h3><p>Go to <a href="https://start.spring.io/"><strong>https://start.spring.io</strong></a></p><p>Choose:</p><p><strong>Project:</strong> Maven</p><p><strong>Language:</strong> Java</p><p><strong>Spring Boot Version:</strong> 3.x</p><p><strong>Dependencies:</strong></p><p>Spring Web</p><p>Spring Data JPA</p><p>MySQL Driver</p><p>Click <strong>Generate</strong>, then extract and import into IntelliJ/Eclipse.</p><h3>Option 2: Using IDE (IntelliJ Ultimate)</h3><p>File → New → Project → Spring Initializr.</p><h3>4. Adding Dependencies (pom.xml Explained Clearly)</h3><p>Even if you used Initializr, it’s important to understand what each dependency does.</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;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.mysql&lt;/groupId&gt;<br>    &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><h3>What they do:</h3><p><strong>Spring Web</strong> → Allows you to create REST APIs<br> <strong>Spring Data JPA</strong> → Handles database operations without writing SQL<br> <strong>MySQL Connector-J</strong> → Lets Java communicate with MySQL through JDBC</p><h3>5. Creating the Database in MySQL</h3><p>Open MySQL Workbench or CLI:</p><pre>CREATE DATABASE springbootdb;</pre><p>Use any name you like.</p><h3>6. Configuring Spring Boot to Connect With MySQL</h3><p>This is the <strong>heart</strong> of database connectivity.</p><p>Go to:<br> src/main/resources/application.properties</p><p>Add:</p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb<br>spring.datasource.username=root<br>spring.datasource.password=yourpassword<br>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.show-sql=true<br>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect</pre><h3>Breaking it down:</h3><p><strong>spring.datasource.url</strong><br> Defines the MySQL server address + port + DB name.</p><p><strong>spring.jpa.hibernate.ddl-auto=update</strong><br> Automatically creates/updates tables.</p><p>ValueMeaningcreateDrops &amp; recreates tables every timeupdateSafely updates schema without deletingvalidateEnsures schema matches but doesn’t modifynoneNo action</p><p><strong>spring.jpa.show-sql=true</strong><br> Prints SQL queries in console.</p><h3>7. Creating an Entity (Model Class)</h3><p>We create a table through an entity.</p><pre>import jakarta.persistence.*;<br>@Entity<br>public class User {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String name;<br>    private String email;<br>    // getters and setters<br>}</pre><h3>What happens when you run the project?</h3><p>Spring Boot + Hibernate → Creates a table named user automatically.</p><h3>8. Creating a Repository (Database Interface)</h3><p>With Spring Data JPA, you never write SQL.</p><pre>import org.springframework.data.jpa.repository.JpaRepository;<br><br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>}</pre><p>This interface gives you ready-made methods:</p><ul><li>save()</li><li>findAll()</li><li>findById()</li><li>deleteById()</li></ul><h3>9. Creating a Controller to Test the MySQL Connection</h3><pre>import org.springframework.web.bind.annotation.*;<br>import java.util.List;<br><br>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br>    private final UserRepository repository;<br>    public UserController(UserRepository repository) {<br>        this.repository = repository;<br>    }<br>    @PostMapping<br>    public User createUser(@RequestBody User user){<br>        return repository.save(user);<br>    }<br>    @GetMapping<br>    public List&lt;User&gt; getAllUsers(){<br>        return repository.findAll();<br>    }<br>}</pre><h3>10. Running and Testing the Application</h3><p>Run the application:</p><pre>mvn spring-boot:run</pre><p>OR click the <strong>Run</strong> button in your IDE.</p><h3>Test using Postman:</h3><p><strong>POST</strong> → <a href="http://localhost:8080/users">http://localhost:8080/users</a><br> Body:</p><pre>{<br>  &quot;name&quot;: &quot;John&quot;,<br>  &quot;email&quot;: &quot;john@gmail.com&quot;<br>}</pre><p><strong>GET</strong> → <a href="http://localhost:8080/users">http://localhost:8080/users</a></p><p>If you see results → MySQL is connected successfully.</p><h3>11. Common Errors and Their Exact Fixes</h3><h3>❌ 1. Communications link failure</h3><p>✔ MySQL server is not running.<br> Start MySQL service:</p><pre>sudo service mysql start</pre><h3>❌ 2. Access denied for user ‘root’</h3><p>Password wrong or permissions missing.</p><p>Fix:</p><pre>ALTER USER &#39;root&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;newpassword&#39;;</pre><h3>❌ 3. Public Key Retrieval Not Allowed</h3><p>Add:</p><pre>?allowPublicKeyRetrieval=true&amp;useSSL=false</pre><p>Final URL:</p><pre>jdbc:mysql://localhost:3306/springbootdb?allowPublicKeyRetrieval=true&amp;useSSL=false</pre><h3>❌ 4. Unknown database error</h3><p>Meaning: Database not created.</p><p>Run:</p><pre>CREATE DATABASE springbootdb;</pre><h3>12. Best Practices for Production</h3><p>✔ Use <strong>environment variables</strong> for DB passwords<br> ✔ Set ddl-auto=none in production<br> ✔ Use connection pool (HikariCP - default)<br> ✔ Use migration tools like <strong>Flyway</strong> or <strong>Liquibase</strong><br> ✔ Never expose database port publicly<br> ✔ Always use <strong>MySQL8Dialect</strong> for efficient SQL generation</p><h3>13. Final Summary</h3><p>To connect Spring Boot to MySQL:</p><ol><li>Install MySQL</li><li>Create DB</li><li>Add dependencies</li><li>Configure application.properties</li><li>Create entity + repository</li><li>Run API</li><li>Test with Postman</li><li>Fix common issues if needed</li></ol><p>Spring Boot + MySQL = Clean, powerful, scalable backend stack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48c2bd0b4783" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Affect vs Effect: What’s the Difference and When to Use Them?]]></title>
            <link>https://articlesmedia.medium.com/affect-vs-effect-whats-the-difference-and-when-to-use-them-34778383fae5?source=rss-526562577041------2</link>
            <guid isPermaLink="false">https://medium.com/p/34778383fae5</guid>
            <category><![CDATA[affect-vs-effect]]></category>
            <category><![CDATA[writing-tips]]></category>
            <category><![CDATA[grammar-guide]]></category>
            <category><![CDATA[english-grammar]]></category>
            <category><![CDATA[vocabulary]]></category>
            <dc:creator><![CDATA[Articles Media]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 18:17:06 GMT</pubDate>
            <atom:updated>2025-11-29T18:17:06.408Z</atom:updated>
            <content:encoded><![CDATA[<p>Confused between “affect” and “effect”? This simple, practical guide breaks down the difference with clear explanations, examples, and memory tricks so you never mix them up again.</p><h4>Source : <a href="https://value2read.blogspot.com/2025/11/affect-vs-effect-whats-difference-and.html">https://value2read.blogspot.com/2025/11/affect-vs-effect-whats-difference-and.html</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxgIw1muyKBV-qkCjjPw7Q.png" /><figcaption>Affect vs Effect</figcaption></figure><p>English is full of tricky word pairs, and <em>affect vs effect</em> is one of the most commonly misunderstood combinations. These two words look almost identical, they sound incredibly similar, and they deal with the idea of change — which makes the confusion even stronger.<br> But the good news? Once you understand the core difference, the rest becomes surprisingly simple.</p><p>In this article, we will explore both words in detail, look at real-world examples, break down common mistakes, and use easy memory techniques to help you choose the correct word every single time.</p><h3>The Core Difference You Must Know</h3><p>If you take away just one rule from this article, let it be this:</p><ul><li><strong>Affect</strong> is <em>usually a verb</em> → it means <strong>to influence</strong> something.</li><li><strong>Effect</strong> is <em>usually a noun</em> → it refers to <strong>the result</strong> of something.</li></ul><p>Think of it like this:<br> <strong>Affect</strong> is the <em>cause</em>, and <strong>Effect</strong> is the <em>result</em>.<br> Or even simpler:<br> <strong>Affect is the action. Effect is the outcome.</strong></p><p>This distinction alone will solve 95% of your confusion.</p><h3>Understanding “Affect” in Detail</h3><p><strong>Affect</strong> is all about <strong>action</strong> — something is impacting, influencing, changing, or altering something else. It’s active, dynamic, and verbal.</p><h3>✦ Clear examples of “Affect”:</h3><ul><li><em>The weather can affect your travel plans.</em><br> → Weather influences what you do.</li><li><em>Lack of sleep affects your thinking ability.</em><br> → Sleep (or lack of it) changes how your brain performs.</li><li><em>Stress affects your productivity at work.</em><br> → Stress impacts how well you perform tasks.</li></ul><p>In all these examples, <strong>affect</strong> shows an action that changes something else.</p><h3>✦ When SHOULD you use “Affect”?</h3><p>Use <strong>affect</strong> when:</p><ul><li>something is being <em>influenced or changed</em></li><li>you can rewrite the sentence using <em>impact</em>, <em>alter</em>, or <em>influence</em></li></ul><p>Example rewrite test:</p><ul><li><em>The news affected him deeply.</em><br> ➝ <em>The news influenced him deeply.</em> (✓ Perfect substitution)</li></ul><p>If you can replace it with <strong>influence</strong>, then <strong>affect</strong> is the right choice.</p><h3>Understanding “Effect” in Detail</h3><p><strong>Effect</strong> shifts the focus to <strong>results</strong>. It’s not about the action itself, but what happens because of that action.</p><h3>✦ Clear examples of “Effect”:</h3><ul><li><em>The effect of pollution is visible in major cities.</em><br> → Pollution leads to visible consequences.</li><li><em>The medicine had no side effects.</em><br> → No results or reactions occurred.</li><li><em>The new schedule had a positive effect on productivity.</em><br> → The outcome of the new schedule was good.</li></ul><p>In every one of these examples, <strong>effect</strong> talks about an end state — the result of something that happened earlier.</p><h3>✦ When SHOULD you use “Effect”?</h3><p>Use <strong>effect</strong> when:</p><ul><li>you want to talk about an <em>outcome</em></li><li>the sentence describes what happened <em>after</em> an action</li><li>you could replace the word with <em>result</em>, <em>outcome</em>, or <em>consequence</em></li></ul><p>Example rewrite:</p><ul><li><em>The new law had an effect on traffic.</em><br> ➝ <em>The new law had a result on traffic.</em> (✓ Works perfectly)</li></ul><h3>A Beautifully Simple Memory Trick</h3><p>Remember this:</p><h3>A before E → Action before End Result</h3><ul><li><strong>Affect</strong> starts with A → Action</li><li><strong>Effect</strong> starts with E → End result</li></ul><p>The order of letters in the alphabet actually mirrors the sequence of events in real life:<br> First something happens (<strong>affect</strong>), then the result appears (<strong>effect</strong>).</p><h3>Common Mistakes (and How to Fix Them Easily)</h3><p>Because these words look and sound similar, people often swap them. Here are the typical mistakes you should avoid:</p><h3>❌ The weather effects my plans.</h3><p>✔️ Correct: <em>The weather affects my plans.</em><br> Why? Because weather <strong>influences</strong> (action), not results.</p><h3>❌ The training had a great affect on my performance.</h3><p>✔️ Correct: <em>The training had a great effect on my performance.</em><br> Why? You’re talking about the <strong>result</strong> of the training, not the action.</p><h3>❌ Will this decision effect our work?</h3><p>✔️ Correct: <em>Will this decision affect our work?</em><br> Why? The decision will <strong>influence</strong> the work.</p><h3>Rare but Important: “Effect” as a Verb</h3><p>Even native speakers rarely use <strong>effect</strong> as a verb, but it does exist.<br> When used this way, it means <strong>to bring something into existence</strong> or <strong>to cause something new to happen</strong>.</p><p>Examples:</p><ul><li><em>The new manager hopes to effect major changes.</em><br> → Meaning: to create or bring about changes.</li><li><em>The government aims to effect reform.</em><br> → Meaning: to make reform happen.</li></ul><p>This usage is more formal and is mostly found in academic, legal, or corporate writing.<br>For everyday writing, you almost never need this version — but it’s good to know it exists.</p><h3>Practice Questions to Test Yourself</h3><p>Try to answer these before checking the solutions:</p><ol><li>Social media can ___ your mood.</li><li>The main ___ of global warming is rising temperatures.</li><li>Her speech really ___ the audience.</li><li>The new system had a noticeable ___ on efficiency.</li><li>Stress can ___ your sleep cycle.</li></ol><h3>✔️ Answers:</h3><ol><li>affect</li><li>effect</li><li>affected</li><li>effect</li><li>affect</li></ol><p>If you got them all right, you’ve mastered the concept!</p><h3>Bringing It All Together</h3><p>The <em>affect vs effect</em> confusion is common, but the solution is incredibly simple once you remember the two key roles:</p><ul><li><strong>Affect</strong> = verb (an action)</li><li><strong>Effect</strong> = noun (a result)</li></ul><p>And the memory trick:</p><p>▶️ <strong>A comes before E — Actions come before End results.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34778383fae5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build Your First AI-Powered Java Application? — Spring AI Full Beginner Guide]]></title>
            <link>https://articlesmedia.medium.com/how-to-build-your-first-ai-powered-java-application-spring-ai-full-beginner-guide-80120b96c1ef?source=rss-526562577041------2</link>
            <guid isPermaLink="false">https://medium.com/p/80120b96c1ef</guid>
            <category><![CDATA[openai-java-example]]></category>
            <category><![CDATA[java-ai-integration]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[spring-ai-tutorial]]></category>
            <dc:creator><![CDATA[Articles Media]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 17:13:28 GMT</pubDate>
            <atom:updated>2025-11-29T17:13:28.149Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build Your First AI-Powered Java Application? — Spring AI Full Beginner Guide</h3><p>Spring AI makes it insanely easy to connect Java with OpenAI, Hugging Face, and more — no messy APIs, just clean Spring magic. In this guide, you’ll build your first AI-driven Java application in minutes. Let’s code the future!</p><h4>📌 Source : <a href="https://value2read.blogspot.com/2025/11/how-to-build-your-first-ai-powered-java.html">https://value2read.blogspot.com/2025/11/how-to-build-your-first-ai-powered-java.html</a> 📌</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D303ON1uAfCnQkbY5_3-BA.png" /><figcaption>AI-Powered Java Application — Spring AI Full Beginner Guide</figcaption></figure><p>Welcome to the world of <strong>Spring AI</strong>! In 2025, generative AI (LLMs like GPT-4/5) is everywhere — writing code, answering questions, and more. Java developers naturally ask: <em>“How do I bring this power into my Spring Boot apps?”</em> The answer is <strong>Spring AI</strong>, a new Spring-native framework that makes integrating AI models as easy as plugging in Spring Data or Spring Security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaZmrDQTOGrZisGIxXwjfA.png" /></figure><p>Instead of hand-coding HTTP calls and JSON parsing, Spring AI provides a <strong>common abstraction layer</strong> for chat, embeddings, and other AI tasks, letting you swap providers (OpenAI, Hugging Face, Azure, etc.) with just a config change. In this guide, we’ll build a simple Spring Boot service powered by OpenAI (chat model), covering setup, configuration, controllers, prompt templates, response handling, logging, testing, and even switching to Hugging Face as a bonus.</p><p>Spring AI applies Spring patterns to AI. Think of it like Spring Data JPA — you write to a standard interface and Spring talks to the right backend. You’ll inject a ChatClient and call it, and Spring AI handles the rest. This means <strong>no more hardcoding API URLs or reinventing wheels</strong> for each provider. By the end, you’ll have a Spring Boot “AI app” that can chat with GPT or other models with minimal code.</p><blockquote><strong><em>Tip:</em></strong><em> Use modern Java (e.g. Java 21+) and Spring Boot 3.2+ to be compatible with Spring AI. Set up your project with Spring Initializr: include </em><strong><em>Web</em></strong><em> and </em><strong><em>AI model</em></strong><em> starters (e.g. OpenAI). You can also add Spring Boot Actuator later for observability.</em></blockquote><h3>What is Spring AI and Why It Matters in 2025</h3><p><strong>Spring AI</strong> is a <strong>Spring team project</strong> for <strong>AI integration</strong>. It was inspired by Python libraries like <strong>LangChain</strong>, but built from the ground up for <strong>Java/Spring</strong>. Its goal is to make adding <strong>AI features</strong> to your Spring apps streamlined and familiar, without unnecessary complexity. Instead of writing raw HTTP calls to <strong>OpenAI</strong> or <strong>Hugging Face</strong> endpoints, you use <strong>Spring beans</strong> (like a <strong>ChatClient</strong>). Spring AI then handles <strong>authentication</strong>, <strong>requests</strong>, <strong>retries</strong>, etc., under the hood.</p><p>Why does this matter now? By <strong>2025</strong>, <strong>AI is part of every tech stack</strong>. Enterprises want to add <strong>chatbots</strong>, <strong>summaries</strong>, <strong>code generation</strong>, etc., to their <strong>Java backend</strong>. <strong>Spring AI</strong> lets you do that <strong>“the Spring way”</strong>. You can switch from <strong>OpenAI</strong> to a <strong>local model</strong> or another <strong>cloud service</strong> just by changing dependencies and config — <strong>no code rewrite</strong>. In short, Spring AI brings the power of <strong>LLMs</strong> into the familiar <strong>Spring ecosystem</strong>, so <strong>Java developers aren’t left behind in the AI revolution</strong>.</p><h3>Setting Up the Spring Boot Project</h3><p>First, create a new Spring Boot project (e.g. via Spring Initializr). Choose <strong>Java 21+</strong> and <strong>Spring Boot 3.2+</strong>, and add the <strong>Web</strong> dependency. Then add the Spring AI starters for your AI model. For OpenAI, add the <em>Spring AI Boot</em> and <em>OpenAI model</em> starters. In Maven pom.xml it looks like this</p><pre>&lt;dependencies&gt;<br> &lt;! - Spring AI core starter →<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-ai-boot-starter&lt;/artifactId&gt;<br> &lt;/dependency&gt;<br> &lt;! - Spring AI OpenAI model starter →<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-ai-openai-starter&lt;/artifactId&gt;<br> &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>(Newer <strong>Spring AI versions</strong> may use artifact names like <strong>spring-ai-openai-spring-boot-starter</strong> — check <strong>Spring AI docs</strong> for the latest.) If you use <strong>Gradle</strong>, similarly include <strong>spring-ai-boot-starter</strong> and <strong>spring-ai-openai-starter</strong>. These starters bring in everything needed to call <strong>OpenAI’s Chat API</strong> without additional SDKs.</p><p>Tip: Consider importing the Spring AI Bill of Materials (BOM) for version consistency. For example, use &lt;artifactId&gt;spring-ai-bom&lt;/artifactId&gt; with &lt;type&gt;pom&lt;/type&gt; to pin matching versions. This ensures all Spring AI modules stay in sync.</p><p>Next, add any other dependencies your app needs (e.g. Spring Web MVC). Your project is now ready for AI integration.</p><h3>Configuring the OpenAI API Key</h3><p>Spring AI reads model credentials and settings from Spring properties. Create an application.properties (or .yml) in src/main/resources. At minimum, set your OpenAI API key. <strong>Do not hardcode the key</strong> – use an environment variable or secure config. For example, in application.properties</p><pre># OpenAI API credentials and model configuration<br>spring.ai.openai.api-key=${OPENAI_API_KEY}<br>spring.ai.openai.chat.model=gpt-4<br>spring.ai.openai.chat.temperature=0.7</pre><p>Here we use ${OPENAI_API_KEY} to load the key from an environment variable (set export OPENAI_API_KEY=your_key in your OS). Spring AI will use the specified model (e.g. gpt-4) and temperature. You can omit the model if you want the default.</p><p><strong>Tip:</strong> Store secrets securely. E.g. in Linux/Mac: export OPENAI_API_KEY=…. Spring’s placeholder ${…} reads it from the environment. This way your source code stays free of private keys.</p><p>If you prefer YAML, it looks like this:</p><pre>spring:<br>  ai:<br>    openai:<br>      api-key: ${OPENAI_API_KEY}<br>      chat:<br>        options:<br>          model: gpt-4<br>          temperature: 0.7</pre><p>Beyond api-key, you can set other options like temperature, max tokens, etc., under spring.ai.openai.chat.options. For basic use, just the API key is enough.</p><p>Now the application knows how to reach OpenAI. Spring Boot auto-configuration will create a ChatClient bean (and other model beans) behind the scenes based on these properties.</p><h3>Building a Simple AI-Driven Controller</h3><p>With configuration in place, let’s write a controller that uses Spring AI’s ChatClient. Spring auto-configures a ChatClient.Builder (or directly a ChatClient bean) using the above properties. You can inject a ChatClient.Builder into your class and build the client.</p><p>For example, here’s a REST controller that returns a quick joke about any topic:</p><pre>import org.springframework.ai.chat.client.ChatClient;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>public class ChatController {<br>    private final ChatClient chatClient;<br>    public ChatController(ChatClient.Builder chatClientBuilder) {<br>        this.chatClient = chatClientBuilder.build();<br>    }<br>    @GetMapping(&quot;/ai/simple-joke&quot;)<br>    public String getJoke(@RequestParam(defaultValue = &quot;programmers&quot;) String topic) {<br>        // Send a prompt to the AI model and return the response<br>        return chatClient<br>                .prompt()<br>                .user(&quot;Tell me a simple joke about &quot; + topic)<br>                .call()<br>                .content();<br>    }<br>}</pre><p>In this code:</p><ul><li>We inject ChatClient.Builder and call build() to get a ChatClient instance.</li><li>In getJoke(), we create a chat prompt with user(&quot;...&quot;), then .call() the AI.</li><li>.content() extracts the generated text as a String.</li></ul><p>No OpenAI-specific code appears here — Spring AI does it. This aligns with the principle of provider-agnostic code.</p><p>You can return the raw string, or wrap it in JSON as needed (for example, returning a Map.of(&quot;joke&quot;, response)).</p><blockquote><strong><em>Tip:</em></strong><em> Use </em><em>ChatClient methods fluently. The call above is equivalent to invoking OpenAI’s Chat Completions API, but you don’t deal with HTTP or JSON. If you need to customize headers or timeouts, Spring AI also provides configuration properties and hooks (see the docs).</em></blockquote><h3>Using Prompt Templates to Improve Prompts</h3><p>Hardcoding prompt strings can get messy. Spring AI offers <strong>PromptTemplate</strong> for cleaner, parameterized prompts. This lets you define a template with placeholders and fill in variables at runtime. For example:</p><pre>@GetMapping(&quot;/ai/template-joke&quot;)<br>public String getTemplateJoke(@RequestParam String adjective, <br>                              @RequestParam String topic) {<br>    // Define a template with placeholders {adjective} and {topic}<br>    PromptTemplate template = new PromptTemplate(&quot;Tell me a {adjective} joke about {topic}.&quot;);<br>    // Fill in the placeholders<br>    Prompt prompt = template.create(Map.of(&quot;adjective&quot;, adjective, &quot;topic&quot;, topic));<br>    // Call the AI model with the templated prompt<br>    return chatClient<br>              .call(prompt)<br>              .getResult()<br>              .getOutput()<br>              .getContent();<br>}</pre><p>This PromptTemplate example comes from the Spring AI docs. It produces prompts like “Tell me a <strong>funny</strong> joke about <strong>cats</strong>.” You just change the template and variables – no string concatenation needed.</p><blockquote><strong><em>Tip:</em></strong><em> </em><strong><em>Prompt templates are great for maintenance.</em></strong><em> You can store templates in files or constants and reuse them. It also avoids injection issues with raw user input. Spring AI automatically adds any special instructions needed for output formatting (if you ask for structured data) when using </em><em>entity() or converters.</em></blockquote><h3>Handling the AI Response</h3><p>Spring AI lets you extract just the text or get the full response metadata. In the above examples we used .content() to get the plain string. Under the hood, Spring AI’s .call() returned a ChatResponse object with details. If you need more control (e.g. token usage, model name, etc.), you can get the full response. For example:</p><pre>ChatResponse response = chatClient<br>                            .prompt()<br>                            .user(&quot;Tell me a simple joke&quot;)<br>                            .call()<br>                            .response(); // get full ChatResponse<br>String joke = response.getResult().getOutput().getContent();<br>System.out.println(&quot;Model used: &quot; + response.getMetadata().getModel());</pre><p>Here, response.getResult().getOutput().getContent() is the joke text, and response.getMetadata() has info like the model name and token counts.</p><h3>Error Handling</h3><p>AI calls can fail (network issues, rate limits, invalid input, etc.). Wrap your calls in a try-catch to handle errors gracefully. Spring AI provides a common exception for API errors: OpenAiApiClientErrorException (and equivalents for other providers). For example:</p><pre>try {<br>    String answer = chatClient.prompt()<br>                             .user(&quot;Hello world&quot;)<br>                             .call()<br>                             .content();<br>    return answer;<br>}<br>catch (OpenAiApiClientErrorException ex) {<br>    // Handle API error (e.g., log and return a default message)<br>    System.err.println(&quot;AI call failed: &quot; + ex.getMessage());<br>    return &quot;Sorry, I couldn&#39;t get a response right now.&quot;;<br>}</pre><p>This catches all OpenAI-related errors in one place<a href="https://www.baeldung.com/spring-ai#:~:text=Additionally%2C%20as%20with%20communication%20with,abstraction%20over%20all%20OpenAI%20errors">baeldung.com</a>. You could also catch the generic ChatClientException or use Spring’s @ControllerAdvice to map exceptions to HTTP error responses.</p><blockquote><strong><em>Tip:</em></strong><em> </em><strong><em>Always validate user input.</em></strong><em> Do basic checks (e.g., not empty) before sending to the model, to avoid unexpected failures.</em></blockquote><h3>Adding Logging for Debugging</h3><p>Logging is crucial for debugging AI prompts and responses. For simple cases, you can print or log in your code. For example, using SLF4J:</p><pre>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>@RestController<br>public class ChatController {<br>    private static final Logger log = LoggerFactory.getLogger(ChatController.class);<br>    // ...<br>    public String getJoke(...) {<br>        String prompt = &quot;Tell me a joke about &quot; + topic;<br>        log.info(&quot;Sending prompt to AI: {}&quot;, prompt);<br>        String answer = chatClient.prompt().user(prompt).call().content();<br>        log.info(&quot;Received response: {}&quot;, answer);<br>        return answer;<br>    }<br>}</pre><p>Spring AI also has built-in observability. You can enable logging of prompts and completions via properties :</p><pre>spring.ai.chat.client.observations.log-prompt=true<br>spring.ai.chat.client.observations.log-completion=true</pre><p>By default these are false (to avoid accidentally logging sensitive info). Turn them on in development or debugging to see exactly what gets sent and received.</p><blockquote><strong><em>Tip:</em></strong><em> Consider using Spring Boot Actuator and Micrometer to collect metrics (Spring AI provides metrics for calls). But for beginners, simple logs (or the built-in observers) are a good start.</em></blockquote><h3>Testing the API with Postman or curl</h3><p>With the app running, test your endpoints just like any REST API. For example, if you used the above controller:</p><p><strong>Using curl:</strong></p><p>curl &quot;http://localhost:8080/ai/simple-joke?topic=java&quot;</p><ul><li>This might return something like &quot;A SQL query walks into a bar, walks up to two tables and asks: &#39;Can I join you?&#39;&quot;.</li></ul><p><strong>Using Postman:</strong></p><ul><li>Send a GET to http://localhost:8080/ai/simple-joke with query param topic=java.</li><li>You should get a JSON/string response with the joke.</li></ul><p>If you built the ChatService example (from [18]):</p><pre>curl &quot;http://localhost:8080/ai/chat?prompt=Hello&quot;</pre><p>It will return the AI’s answer in JSON. (The exact URL depends on your mappings.)</p><p>Check your console logs to see the prompt and response printed (if you added logging).</p><h3>Deploying Locally</h3><p>For local testing (no Docker needed), you can run the Spring Boot app directly:</p><ol><li><strong>Run via Maven:</strong></li></ol><pre>mvn spring-boot:run</pre><p>This will compile and start the app on port 8080 by default.</p><p><strong>2. Run the JAR:</strong></p><pre>mvn clean package<br>java -jar target/your-app-name-0.0.1-SNAPSHOT.jar</pre><p>(Replace the JAR name as built.) The embedded Tomcat will start and serve your APIs.</p><p>Before running, ensure the OPENAI_API_KEY environment variable is set in that shell/session (or set the property in application.properties if you prefer, though env var is safer). Once running, open http://localhost:8080/ in a browser or use curl/Postman as above.</p><p>No special deployment steps are needed beyond a normal Spring Boot app — it’s just another web application with an extra AI client.</p><h3>Bonus: Switching from OpenAI to Hugging Face</h3><p>One of Spring AI’s advantages is easy switching between providers. To use a Hugging Face Inference API instead of OpenAI:</p><ol><li><strong>Add the Hugging Face starter</strong> to your pom.xml (instead of or in addition to the OpenAI one)</li></ol><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-ai-huggingface-spring-boot-starter&lt;/artifactId&gt;<br>    &lt;!-- or spring-ai-starter-model-huggingface in some versions --&gt;<br>&lt;/dependency&gt;</pre><p><strong>2. Configure the Hugging Face endpoint and key</strong> in application.properties:</p><pre>spring.ai.huggingface.chat.api-key=${HUGGINGFACE_API_KEY}<br>spring.ai.huggingface.chat.url=https://api-inference.huggingface.co/models/your-model</pre><p>You need a Hugging Face Inference API token (HUGGINGFACE_API_KEY) and the inference URL for your model endpoint.</p><p><strong>3. Use the Hugging Face client in code:</strong> The starter auto-configures a HuggingfaceChatModel bean. You can inject it directly, as in this example from the docs :</p><pre>@RestController<br>public class HuggingChatController {<br><br>    private final HuggingfaceChatModel chatModel;<br><br>    public HuggingChatController(HuggingfaceChatModel chatModel) {<br>        this.chatModel = chatModel;<br>    }<br><br>    @GetMapping(&quot;/ai/generate&quot;)<br>    public Map&lt;String, String&gt; generate(@RequestParam(defaultValue = &quot;Hello&quot;) String message) {<br>        String output = this.chatModel.call(message);<br>        return Map.of(&quot;output&quot;, output);<br>    }<br>}</pre><p>This works the same way, but under the covers it calls the Hugging Face endpoint. No need to change the rest of your app code.</p><blockquote><strong><em>Tip:</em></strong><em> To swap providers, you really only change the dependency and config. Your service logic stays identical. This “write once, switch easily” capability is one of Spring AI’s core benefits</em></blockquote><p><strong>Too Long; Didn’t Read</strong></p><p><strong>Introduction:</strong> <strong>Spring AI</strong> is a <strong>Spring-friendly way</strong> to call <strong>LLMs (OpenAI, HuggingFace, etc.)</strong> in your <strong>Java apps</strong>. It saves you from manual <strong>HTTP calls</strong> and <strong>JSON handling</strong>.</p><p><strong>Setup:</strong> Create a <strong>Spring Boot project (Java 21+, Spring Boot 3.2+)</strong>. Add <strong>spring-ai-boot-starter</strong> and <strong>spring-ai-openai-starter</strong> (or the appropriate provider starter) to your <strong>pom.xml</strong>.</p><p><strong>API Key:</strong> In <strong>application.properties</strong>, set spring.ai.openai.api-key=${OPENAI_API_KEY} (and <strong>model, temperature</strong>) to point to your <strong>OpenAI key</strong>.</p><p><strong>Controller:</strong> Inject <strong>ChatClient</strong> (via <strong>ChatClient.Builder</strong>), then in your endpoint do:</p><pre>chatClient.prompt().user(&quot;Your prompt here&quot;).call().content();</pre><p>This sends the prompt to the AI and gets a String reply.</p><ul><li><strong>Prompt Templates:</strong> Use PromptTemplate for dynamic prompts. E.g.</li></ul><pre>PromptTemplate template = new PromptTemplate(&quot;Tell me a {adj} joke about {topic}.&quot;);<br>Prompt prompt = template.create(Map.of(&quot;adj&quot;, &quot;funny&quot;, &quot;topic&quot;, &quot;cats&quot;));<br>String answer = chatClient.call(prompt).getResult().getOutput().getContent();</pre><p><strong>Handling Responses:</strong> .content() gives the <strong>text</strong>. Use .response() to get <strong>ChatResponse</strong> with <strong>metadata</strong>. Wrap calls in <strong>try-catch</strong> to handle errors (<strong>Spring AI</strong> throws <strong>OpenAiApiClientErrorException</strong> on <strong>API failures</strong>).</p><p><strong>Logging:</strong> Use a logger (or enable Spring AI observability) to log prompts and responses for debugging.</p><p><strong>Testing:</strong> Run the app and test with Postman or curl. E.g.:</p><pre>curl &quot;http://localhost:8080/ai/simple-joke?topic=java&quot;</pre><p>You should see the AI’s generated text in the response.</p><p><strong>Running Locally:</strong> Just run with mvn spring-boot:run or build a jar and java -jar. Ensure the OPENAI_API_KEY env var is set. The app will serve on port 8080 by default.</p><p><strong>Bonus — Switch to Hugging Face:</strong> Replace the OpenAI starter with spring-ai-huggingface-spring-boot-starter, and in application.properties set spring.ai.huggingface.chat.api-key and spring.ai.huggingface.chat.url as documented. Inject HuggingfaceChatModel in your code and call it just like ChatClient.</p><p>Spring AI brings AI into Spring Boot in a familiar way, so you can focus on your application logic instead of plumbing. With these steps, you’ve built a basic AI-powered Spring app. From here, you can explore more Spring AI features — structured outputs, embeddings, RAG, and more — as your AI needs grow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80120b96c1ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>