<?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 Full Stack Developer on Medium]]></title>
        <description><![CDATA[Stories by Full Stack Developer on Medium]]></description>
        <link>https://medium.com/@ByteCodeBlogger?source=rss-d9bf18529541------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ANzDaum1wnT55zhf1sbLSg@2x.jpeg</url>
            <title>Stories by Full Stack Developer on Medium</title>
            <link>https://medium.com/@ByteCodeBlogger?source=rss-d9bf18529541------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 03:51:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ByteCodeBlogger/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[Deep Dive into simple Java Interview Questions with me : Thread Safety]]></title>
            <link>https://medium.com/@ByteCodeBlogger/deep-dive-into-simple-java-interview-questions-with-me-thread-safety-86af24f0f2ef?source=rss-d9bf18529541------2</link>
            <guid isPermaLink="false">https://medium.com/p/86af24f0f2ef</guid>
            <category><![CDATA[threading-in-java]]></category>
            <category><![CDATA[java-interview]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[thread-safety]]></category>
            <dc:creator><![CDATA[Full Stack Developer]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 07:16:19 GMT</pubDate>
            <atom:updated>2026-04-13T07:16:19.148Z</atom:updated>
            <content:encoded><![CDATA[<p>Given a code snippet, identify the issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LSjQVbdtscByQ-gi" /><figcaption>Photo by <a href="https://unsplash.com/@microsoftcopilot?utm_source=medium&amp;utm_medium=referral">Microsoft Copilot</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In below code snippet, can you identify the issue? (And its not syntax)</p><pre>public class UserCache {<br>    private Map&lt;String, User&gt; cache = new HashMap&lt;&gt;();<br>    <br>    public void addUser(User user) {<br>        cache.put(user.getId(), user);<br>    }<br>}</pre><p>How many issues did you think of? :) Well there are about 5 issues :</p><ol><li><strong>Thread Safety Issue</strong></li></ol><ul><li>HashMap is not thread-safe. Concurrent access will cause race conditions and potential data corruption</li><li><strong>Fix</strong>: Use ConcurrentHashMap or synchronize access</li></ul><p><strong>2. Memory Leak</strong></p><ul><li>Cache grows indefinitely without eviction policy</li><li>No size limits or TTL (time-to-live) mechanism</li><li><strong>Fix</strong>: Implement cache eviction (LRU, size limits, or use libraries like Caffeine/Guava)</li></ul><p><strong>3. Null Safety</strong></p><ul><li>No null checks for user parameter or user.getId()</li><li><strong>Fix</strong>: Add validation or use @NonNull annotations</li></ul><p><strong>4. Encapsulation Violation</strong></p><ul><li>Direct field access to mutable HashMap exposes internal state</li><li><strong>Fix</strong>: Make field private final and provide controlled access methods</li></ul><p><strong>5. Missing Cache Operations</strong></p><ul><li>Only has addUser() - missing getUser(), removeUser(), clear()</li><li>No way to retrieve cached data</li></ul><h3>DEEP DIVE : FOLLOW UP QUESTIONS</h3><h4>What is the INTERNAL difference between HashMap and ConcurrentHashMap that makes it thread safe?</h4><p><strong>1. Locking Mechanism</strong></p><p><strong>HashMap:</strong></p><ul><li>No locking at all</li><li>Single-threaded design</li><li>Concurrent modifications cause ConcurrentModificationException or data corruption</li></ul><p><strong>ConcurrentHashMap:</strong></p><ul><li>Uses <strong>lock striping</strong> (segmentation) in Java 7</li><li>Uses <strong>CAS operations + synchronized blocks</strong> in Java 8+</li><li>Only locks affected bucket/segment, not entire map</li></ul><p><strong>2. Internal Structure (Java 8+)</strong></p><p><strong>HashMap:</strong></p><pre>Array of buckets → Each bucket is linked list/tree<br>No synchronization on bucket access</pre><p><strong>ConcurrentHashMap:</strong></p><pre>Array of Node[] → Each bucket independently lockable<br>Uses volatile variables for visibility<br>Atomic operations via Unsafe.compareAndSwapObject()</pre><p><strong>3. Key Technical Mechanisms</strong></p><p><strong>ConcurrentHashMap uses:</strong></p><ul><li><strong>CAS (Compare-And-Swap)</strong>: Lock-free updates for simple operations</li></ul><pre>// Pseudocode of internal operation<br>if (currentValue == expectedValue) {<br>    atomicUpdate(newValue);<br>}</pre><ul><li><strong>Synchronized blocks</strong>: Only when bucket needs structural changes (collisions)</li></ul><pre>synchronized (bucket) {<br>    // Insert/remove in chain<br>}</pre><ul><li><strong>Volatile fields</strong>: Ensures visibility across threads</li></ul><pre>transient volatile Node&lt;K,V&gt;[] table;</pre><p><strong>4. Put Operation Comparison</strong></p><p><strong>HashMap.put():</strong></p><pre>// Simplified<br>public V put(K key, V value) {<br>    int hash = hash(key);<br>    int index = indexFor(hash);<br>    table[index] = newNode; // Direct write - NOT thread-safe<br>}</pre><p><strong>ConcurrentHashMap.put():</strong></p><pre>// Simplified Java 8+ approach<br>public V put(K key, V value) {<br>    int hash = spread(key.hashCode());<br>    <br>    if (table[i] == null) {<br>        // CAS operation - lock-free<br>        casTabAt(table, i, newNode);<br>    } else {<br>        synchronized (table[i]) { // Lock only this bucket<br>            // Insert into chain/tree<br>        }<br>    }<br>}</pre><p><strong>5. Size Tracking</strong></p><p><strong>HashMap:</strong></p><ul><li>Simple int size field</li><li>Not atomic</li></ul><p><strong>ConcurrentHashMap:</strong></p><ul><li>Uses LongAdder or baseCount + counterCells[]</li><li>Distributes count across multiple cells to reduce contention</li><li>Aggregates on size() call</li></ul><h4>WHAT IS THE DIFFERENCE BETWEEN ConcurrentHashMap &amp; Collections.synchronizedMap</h4><p><strong>1. Locking Granularity (Performance)</strong></p><p><strong>ConcurrentHashMap:</strong></p><ul><li><strong>Fine-grained locking</strong> — locks individual buckets/segments</li><li>Multiple threads can read/write different buckets simultaneously</li><li>High concurrency, better throughput</li></ul><p><strong>Collections.synchronizedMap:</strong></p><ul><li><strong>Coarse-grained locking</strong> — locks entire map for every operation</li><li>Only one thread can access map at a time (read OR write)</li><li>Poor concurrency, bottleneck under load</li></ul><p><strong>2. Iteration Behavior</strong></p><p><strong>ConcurrentHashMap:</strong></p><ul><li><strong>Weakly consistent</strong> iterators</li><li>Reflects state at creation + may reflect subsequent changes</li><li>Never throws ConcurrentModificationException</li><li>No external synchronization needed</li></ul><p><strong>Collections.synchronizedMap:</strong></p><ul><li><strong>Fail-fast</strong> iterators</li><li>Throws ConcurrentModificationException if modified during iteration</li><li><strong>Requires manual synchronization:</strong></li></ul><pre>Map m = Collections.synchronizedMap(new HashMap());<br>synchronized(m) {  // Must lock manually!<br>    for (Object key : m.keySet()) {<br>        // iterate<br>    }<br>}</pre><p><strong>3. Null Key/Value Support</strong></p><p><strong>ConcurrentHashMap:</strong></p><ul><li>Does <strong>NOT</strong> allow null keys or values</li><li>Throws NullPointerException</li></ul><p><strong>Collections.synchronizedMap:</strong></p><ul><li>Allows null (depends on underlying map)</li><li>HashMap allows one null key, multiple null values</li></ul><p><strong>When to Use:</strong></p><ul><li><strong>ConcurrentHashMap</strong>: High-concurrency scenarios, modern applications</li><li><strong>Collections.synchronizedMap</strong>: Legacy code, need null support, simple synchronization needs</li></ul><h4>If ConcurrentHashMap is thread-safe, why not always use it everywhere instead of HashMap?</h4><p><strong>1. Performance Overhead (Single-Threaded)</strong></p><ul><li>ConcurrentHashMap has synchronization overhead even with one thread</li><li>HashMap is 10-20% faster in single-threaded scenarios</li><li>Extra memory for concurrency structures (volatile fields, CAS machinery)</li></ul><pre>// Single-threaded application<br>Map&lt;String, Config&gt; appConfig = new HashMap&lt;&gt;();  // Better choice<br>// vs<br>Map&lt;String, Config&gt; appConfig = new ConcurrentHashMap&lt;&gt;();  // Unnecessary overhead</pre><p><strong>2. No Null Support</strong></p><ul><li>ConcurrentHashMap rejects null keys and values</li><li>Some designs legitimately use null as sentinel values</li></ul><pre>Map&lt;String, User&gt; cache = new HashMap&lt;&gt;();<br>cache.put(&quot;guest&quot;, null);  // Valid - represents &quot;no user&quot;<br><br>Map&lt;String, User&gt; cache = new ConcurrentHashMap&lt;&gt;();<br>cache.put(&quot;guest&quot;, null);  // NullPointerException!</pre><p><strong>3. Memory Footprint</strong></p><ul><li>ConcurrentHashMap uses more memory per entry</li><li>Additional fields for concurrency control</li><li>Matters in memory-constrained environments or large collections</li></ul><pre>─────────────────────────────────────┬──────────────────────────────────────────┐<br>│         Use HashMap when:               │    Use ConcurrentHashMap when:           │<br>├─────────────────────────────────────────┼──────────────────────────────────────────┤<br>│ Single-threaded application             │ Multi-threaded access required           │<br>├─────────────────────────────────────────┼──────────────────────────────────────────┤<br>│ Local/method scope (thread-confined)    │ Shared across multiple threads           │<br>├─────────────────────────────────────────┼──────────────────────────────────────────┤<br>│ Need null keys or values                │ High read concurrency needed             │<br>├─────────────────────────────────────────┼──────────────────────────────────────────┤<br>│ Already externally synchronized         │ Lock-free reads required                 │<br>├─────────────────────────────────────────┼──────────────────────────────────────────┤<br>│ Need ordering                           │ Frequent concurrent writes               │<br>│ (LinkedHashMap/TreeMap)                 │                                          │<br>├─────────────────────────────────────────┼──────────────────────────────────────────┤<br>│ Memory-constrained environment          │ No null values in design                 │<br>├─────────────────────────────────────────┼──────────────────────────────────────────┤<br>│ Maximum single-thread performance       │ Minimize lock contention                 │<br>├─────────────────────────────────────────┼──────────────────────────────────────────┤<br>│ Simple, clear intent (not shared)       │ High-throughput scenarios                │<br>└─────────────────────────────────────────┴──────────────────────────────────────────┘</pre><h4>WHAT ARE SOME CACHING FRAMEWORKS ?</h4><p><strong>1. Caffeine (Recommended for Java)</strong></p><pre>Cache&lt;String, User&gt; cache = Caffeine.newBuilder()<br>    .maximumSize(10_000)<br>    .expireAfterWrite(10, TimeUnit.MINUTES)<br>    .build();<br><br>cache.put(&quot;user1&quot;, user);<br>User user = cache.getIfPresent(&quot;user1&quot;);</pre><ul><li>Fastest Java cache library</li><li>Automatic eviction (LRU, LFU, time-based)</li><li>Async loading support</li></ul><p><strong>2. Guava Cache</strong></p><pre>LoadingCache&lt;String, User&gt; cache = CacheBuilder.newBuilder()<br>    .maximumSize(1000)<br>    .expireAfterAccess(30, TimeUnit.MINUTES)<br>    .build(new CacheLoader&lt;String, User&gt;() {<br>        public User load(String key) {<br>            return loadUserFromDB(key);<br>        }<br>    });</pre><ul><li>Simple API</li><li>Auto-loading capabilities</li><li>Good for small to medium caches</li></ul><p><strong>3. Spring Cache Abstraction</strong></p><pre>@Cacheable(&quot;users&quot;)<br>public User getUser(String id) {<br>    return userRepository.findById(id);<br>}<br><br>@CacheEvict(&quot;users&quot;)<br>public void updateUser(User user) {<br>    userRepository.save(user);<br>}</pre><ul><li>Works with multiple backends (Caffeine, Redis, Ehcache)</li><li>Annotation-based</li><li>Easy integration</li></ul><p><strong>4. Redis</strong></p><pre>// Using Jedis client<br>Jedis jedis = new Jedis(&quot;localhost&quot;);<br>jedis.set(&quot;user:1&quot;, userJson);<br>String user = jedis.get(&quot;user:1&quot;);<br>jedis.expire(&quot;user:1&quot;, 3600); // TTL in seconds</pre><ul><li>Distributed caching</li><li>Persistence options</li><li>Pub/sub, data structures</li></ul><p><strong>5. Ehcache</strong></p><pre>CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);<br>Cache&lt;String, User&gt; cache = cacheManager.createCache(&quot;users&quot;,<br>    CacheConfigurationBuilder.newCacheConfigurationBuilder(<br>        String.class, User.class, ResourcePoolsBuilder.heap(100))<br>    .build());</pre><ul><li>Disk overflow support</li><li>Clustering capabilities</li><li>JCache (JSR-107) compliant</li></ul><p>Please let me know what are some other follow up questions that can be asked in this area ? :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86af24f0f2ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interview Story : “We Use the Latest Java”………. “Java 8”]]></title>
            <link>https://medium.com/@ByteCodeBlogger/interview-story-we-use-the-latest-java-java-8-99144ee8ac23?source=rss-d9bf18529541------2</link>
            <guid isPermaLink="false">https://medium.com/p/99144ee8ac23</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[java-developer]]></category>
            <category><![CDATA[java-interview]]></category>
            <dc:creator><![CDATA[Full Stack Developer]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 14:24:56 GMT</pubDate>
            <atom:updated>2026-02-18T14:25:24.124Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been taking interviews for Java Full Stack developers recently.</p><p>And I’ve discovered something fascinating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_E3V-MlKOySkunOk" /><figcaption>Photo by <a href="https://unsplash.com/@huyenbui30?utm_source=medium&amp;utm_medium=referral">Huyen Bui</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>According to a statistically significant number of candidates, <strong>Java 8 is the “latest version” they use.</strong></p><p>Or when I ask,<br>“What features of the latest Java versions have you worked with?”</p><p>The answer arrives with great confidence:</p><ul><li>Streams</li><li>Functional Interfaces</li><li>Lambda expressions</li></ul><p>At this point, I usually check the calendar to confirm it’s not 2015 :P</p><h4>Java 8 was released in <strong>March 2014</strong>.<br>That was 12 years ago.</h4><p>If Java 8 were a child, it would be in middle school by now.</p><h3>Streams Are Not “Latest Java”</h3><p>Streams are not cutting-edge anymore.</p><p>They are baseline.</p><blockquote>Saying “I use Streams” in 2026 is like saying:</blockquote><blockquote><em>“I use ArrayList.”</em></blockquote><p>Great. That’s expected.</p><p>It’s not a feature of “latest Java.”<br>It’s table stakes.</p><h3>What This Really Signals</h3><p>When someone says they use “latest Java” and then lists Java 8 features, it usually means one of three things:</p><ol><li>Their project is stuck on Java 8 and they never explored beyond it.</li><li>They haven’t read release notes in years.</li><li>They equate “Java 8 introduced it” with “still modern.”</li></ol><p>None of these are crimes.</p><p>BUT for a senior or mid-level engineer, it signals stagnation.</p><p>Technology moves. Especially Java, which now releases every six months.</p><p>If you are building backend systems in 2026 and haven’t explored:</p><ul><li>Records</li><li>Sealed classes</li><li>Modern switch</li><li>Virtual threads</li></ul><p>Then you’re coding with a 2014 mental model in a 2026 ecosystem.</p><h3>Section for Interviewers : The Real Question Interviewers Should Ask</h3><p>Instead of asking:</p><blockquote><em>“What is the latest Java version you worked on?”</em></blockquote><p>Try asking:</p><ul><li>What Java version is your production system currently on?</li><li>Why did your team choose that version?</li><li>Have you evaluated migrating?</li><li>Which post-Java-8 features have improved your codebase?</li><li>Have you experimented with virtual threads?</li><li>Do you understand how records differ from Lombok @Data?</li></ul><p>These questions expose depth.</p><p>Because real experience sounds like this:</p><blockquote><em>“We’re on Java 17 LTS. We migrated from 8 because records and switch expressions simplified our DTO layer. We’re evaluating Java 21 for virtual threads to improve concurrency in our I/O heavy services.”</em></blockquote><p>That’s modern engineering.</p><h3>Section for Interviewee : What Happened After Java 8?</h3><p>Here’s a quick reality check.</p><h3>Java 9 (2017)</h3><ul><li>Module System (Project Jigsaw)</li><li>JShell</li><li>Collection factory methods (List.of, Set.of)</li><li>Private methods in interfaces</li></ul><h3>Java 10</h3><ul><li>var for local variable type inference</li></ul><h3>Java 11 (LTS)</h3><ul><li>New String methods (isBlank, lines, strip)</li><li>Files.readString</li><li>HTTP Client API (standardized)</li><li>Removal of Java EE modules</li></ul><h3>Java 14–17</h3><ul><li>Switch expressions (no more accidental fall-through drama)</li><li>Records</li><li>Pattern matching for instanceof</li><li>Text blocks</li><li>Sealed classes</li></ul><h3>Java 21 (LTS)</h3><ul><li>Virtual Threads (Project Loom)</li><li>Pattern matching for switch (finalized)</li><li>Structured concurrency (preview)</li><li>Record patterns</li></ul><p>But somehow, in many interviews, Java evolution stopped at:</p><blockquote><em>“Yes ma’am, we use streams.”</em></blockquote><h3>Final Thought</h3><p>Streams were revolutionary.</p><p>In 2014.</p><p>In 2026, calling them “latest Java” is like calling WhatsApp a startup.</p><p>If you’re interviewing for backend roles today, here’s a gentle reminder:</p><p>Read the release notes.<br>Experiment with new LTS versions.<br>Understand why features exist, not just that they exist.</p><p>Because “We use Java 8” is not a flex anymore :)</p><blockquote>P.S : I have never rejected any candidate for not using latest Java. But its minus points if somebody will try to claim to use some version but know nothing about it. Be honest and be smart :)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99144ee8ac23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency vs Parallelism in Java]]></title>
            <link>https://medium.com/@ByteCodeBlogger/concurrency-vs-parallelism-in-java-8495d7f0a495?source=rss-d9bf18529541------2</link>
            <guid isPermaLink="false">https://medium.com/p/8495d7f0a495</guid>
            <category><![CDATA[java-23]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[java-concept]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Full Stack Developer]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 09:51:55 GMT</pubDate>
            <atom:updated>2025-12-13T09:51:55.234Z</atom:updated>
            <content:encoded><![CDATA[<p>Both are not the same thing, let’s look into it and quickly learn about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iMuodeYgLMgTc8TJ" /><figcaption>Photo by <a href="https://unsplash.com/@anshu18?utm_source=medium&amp;utm_medium=referral">Anshu A</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Concurrency</h3><p><strong>Concurrency is the composition of independently executing tasks that may or may not run at the same time.</strong> It’s about structuring a program to handle multiple tasks that can make progress without waiting for each other to complete, regardless of whether they execute simultaneously.</p><blockquote>Concurrency is a <em>design property</em> — it’s about how you structure your program to manage multiple concerns.</blockquote><h3>Parallelism</h3><p><strong>Parallelism is the simultaneous execution of multiple computations to achieve faster results.</strong> It’s about dividing a problem into sub-problems that execute at the exact same moment on different processing units.</p><blockquote>Parallelism is an <em>execution property</em> — it’s about actually running things at the same time to improve performance.</blockquote><h3>Key Distinctions</h3><p><strong>Concurrency (Task Management)</strong></p><ul><li>Multiple tasks make progress by switching between them</li><li>Can run on a single core through time-slicing</li><li>Focus: Structure and coordination of tasks</li><li>Example: A single chef switching between chopping vegetables and stirring soup</li></ul><p><strong>Parallelism (Simultaneous Execution)</strong></p><ul><li>Multiple tasks execute at the exact same time</li><li>Requires multiple cores/processors</li><li>Focus: Speed through simultaneous computation</li><li>Example: Multiple chefs each preparing different dishes</li></ul><h3>Java Code Examples</h3><h3>Concurrency with Threads</h3><pre>public class ConcurrencyExample {<br><br>    public static void main(String[] args) {<br><br>        Thread task1 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 5; i++) {<br>                System.out.println(&quot;Task 1 - Count: &quot; + i);<br>                try { Thread.sleep(100); } catch (InterruptedException e) {}<br>            }<br>        })<br><br>Thread task2 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 5; i++) {<br>                System.out.println(&quot;Task 2 - Count: &quot; + i);<br>                try { Thread.sleep(100); } catch (InterruptedException e) {}<br>            }<br>        });<br><br>        task1.start();<br>        task2.start();<br>    }<br>}<br>// Output shows interleaved execution (concurrent but not necessarily parallel)</pre><h3>Parallelism with Parallel Streams</h3><pre>import java.util.Arrays;<br>import java.util.List;<br><br>public class ParallelismExample {<br><br>    public static void main(String[] args) {<br><br>        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);<br><br>        // Sequential processing<br>        long sequential = numbers.stream()<br>            .map(n -&gt; n * n)<br>            .reduce(0, Integer::sum);<br><br>        // Parallel processing - actually runs on multiple cores<br>        long parallel = numbers.parallelStream()<br>            .map(n -&gt; n * n)<br>            .reduce(0, Integer::sum);<br><br>        System.out.println(&quot;Sequential: &quot; + sequential);<br>        System.out.println(&quot;Parallel: &quot; + parallel);<br><br>    }<br>}</pre><h3>Parallelism with ExecutorService</h3><pre>import java.util.concurrent.*;<br><br>public class ParallelExecutorExample {<br><br>    public static void main(String[] args) throws InterruptedException {<br><br>        ExecutorService executor = Executors.newFixedThreadPool(4);<br>        Callable&lt;Integer&gt; task = () -&gt; {<br>            int sum = 0;<br>            for (int i = 0; i &lt; 1000; i++) sum += i;<br>            return sum;<br>        };<br><br>        // Submit 4 tasks that run in parallel on 4 threads<br>        Future&lt;Integer&gt; f1 = executor.submit(task);<br>        Future&lt;Integer&gt; f2 = executor.submit(task);<br>        Future&lt;Integer&gt; f3 = executor.submit(task);<br>        Future&lt;Integer&gt; f4 = executor.submit(task);<br>        executor.shutdown();<br>    }<br>}</pre><ul><li><strong>Concurrency</strong> = Multiple tasks can be <em>in progress</em> at once (structure)</li><li><strong>Parallelism</strong> = Multiple tasks <em>are executing</em> at once (execution)</li></ul><h3>Trade-offs</h3><p><strong>Concurrency</strong> enables responsiveness and resource sharing but adds complexity in coordination.</p><p><strong>Parallelism</strong> provides speed improvements but requires sufficient cores and thread-safe operations.</p><h3>When to Choose What</h3><p><strong>Choose Concurrency When:</strong></p><ul><li>Handling I/O-bound tasks (network calls, file operations, database queries)</li><li>Building responsive UIs or interactive applications</li><li>Managing independent workflows (user sessions, event processing)</li><li>Working with asynchronous operations</li><li>Need to handle many simultaneous connections</li></ul><p><strong>Choose Parallelism When:</strong></p><ul><li>Processing CPU-intensive computations (mathematical calculations, encryption)</li><li>Working with large datasets that can be partitioned</li><li>Performing batch transformations (image/video processing)</li><li>You have sufficient cores available</li><li>The problem is embarrassingly parallel (minimal dependencies)</li></ul><p><strong>Avoid Parallelism When:</strong></p><ul><li>Dataset is small (overhead exceeds benefit)</li><li>Operations have dependencies between elements</li><li>Memory bandwidth is the bottleneck</li><li>Running on limited hardware (mobile, embedded systems)</li></ul><p>Hope this help!! It may not be asked in interviews but it is good for your foundation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8495d7f0a495" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence series : Regression !!]]></title>
            <link>https://medium.com/@ByteCodeBlogger/artificial-intelligence-series-regression-6f25413195c4?source=rss-d9bf18529541------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f25413195c4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aiml]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[artificial-inteligence]]></category>
            <dc:creator><![CDATA[Full Stack Developer]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 15:48:10 GMT</pubDate>
            <atom:updated>2025-12-08T15:48:10.304Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial Intelligence series : Regression !!</h3><p>As some of my regular readers know, I am pursuing Masters in AI/ML and here is something you MUST know if you are interested in AI/ML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-ep3JZ33t9_ytNsZ" /><figcaption>Photo by <a href="https://unsplash.com/@bladimirgarcia?utm_source=medium&amp;utm_medium=referral">Bladimir Garcia</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Regression Definition</h3><p><strong>Regression is a statistical method that models the relationship between a dependent variable (output) and one or more independent variables (inputs) to predict continuous numerical values.</strong></p><h3>Core Components:</h3><ul><li><strong>Dependent Variable (Y)</strong>: The outcome you want to predict</li><li><strong>Independent Variable(s) (X)</strong>: The input features used for prediction</li><li><strong>Relationship</strong>: Mathematical function connecting inputs to output</li></ul><h3>Simple Example:</h3><pre>Predicting house price (Y) based on size (X)<br><br>Price = $50,000 + ($200 × Square Feet)</pre><h3>Key Characteristics:</h3><ul><li>Predicts <strong>continuous values</strong> (not categories)</li><li>Finds the <strong>best-fit line or curve</strong> through data points</li><li>Minimizes <strong>prediction error</strong> between actual and predicted values</li></ul><h3>Real-World AI Applications</h3><p>Regression powers critical AI systems:</p><ul><li><strong>Predictive Analytics</strong> — Forecasting sales, demand, stock prices</li><li><strong>Recommendation Systems</strong> — Predicting user ratings and preferences</li><li><strong>Computer Vision</strong> — Age estimation, pose estimation, object localization</li><li><strong>Natural Language Processing</strong> — Sentiment scoring, readability metrics</li><li><strong>Autonomous Systems</strong> — Predicting trajectories, sensor calibration</li></ul><p>This is regression for now and I will add more to this article as I learn more about it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f25413195c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NaN: The Number That Hates Itself]]></title>
            <link>https://medium.com/@ByteCodeBlogger/nan-the-number-that-hates-itself-28a36ea2c774?source=rss-d9bf18529541------2</link>
            <guid isPermaLink="false">https://medium.com/p/28a36ea2c774</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-fun-facts]]></category>
            <category><![CDATA[java-23]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java-interview]]></category>
            <dc:creator><![CDATA[Full Stack Developer]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 16:52:07 GMT</pubDate>
            <atom:updated>2025-11-21T16:52:07.525Z</atom:updated>
            <content:encoded><![CDATA[<p>Java doesn’t always have to be serious! Let’s look at NaN in Java, its fun!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hCLBHttgJV5410wW" /><figcaption>Photo by <a href="https://unsplash.com/@braydona?utm_source=medium&amp;utm_medium=referral">Braydon Anderson</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Strangest Number in Java</h3><p>Meet NaN - short for &quot;Not a Number&quot; - the most antisocial value in all of Java:</p><pre>double nan = Double.NaN;<br><br>System.out.println(nan == nan);   // false 🤯<br>System.out.println(nan != nan);   // true 🤯<br>System.out.println(nan &lt; 5);      // false<br>System.out.println(nan &gt; 5);      // false<br>System.out.println(nan == 5);     // false</pre><p><strong>NaN is the only value in Java that is not equal to itself.</strong> Let that sink in.</p><h3>How Do You Even Get a NaN?</h3><p>NaN appears when math goes off the rails:</p><pre>double result1 = 0.0 / 0.0;           // NaN<br>double result2 = Math.sqrt(-1);       // NaN<br>double result3 = Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY;  // NaN<br>double result4 = Double.POSITIVE_INFINITY / Double.POSITIVE_INFINITY;  // NaN<br><br>System.out.println(result1);  // NaN</pre><p>Basically, whenever you ask Java to do impossible math, you get NaN.</p><h3>The Identity Crisis</h3><h3>Question: Is NaN equal to NaN?</h3><p><strong>Your brain:</strong> “Of course! Everything equals itself!”</p><p><strong>Java:</strong> “Nope.”</p><pre>double x = Double.NaN;<br>double y = Double.NaN;<br><br>System.out.println(x == y);  // false</pre><p>Even two NaNs aren’t equal to each other. They’re like snowflakes — each one is uniquely… not a number.</p><h3>Question: How do you check for NaN then?</h3><p><strong>Wrong way:</strong></p><pre>if (value == Double.NaN) {  // Always false!<br>    System.out.println(&quot;It&#39;s NaN!&quot;);<br>}</pre><p><strong>Right way:</strong></p><pre>if (Double.isNaN(value)) {  // Correct!<br>    System.out.println(&quot;It&#39;s NaN!&quot;);<br>}</pre><h3>Why This Madness?</h3><p>This isn’t Java being quirky — it’s following the <strong>IEEE 754 floating-point standard</strong>. The logic goes:</p><blockquote><strong><em>“If a calculation is undefined, we can’t say the result equals anything — not even another undefined result.”</em></strong></blockquote><p>Think of it like this:</p><ul><li>0/0 could be anything (0, 1, infinity, 42...)</li><li>sqrt(-1) is imaginary</li><li>These aren’t the same “undefined”</li><li>So NaN ≠ NaN</li></ul><p>It’s mathematically sound, even if it hurts your brain.</p><h3>The Comparison Trap</h3><p>NaN breaks <strong>all</strong> comparisons:</p><pre>double nan = Double.NaN;<br><br>nan == 100   // false<br>nan != 100   // true<br>nan &lt; 100    // false<br>nan &gt; 100    // false<br>nan &lt;= 100   // false<br>nan &gt;= 100   // false</pre><p>NaN is neither less than, greater than, nor equal to anything — including itself!</p><h3>Real-world disaster:</h3><pre>double[] scores = {85.5, 92.0, Double.NaN, 78.5};<br><br>// Find maximum score<br>double max = scores[0];<br>for (double score : scores) {<br>    if (score &gt; max) {  // NaN &gt; max is always false!<br>        max = score;<br>    }<br>}<br>System.out.println(max);  // 85.5 - Wrong! Missed 92.0 because of NaN</pre><h3>Survival Guide</h3><h3>DO: Use the proper check</h3><pre>if (Double.isNaN(value)) {<br>    // Handle NaN case<br>}</pre><h3>DO: Filter NaN before calculations</h3><pre>double sum = Arrays.stream(values)<br>    .filter(v -&gt; !Double.isNaN(v))<br>    .sum();</pre><h3>DO: Use Float.isNaN() for floats</h3><pre>float f = Float.NaN;<br>if (Float.isNaN(f)) {<br>    // Handle it<br>}</pre><h3>DON’T: Compare with ==</h3><pre>if (value == Double.NaN) {  // Never works!<br>    // This code never runs<br>}</pre><h3>DON’T: Ignore NaN in calculations</h3><pre>double average = sum / count;  // Could be NaN!<br>// Always check before using the result</pre><h3>The Quirky Behavior Showcase</h3><p><strong>NaN propagates through calculations:</strong></p><pre>double result = 10 + Double.NaN;  // NaN<br>result = 5 * Double.NaN;          // NaN<br>result = Math.max(100, Double.NaN);  // NaN (in most cases)</pre><p><strong>NaN in sorting causes chaos:</strong></p><pre>Double[] numbers = {3.0, Double.NaN, 1.0, 2.0};<br>Arrays.sort(numbers);<br>// Result is unpredictable! NaN breaks comparison contract</pre><p><strong>NaN in collections:</strong></p><pre>Set&lt;Double&gt; set = new HashSet&lt;&gt;();<br>set.add(Double.NaN);<br>set.add(Double.NaN);<br>System.out.println(set.size());  // 2! (They hash differently)</pre><h3>The Philosophical Takeaway</h3><p>NaN teaches us an important lesson: <strong>Not all values are created equal.</strong></p><p>In a world where we expect x == x to always be true, NaN reminds us that sometimes, uncertainty is the only honest answer.</p><p>When your calculation doesn’t make sense, Java doesn’t pretend it does. It gives you NaN and says, “You figure it out.”</p><p><strong>Remember:</strong> NaN is not a bug, it’s a feature. A weird, self-hating, comparison-breaking feature that follows international standards. Handle it with care, check for it explicitly, and never, ever use == to find it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28a36ea2c774" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autoboxing: When Java’s Math Breaks Your Brain]]></title>
            <link>https://medium.com/@ByteCodeBlogger/autoboxing-when-javas-math-breaks-your-brain-f5d2bc64f87d?source=rss-d9bf18529541------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5d2bc64f87d</guid>
            <category><![CDATA[java-interview]]></category>
            <category><![CDATA[autoboxing]]></category>
            <category><![CDATA[integer]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[wrapper]]></category>
            <dc:creator><![CDATA[Full Stack Developer]]></dc:creator>
            <pubDate>Wed, 19 Nov 2025 17:22:03 GMT</pubDate>
            <atom:updated>2025-11-19T17:22:03.468Z</atom:updated>
            <content:encoded><![CDATA[<p>You think you know this but read the 3rd print statement :) And no, you don’t have to read the whole article lol. Ok so, here’s a puzzle that makes even experienced Java developers question everything:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kThPuaqNjXLIUHGv" /><figcaption>Photo by <a href="https://unsplash.com/@silverkblack?utm_source=medium&amp;utm_medium=referral">Vitaly Gariev</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><pre>Integer a = 1000;<br>Integer b = 1000;<br><br>System.out.println(a == b);        // false - makes sense<br>System.out.println(a.equals(b));   // true - obviously<br>System.out.println(a == b + 0);    // true - WAIT, WHAT?!</pre><p>How does adding zero suddenly make them equal? Welcome to the wild world of <strong>autoboxing</strong> — where Java secretly changes your types behind your back hahaha</p><h3>The Plot Twist</h3><p>That innocent b + 0 triggers a chain reaction:</p><ol><li>Java sees math happening</li><li>“Can’t do math with objects!” it thinks</li><li><strong>Unboxes</strong> b from Integer to int (1000)</li><li>Adds zero: 1000 + 0 = 1000</li><li><strong>Unboxes</strong> a to compare: 1000 == 1000</li><li>Returns true!</li></ol><p>So a == b + 0 actually becomes 1000 == 1000 (primitive comparison), not object comparison!</p><h3>The Integer Cache Conspiracy</h3><p>But wait, there’s more weirdness:</p><pre>Integer x = 127;<br>Integer y = 127;<br>System.out.println(x == y);  // true<br><br>Integer m = 128;<br>Integer n = 128;<br>System.out.println(m == n);  // false</pre><p><strong>What sorcery is this? (Yes, we all know it, but for those who don’t know, here-)</strong></p><p>Java caches Integer objects from <strong>-128 to 127</strong>. So small numbers share the same object, but bigger numbers don&#39;t!</p><pre>Integer a = 100;  // Returns cached object<br>Integer b = 100;  // Returns SAME cached object<br>// a == b is true<br><br>Integer c = 200;  // Creates new object<br>Integer d = 200;  // Creates DIFFERENT new object  <br>// c == d is false</pre><h3>Autoboxing in Action</h3><p><strong>Boxing</strong> (primitive → wrapper):</p><pre>Integer num = 42;  // Auto-boxes int to Integer<br><br>// Actually: Integer num = Integer.valueOf(42);</pre><p><strong>Unboxing</strong> (wrapper → primitive):</p><pre>int value = num;  // Auto-unboxes Integer to int<br><br>// Actually: int value = num.intValue();</pre><p><strong>In expressions</strong> (the sneaky part):</p><pre>Integer a = 1000;<br>Integer b = 1000;<br><br>// Any math operation triggers unboxing<br>System.out.println(a + b);      // Unboxes both, adds, returns int 2000<br>System.out.println(a * 2);      // Unboxes a, multiplies, returns int 2000<br>System.out.println(a &gt; b);      // Unboxes both, compares primitives<br>System.out.println(a == b + 0); // Unboxes both, compares primitives (true!)</pre><h3>The Gotchas</h3><p><strong>1. NullPointerException surprise:</strong></p><pre>Integer num = null;<br><br>int value = num;  // NullPointerException during unboxing!</pre><p><strong>2. Performance trap:</strong></p><pre>// Terrible - boxes/unboxes in every iteration<br><br>Integer sum = 0;<br>for (int i = 0; i &lt; 1000; i++) {<br>    sum += i;  // Unbox sum, add, box result, repeat!<br>}<br><br>// Better - stay primitive<br><br>int sum = 0;<br>for (int i = 0; i &lt; 1000; i++) {<br>    sum += i;  // Pure primitive math<br>}</pre><p><strong>3. Comparison confusion:</strong></p><pre>Integer a = 1000;<br>Integer b = 1000;<br><br>a == b           // false - different objects<br>a.equals(b)      // true - same value<br>a == b + 0       // true - both unboxed to primitives!<br>a.intValue() == b.intValue()  // true - explicit unboxing</pre><h3>The Rules of Thumb</h3><p><strong>-&gt; Use primitives</strong> (int, double) for math and loops<br> -&gt; <strong>Use wrappers</strong> (Integer, Double) only when you need objects (collections, nullability)<br> -&gt; <strong>Always use </strong><strong>equals()</strong> for wrapper comparisons<br> -&gt; <strong>Watch out for null</strong> - unboxing null = *$%#%^</p><h3>The Mind-Bender Explained</h3><p>Back to our original puzzle:</p><pre>Integer a = 1000;<br>Integer b = 1000;<br><br>a == b        // Compares references → false (different objects)<br>a.equals(b)   // Compares values → true (both are 1000)<br>a == b + 0    // Unboxes to primitives → true (1000 == 1000)</pre><p>The + 0 forces Java to treat them as primitives, not objects. It&#39;s like asking &quot;are these the same box?&quot; vs &quot;do these boxes contain the same thing?&quot;</p><h3>The Bottom Line</h3><p>Autoboxing is Java’s attempt to make primitives and wrappers play nice together. It works great… until it doesn’t.</p><p>The magic happens automatically, but <strong>you</strong> need to remember:</p><ul><li>Math operations trigger unboxing</li><li>Comparisons with == on wrappers compare references (unless unboxing happens)</li><li>The cache makes small numbers behave differently than large ones</li></ul><p>Next time someone asks why a == b + 0 is true but a == b is false, you can smugly explain: &quot;Ah, autoboxing strikes again!&quot; :P</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5d2bc64f87d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Erasure: Java’s Generics Magic Trick (That’s Actually a Lie)]]></title>
            <link>https://medium.com/@ByteCodeBlogger/type-erasure-javas-generics-magic-trick-that-s-actually-a-lie-d9c50023b3a1?source=rss-d9bf18529541------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9c50023b3a1</guid>
            <category><![CDATA[type-erasure]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-generic]]></category>
            <category><![CDATA[java-interview]]></category>
            <dc:creator><![CDATA[Full Stack Developer]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 17:03:01 GMT</pubDate>
            <atom:updated>2025-11-18T17:03:01.432Z</atom:updated>
            <content:encoded><![CDATA[<p>I ask for output in interviews to check the candidates knowledge, but they don’t NEED to know it! Its just tricky &amp; fun! So, here’s a mind-bending fact: Your generic types don’t actually exist at runtime. Java is basically gaslighting you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9zI_FIs2bidEypmc" /><figcaption>Photo by <a href="https://unsplash.com/@tengyart?utm_source=medium&amp;utm_medium=referral">Олег Мороз</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Shocking Truth</h3><p>Check this out:</p><pre>List&lt;String&gt; strings = new ArrayList&lt;&gt;();<br>List&lt;Integer&gt; integers = new ArrayList&lt;&gt;();<br><br>System.out.println(strings.getClass() == integers.getClass());<br><br>// Prints: true (Wait, WHAT?!)</pre><p>Both are just ArrayList at runtime. The &lt;String&gt; and &lt;Integer&gt; parts? Gone. Vanished. Erased.</p><p>Welcome to <strong>Type Erasure</strong> — Java’s way of pretending generics exist while secretly throwing them away.</p><h3>What Actually Happens</h3><p>When you write this:</p><pre>public class Box&lt;T&gt; {<br>    private T item;<br>    <br>    public void set(T item) {<br>        this.item = item;<br>    }<br>    <br>    public T get() {<br>        return item;<br>    }<br>}</pre><p>Java compiles it to this:</p><pre>public class Box {<br>    private Object item;  // T becomes Object!<br>    <br>    public void set(Object item) {<br>        this.item = item;<br>    }<br>    <br>    public Object get() {<br>        return item;<br>    }<br>}</pre><p>Your fancy &lt;T&gt; just becomes boring old Object. The compiler adds invisible casts everywhere to make it work.</p><h3>Why This Madness?</h3><p><strong>Backward compatibility.</strong> When Java 5 added generics in 2004, millions of lines of pre-generic code existed. Type erasure let old and new code play nice together without breaking the internet.</p><pre>// Old code (pre-Java 5)<br><br>List oldList = new ArrayList();<br><br>// New code (Java 5+)<br><br>List&lt;String&gt; newList = new ArrayList&lt;&gt;();<br><br>// They can still talk to each other!<br>oldList = newList;  // Works (with a warning)</pre><h3>The Annoying Limitations</h3><p><strong>1. Can’t create instances of generic types:</strong></p><pre>public class Container&lt;T&gt; {<br>    T instance = new T();  // Nope! T is just Object at runtime<br>}</pre><p><strong>2. Can’t create generic arrays:</strong></p><pre>List&lt;String&gt;[] arrayOfLists = new List&lt;String&gt;[10];  // Compilation error</pre><p><strong>3. Can’t use primitives:</strong></p><pre>List&lt;int&gt; numbers = new ArrayList&lt;&gt;();  // Must use List&lt;Integer&gt;</pre><p><strong>4. Can’t check types at runtime:</strong></p><pre>if (obj instanceof List&lt;String&gt;) { }  // Can&#39;t check, it&#39;s erased!</pre><h3>The Workarounds</h3><p><strong>Need to create instances? Pass the class:</strong></p><pre>public class Container&lt;T&gt; {<br>    private T instance;<br>    <br>    public Container(Class&lt;T&gt; type) throws Exception {<br>        instance = type.getDeclaredConstructor().newInstance();<br>    }<br>}<br><br>// Usage<br>Container&lt;String&gt; box = new Container&lt;&gt;(String.class);</pre><p><strong>Need runtime type info? Use Type Tokens:</strong></p><pre>// This is how libraries like Gson work<br>TypeReference&lt;List&lt;String&gt;&gt; typeRef = new TypeReference&lt;List&lt;String&gt;&gt;() {};</pre><h3>The Silver Lining</h3><p>Type erasure isn’t all bad:</p><p>-&gt; <strong>No runtime overhead</strong> — no type checking at runtime means faster code<br> -&gt; <strong>Smaller bytecode</strong> — one class instead of multiple versions<br> -&gt; <strong>Works with legacy code</strong> — your grandpa’s Java code still runs</p><h3>The Bottom Line</h3><p>Java’s generics are a <strong>compile-time safety net</strong> that disappears at runtime. Think of them as training wheels that get removed before the race.</p><p>The compiler uses generics to catch your mistakes early, then erases them and trusts you got it right. It’s like your code goes to a fancy prep school (compile time) but ends up working at the same factory as everyone else (runtime).</p><p>So next time someone asks why you can’t do new T() or instanceof List&lt;String&gt;, you can smile knowingly and say: &quot;Ah, type erasure, my old friend...&quot;</p><p><strong>Pro tip:</strong> Just use equals() for comparisons, avoid raw types, and let the compiler do the heavy lifting. The less you fight type erasure, the happier you&#39;ll be! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9c50023b3a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Secret Life of Strings: Java’s Pool Party]]></title>
            <link>https://medium.com/@ByteCodeBlogger/the-secret-life-of-strings-javas-pool-party-e512426aa64f?source=rss-d9bf18529541------2</link>
            <guid isPermaLink="false">https://medium.com/p/e512426aa64f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[intern-string]]></category>
            <category><![CDATA[java-interview]]></category>
            <category><![CDATA[string-pool]]></category>
            <category><![CDATA[string]]></category>
            <dc:creator><![CDATA[Full Stack Developer]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 10:18:30 GMT</pubDate>
            <atom:updated>2025-11-17T10:18:30.793Z</atom:updated>
            <content:encoded><![CDATA[<p>Yes I am referencing “String Pool” :P All jokes aside, this one is for beginners and experienced folks who need a refresher. This might help with your interview prep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i4rctX3lmk8rTWy4" /><figcaption>Photo by <a href="https://unsplash.com/@les_photos_de_raph?utm_source=medium&amp;utm_medium=referral">Raphaël Biscaldi</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever wondered why your Java strings sometimes behave like identical twins and other times like complete strangers? Welcome to the world of <strong>String Interning</strong> and the <strong>String Pool</strong> — Java’s behind-the-scenes memory optimization that’s been quietly saving RAM since the beginning.</p><h3>The Mystery of the Identical Strings</h3><p>Let’s start with a puzzle that confuses every Java developer at least once:</p><pre>String greeting1 = &quot;Hello&quot;;<br>String greeting2 = &quot;Hello&quot;;<br>String greeting3 = new String(&quot;Hello&quot;);<br><br>System.out.println(greeting1 == greeting2);  // true - Wait, what?!<br><br>System.out.println(greeting1 == greeting3);  // false - This makes sense<br><br>System.out.println(greeting1.equals(greeting3)); // true - Of course</pre><p>If you’ve been told “never use == for strings,&quot; you&#39;re probably scratching your head at that first comparison. <strong>How can </strong><strong>== return </strong><strong>true when it checks reference equality, not content</strong>?</p><p><strong>Well, t</strong>hey’re literally the same object in memory!</p><h3>Welcome to the String Pool</h3><p>Think of the String Pool as an exclusive VIP lounge in Java’s memory heap. When you create a string literal (like &quot;Hello&quot;), Java doesn&#39;t just throw it anywhere. Instead, it follows a clever protocol:</p><ol><li><strong>Check the guest list</strong>: “Is ‘Hello’ already in the pool?”</li><li><strong>If yes</strong>: “Great! Here’s the reference to the existing one.”</li><li><strong>If no</strong>: “Let me add it to the pool and give you the reference.”</li></ol><p>This is why greeting1 and greeting2 point to the exact same object – they&#39;re both references to the single &quot;Hello&quot; instance living in the String Pool.</p><pre>// Visualizing the String Pool<br>String Pool: [&quot;Hello&quot;, &quot;World&quot;, &quot;Java&quot;, ...]<br>              ↑<br>              |<br>greeting1 ----+---- greeting2  // Both point here!</pre><h3>The new Keyword: The Party Crasher</h3><p>Now, what about greeting3 = new String(&quot;Hello&quot;)?</p><p>When you use the new keyword, you&#39;re explicitly telling Java: <em>&quot;I don&#39;t care about your fancy pool, create me a brand new object in the regular heap!&quot;</em></p><pre>String Pool: [&quot;Hello&quot;]<br>              ↑<br>              |<br>greeting1 ----+<br><br><br>Regular Heap: [String object: &quot;Hello&quot;]<br>               ↑<br>               |<br>greeting3 -----+</pre><p>This creates <strong>two</strong> objects:</p><ul><li>One in the String Pool (from the literal &quot;Hello&quot;)</li><li>One in the regular heap (from new String())</li></ul><p>That’s why greeting1 == greeting3 returns false – they&#39;re different objects in different memory locations!</p><h3>The Magic Method: intern()</h3><p>But wait, there’s more! Java gives you a secret handshake to get into the String Pool club: the intern() method.</p><pre>String s1 = &quot;Hello&quot;;<br>String s2 = new String(&quot;Hello&quot;);<br>String s3 = s2.intern();<br><br>System.out.println(s1 == s2);  // false - different objects<br><br>System.out.println(s1 == s3);  // true - s3 now references the pool!</pre><p>When you call intern() on a string:</p><ul><li>If the string exists in the pool → returns the pool reference</li><li>If not → adds it to the pool and returns that reference</li></ul><p>It’s like saying, “Hey, can I join the VIP club?” and Java either lets you in or gives you the membership card of someone already inside.</p><h3>Why Does This Matter? The Performance Story</h3><p><strong>Memory Savings</strong>: Imagine an application with thousands of “SUCCESS”, “ERROR”, “PENDING” strings. Without the String Pool, you’d have thousands of duplicate objects. With it? Just three objects, referenced thousands of times.</p><pre>// Without String Pool (hypothetical)<br>Memory: [&quot;SUCCESS&quot;, &quot;SUCCESS&quot;, &quot;SUCCESS&quot;, ...] // 1000 objects<br><br>// With String Pool (reality)<br>String Pool: [&quot;SUCCESS&quot;]  // 1 object, 1000 references</pre><p><strong>Speed Boost</strong>: <strong>String comparison becomes lightning fast when you can use </strong><strong>== instead of </strong><strong>equals() for interned strings !!!</strong></p><h3>The Gotchas: When the Pool Bites Back</h3><h3>Gotcha #1: Concatenation Creates New Objects</h3><pre>String s1 = &quot;Hello&quot;;<br>String s2 = &quot;Hello&quot;;<br>String s3 = &quot;Hel&quot; + &quot;lo&quot;;  // Compile-time constant<br>String s4 = new String(&quot;Hel&quot;) + &quot;lo&quot;;  // Runtime concatenation<br><br>System.out.println(s1 == s2);  // true<br>System.out.println(s1 == s3);  // true - compiler optimizes!<br>System.out.println(s1 == s4);  // false - created at runtime</pre><h3>Gotcha #2: The Pool Lives in PermGen/Metaspace</h3><p>Before Java 7, the String Pool lived in PermGen (limited space). Too many unique strings? OutOfMemoryError!</p><p>Since Java 7, it moved to the main heap, but you can still run into issues with excessive interning.</p><pre>// Don&#39;t do this!<br>for (int i = 0; i &lt; 1_000_000; i++) {<br>    String.valueOf(i).intern();  // Polluting the pool!<br>}</pre><h3>Gotcha #3: Security Concerns</h3><p>Interned strings stick around for the lifetime of the JVM. Sensitive data (passwords, tokens) should <strong>never</strong> be interned:</p><pre>// BAD - password stays in memory forever!<br>String password = userInput.intern();<br><br>// GOOD - use char[] and clear it<br>char[] password = getPassword();<br>// ... use it ...<br>Arrays.fill(password, &#39; &#39;);  // Clear it</pre><h3>Real-World Use Cases</h3><p><strong>1. Configuration Keys</strong></p><pre>public class Config {<br>    private static final String DB_HOST = &quot;database.host&quot;;<br>    private static final String DB_PORT = &quot;database.port&quot;;<br>    // These are automatically interned - perfect!<br>}</pre><p><strong>2. Enum-like String Constants</strong></p><pre>public class Status {<br>    public static final String ACTIVE = &quot;ACTIVE&quot;;<br>    public static final String INACTIVE = &quot;INACTIVE&quot;;<br>    // Interned and memory-efficient<br>}</pre><p><strong>3. Parsing Repeated Values</strong></p><pre>// Reading CSV with repeated values<br>String status = csvValue.intern();  // &quot;ACTIVE&quot; appears 10,000 times<br>// Now all 10,000 references point to one object!</pre><h3>The Bottom Line</h3><p>The String Pool is Java’s clever way of saying, “Why store the same thing twice?” It’s an automatic optimization that:</p><p>-&gt; Saves memory by reusing identical string literals<br>-&gt; Speeds up comparisons when used correctly<br>-&gt; Works transparently for string literals</p><p>But remember:</p><ul><li>Use equals() for string comparison in general code</li><li>Use == only when you&#39;re certain both strings are interned</li><li>Don’t intern user input or dynamic strings unnecessarily</li><li>Never intern sensitive data</li></ul><p>Hope you learnt something new :) Please comment if you liked reading this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e512426aa64f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing AI in Java: Read if you are interested in latest Java-AI space]]></title>
            <link>https://medium.com/@ByteCodeBlogger/implementing-ai-in-java-read-if-you-are-interested-in-latest-java-ai-space-e21158c8da15?source=rss-d9bf18529541------2</link>
            <guid isPermaLink="false">https://medium.com/p/e21158c8da15</guid>
            <category><![CDATA[ai-ml-java]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-23]]></category>
            <category><![CDATA[javaai]]></category>
            <category><![CDATA[aiinjava]]></category>
            <dc:creator><![CDATA[Full Stack Developer]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 16:28:17 GMT</pubDate>
            <atom:updated>2025-11-06T16:28:17.303Z</atom:updated>
            <content:encoded><![CDATA[<p>Whether you’re building chatbots, recommendation systems, or computer vision applications, Java provides robust tools to bring AI capabilities to your applications. Let’s look at that in this article!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*riBGFPatT27H9lul" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Choose Java for AI Development?</h3><ul><li><strong>Enterprise Integration</strong>: Seamlessly integrates with existing Java enterprise applications</li><li><strong>Platform Independence</strong>: Write once, run anywhere — perfect for distributed AI systems</li><li><strong>Performance</strong>: JVM optimizations and garbage collection make it suitable for production AI workloads</li><li><strong>Ecosystem</strong>: Vast library ecosystem and strong community support</li><li><strong>Scalability</strong>: Built-in concurrency and threading capabilities for handling multiple AI requests</li></ul><h3>Core Approaches to AI in Java</h3><h3>1. Cloud-Based AI Services Integration</h3><ul><li><strong>Pros</strong>: No model training required, always up-to-date, enterprise-grade reliability</li><li><strong>Cons</strong>: Internet dependency, ongoing costs, data privacy considerations</li><li><strong>Best For</strong>: Rapid prototyping, applications requiring latest AI capabilities</li></ul><h3>2. Embedded Machine Learning Libraries</h3><ul><li><strong>Pros</strong>: Offline operation, data privacy, predictable costs</li><li><strong>Cons</strong>: Model management overhead, limited to pre-trained models</li><li><strong>Best For</strong>: Edge computing, sensitive data processing, high-volume applications</li></ul><h3>3. Hybrid AI Architecture</h3><ul><li><strong>Pros</strong>: Combines benefits of both approaches, flexible deployment options</li><li><strong>Cons</strong>: Increased complexity, multiple failure points</li><li><strong>Best For</strong>: Enterprise applications requiring both speed and advanced capabilities</li></ul><h3>Essential Java AI Libraries and Frameworks</h3><h3>Deep Learning Frameworks</h3><h4>Deeplearning4j (DL4J)</h4><p><strong>Specialty</strong>: Enterprise-focused deep learning with Spark integration</p><p><strong>Key Features</strong>:</p><ul><li>Native Java implementation (no Python dependencies)</li><li>GPU acceleration support via CUDA</li><li>Integration with Hadoop and Spark for big data processing</li><li>Pre-built neural network architectures (CNN, RNN, LSTM)</li></ul><p><strong>Use Cases</strong>: Image recognition, natural language processing, time series analysis</p><p><strong>Learning Curve</strong>: Moderate to steep</p><p><strong>Performance</strong>: Excellent for production environments</p><h4>ONNX Runtime for Java</h4><p><strong>Specialty</strong>: Cross-platform inference engine for pre-trained models</p><p><strong>Key Features</strong>:</p><ul><li>Supports models from PyTorch, TensorFlow, scikit-learn</li><li>Optimized inference performance</li><li>Hardware acceleration (CPU, GPU, specialized chips)</li><li>Model format standardization</li></ul><p><strong>Use Cases</strong>: Deploying models trained in other frameworks</p><p><strong>Learning Curve</strong>: Easy to moderate</p><p><strong>Performance</strong>: Highly optimized for inference</p><h3>Traditional Machine Learning</h3><h4>Weka (Waikato Environment for Knowledge Analysis)</h4><p><strong>Specialty</strong>: Comprehensive machine learning workbench</p><p><strong>Key Features</strong>:</p><ul><li>200+ built-in algorithms for classification, regression, clustering</li><li>Visual data exploration and model evaluation tools</li><li>Easy-to-use GUI and programmatic API</li><li>Extensive data preprocessing capabilities</li></ul><p><strong>Use Cases</strong>: Data mining, academic research, rapid prototyping</p><p><strong>Learning Curve</strong>: Easy to moderate</p><p><strong>Performance</strong>: Good for small to medium datasets</p><h4>Apache Mahout</h4><p><strong>Specialty</strong>: Scalable machine learning for big data</p><p><strong>Key Features</strong>:</p><ul><li>Distributed algorithms running on Hadoop/Spark</li><li>Focus on collaborative filtering and clustering</li><li>Linear algebra operations optimized for large datasets</li><li>Integration with Apache ecosystem</li></ul><p><strong>Use Cases</strong>: Recommendation systems, large-scale data analysis</p><p><strong>Learning Curve</strong>: Moderate to steep</p><p><strong>Performance</strong>: Excellent for big data scenarios</p><h3>Natural Language Processing</h3><h4>Apache OpenNLP</h4><p><strong>Specialty</strong>: Natural language processing toolkit</p><p><strong>Key Features</strong>:</p><ul><li>Tokenization, sentence segmentation, POS tagging</li><li>Named entity recognition and parsing</li><li>Pre-trained models for multiple languages</li><li>Document classification capabilities</li></ul><p><strong>Use Cases</strong>: Text analysis, chatbots, content categorization</p><p><strong>Learning Curve</strong>: Easy to moderate</p><p><strong>Performance</strong>: Good for most NLP tasks</p><h4>Stanford CoreNLP</h4><p><strong>Specialty</strong>: Advanced linguistic analysis toolkit</p><p><strong>Key Features</strong>:</p><ul><li>Dependency parsing and coreference resolution</li><li>Sentiment analysis and relation extraction</li><li>Multi-language support</li><li>Integration with neural network models</li></ul><p><strong>Use Cases</strong>: Advanced text analytics, research applications</p><p><strong>Learning Curve</strong>: Moderate</p><p><strong>Performance</strong>: High accuracy for complex NLP tasks</p><h3>Computer Vision</h3><h4>OpenCV for Java</h4><p><strong>Specialty</strong>: Computer vision and image processing</p><p><strong>Key Features</strong>:</p><ul><li>Image filtering, transformation, and feature detection</li><li>Object detection and tracking algorithms</li><li>Machine learning modules for image classification</li><li>Real-time video processing capabilities</li></ul><p><strong>Use Cases</strong>: Image analysis, video processing, augmented reality</p><p><strong>Learning Curve</strong>: Moderate to steep</p><p><strong>Performance</strong>: Excellent for real-time applications</p><h3>Practical Implementation: Advanced Sentiment Analysis System</h3><p>Here’s a comprehensive example demonstrating multiple AI approaches in a single application:</p><pre>import java.net.http.HttpClient;<br>import java.net.http.HttpRequest;<br>import java.net.http.HttpResponse;<br>import java.net.URI;<br>import java.util.concurrent.CompletableFuture;<br>import java.util.concurrent.ConcurrentHashMap;<br>import java.util.Map;<br>import java.time.Duration;<br>import com.fasterxml.jackson.databind.ObjectMapper;<br>import com.fasterxml.jackson.databind.JsonNode;<br><br>public class AdvancedSentimentAnalyzer {<br>    private static final String OPENAI_API_URL = &quot;https://api.openai.com/v1/chat/completions&quot;;<br>    private static final String API_KEY = System.getenv(&quot;OPENAI_API_KEY&quot;);<br>    <br>    private final HttpClient httpClient;<br>    private final ObjectMapper objectMapper;<br>    private final Map&lt;String, SentimentResult&gt; cache;<br>    <br>    public AdvancedSentimentAnalyzer() {<br>        this.httpClient = HttpClient.newBuilder()<br>                .connectTimeout(Duration.ofSeconds(10))<br>                .build();<br>        this.objectMapper = new ObjectMapper();<br>        this.cache = new ConcurrentHashMap&lt;&gt;();<br>    }<br>    <br>    // Async sentiment analysis with caching<br>    public CompletableFuture&lt;SentimentResult&gt; analyzeSentimentAsync(String text) {<br>        // Check cache first<br>        String cacheKey = text.toLowerCase().trim();<br>        if (cache.containsKey(cacheKey)) {<br>            return CompletableFuture.completedFuture(cache.get(cacheKey));<br>        }<br>        <br>        return CompletableFuture.supplyAsync(() -&gt; {<br>            try {<br>                return performSentimentAnalysis(text);<br>            } catch (Exception e) {<br>                throw new RuntimeException(&quot;Sentiment analysis failed&quot;, e);<br>            }<br>        }).thenApply(result -&gt; {<br>            cache.put(cacheKey, result);<br>            return result;<br>        });<br>    }<br>    <br>    private SentimentResult performSentimentAnalysis(String text) throws Exception {<br>        String requestBody = createRequestBody(text);<br>        <br>        HttpRequest request = HttpRequest.newBuilder()<br>                .uri(URI.create(OPENAI_API_URL))<br>                .header(&quot;Authorization&quot;, &quot;Bearer &quot; + API_KEY)<br>                .header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>                .timeout(Duration.ofSeconds(30))<br>                .POST(HttpRequest.BodyPublishers.ofString(requestBody))<br>                .build();<br>        <br>        HttpResponse&lt;String&gt; response = httpClient.send(request, <br>                HttpResponse.BodyHandlers.ofString());<br>        <br>        if (response.statusCode() != 200) {<br>            throw new RuntimeException(&quot;API request failed: &quot; + response.statusCode());<br>        }<br>        <br>        return parseSentimentResponse(response.body());<br>    }<br>    <br>    private String createRequestBody(String text) {<br>        return String.format(&quot;&quot;&quot;<br>            {<br>                &quot;model&quot;: &quot;gpt-3.5-turbo&quot;,<br>                &quot;messages&quot;: [<br>                    {<br>                        &quot;role&quot;: &quot;system&quot;,<br>                        &quot;content&quot;: &quot;You are a sentiment analysis expert. Analyze text and respond with JSON containing &#39;sentiment&#39; (positive/negative/neutral) and &#39;confidence&#39; (0.0-1.0).&quot;<br>                    },<br>                    {<br>                        &quot;role&quot;: &quot;user&quot;,<br>                        &quot;content&quot;: &quot;Analyze: %s&quot;<br>                    }<br>                ],<br>                &quot;max_tokens&quot;: 50,<br>                &quot;temperature&quot;: 0.1<br>            }<br>            &quot;&quot;&quot;, text.replace(&quot;\&quot;&quot;, &quot;\\\&quot;&quot;));<br>    }<br>    <br>    private SentimentResult parseSentimentResponse(String responseBody) throws Exception {<br>        JsonNode jsonResponse = objectMapper.readTree(responseBody);<br>        String content = jsonResponse.path(&quot;choices&quot;).get(0)<br>                .path(&quot;message&quot;).path(&quot;content&quot;).asText();<br>        <br>        // Parse JSON response from AI<br>        JsonNode sentimentData = objectMapper.readTree(content);<br>        String sentiment = sentimentData.path(&quot;sentiment&quot;).asText();<br>        double confidence = sentimentData.path(&quot;confidence&quot;).asDouble();<br>        <br>        return new SentimentResult(sentiment, confidence, System.currentTimeMillis());<br>    }<br>    <br>    // Batch processing for multiple texts<br>    public CompletableFuture&lt;Map&lt;String, SentimentResult&gt;&gt; analyzeBatch(String[] texts) {<br>        CompletableFuture&lt;SentimentResult&gt;[] futures = new CompletableFuture[texts.length];<br>        <br>        for (int i = 0; i &lt; texts.length; i++) {<br>            futures[i] = analyzeSentimentAsync(texts[i]);<br>        }<br>        <br>        return CompletableFuture.allOf(futures).thenApply(v -&gt; {<br>            Map&lt;String, SentimentResult&gt; results = new ConcurrentHashMap&lt;&gt;();<br>            for (int i = 0; i &lt; texts.length; i++) {<br>                try {<br>                    results.put(texts[i], futures[i].get());<br>                } catch (Exception e) {<br>                    results.put(texts[i], new SentimentResult(&quot;error&quot;, 0.0, System.currentTimeMillis()));<br>                }<br>            }<br>            return results;<br>        });<br>    }<br>    <br>    // Data class for sentiment results<br>    public static class SentimentResult {<br>        private final String sentiment;<br>        private final double confidence;<br>        private final long timestamp;<br>        <br>        public SentimentResult(String sentiment, double confidence, long timestamp) {<br>            this.sentiment = sentiment;<br>            this.confidence = confidence;<br>            this.timestamp = timestamp;<br>        }<br>        <br>        // Getters<br>        public String getSentiment() { return sentiment; }<br>        public double getConfidence() { return confidence; }<br>        public long getTimestamp() { return timestamp; }<br>        <br>        @Override<br>        public String toString() {<br>            return String.format(&quot;Sentiment: %s (%.2f confidence)&quot;, sentiment, confidence);<br>        }<br>    }<br>    <br>    public static void main(String[] args) {<br>        AdvancedSentimentAnalyzer analyzer = new AdvancedSentimentAnalyzer();<br>        <br>        // Single analysis<br>        analyzer.analyzeSentimentAsync(&quot;I absolutely love this new Java AI framework!&quot;)<br>                .thenAccept(result -&gt; System.out.println(&quot;Single: &quot; + result))<br>                .exceptionally(throwable -&gt; {<br>                    System.err.println(&quot;Error: &quot; + throwable.getMessage());<br>                    return null;<br>                });<br>        <br>        // Batch analysis<br>        String[] texts = {<br>            &quot;This is amazing!&quot;,<br>            &quot;I hate waiting in long queues.&quot;,<br>            &quot;The weather is okay today.&quot;,<br>            &quot;Java makes AI development so much easier!&quot;<br>        };<br>        <br>        analyzer.analyzeBatch(texts)<br>                .thenAccept(results -&gt; {<br>                    System.out.println(&quot;\nBatch Results:&quot;);<br>                    results.forEach((text, result) -&gt; <br>                        System.out.println(text + &quot; -&gt; &quot; + result));<br>                })<br>                .join(); // Wait for completion<br>    }<br>}</pre><h3>Choosing the Right Approach</h3><h3>For Startups and Rapid Prototyping</h3><ul><li>Start with cloud-based APIs (OpenAI, Google AI, AWS)</li><li>Focus on integration speed over custom model development</li><li>Use managed services to minimize infrastructure overhead</li></ul><h3>For Enterprise Applications</h3><ul><li>Consider Deeplearning4j for custom model development</li><li>Implement hybrid approaches for flexibility and compliance</li><li>Invest in proper monitoring and observability tools</li></ul><h3>For Edge and IoT Applications</h3><ul><li>Use ONNX Runtime for optimized inference</li><li>Consider model quantization for resource-constrained environments</li><li>Implement offline-first architectures with cloud synchronization</li></ul><h3>For Research and Academia</h3><ul><li>Leverage Weka for exploratory data analysis</li><li>Use Stanford CoreNLP for advanced linguistic research</li><li>Combine multiple frameworks for comprehensive analysis</li></ul><p>Hope this helps you! Drop a comment if you use/ have used any of this :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e21158c8da15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Generics and Wildcards in Java: ?, ? extends, and ? super]]></title>
            <link>https://medium.com/@ByteCodeBlogger/understanding-generics-and-wildcards-in-java-extends-and-super-c14e61faac52?source=rss-d9bf18529541------2</link>
            <guid isPermaLink="false">https://medium.com/p/c14e61faac52</guid>
            <category><![CDATA[java-23]]></category>
            <category><![CDATA[java-generic]]></category>
            <category><![CDATA[java-pecs-rule]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-type-safety]]></category>
            <dc:creator><![CDATA[Full Stack Developer]]></dc:creator>
            <pubDate>Thu, 30 Oct 2025 16:04:08 GMT</pubDate>
            <atom:updated>2025-10-30T16:04:08.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Generics and Wildcards in Java: ?, ? extends, and ? super</h3><p>Let’s see how ?, ? extends, and ? super work in Java!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSufNa6Tws0INBsp" /><figcaption>Photo by <a href="https://unsplash.com/@heyitst0m?utm_source=medium&amp;utm_medium=referral">Tom Dillon</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Generics were introduced in Java to bring type safety and reduce the number of ClassCastException issues at runtime.</p><p>They allow you to write classes, interfaces, and methods that operate on types specified later. However, while using generics, most developers encounter a point where they need flexibility in what types they can accept. This is where wildcards come into the picture.</p><blockquote>Wildcard in Java generics is represented by a question mark (?). It acts as a placeholder for an unknown type.</blockquote><p>But there is more nuance to it. Sometimes, you want the unknown type to be restricted — maybe it must be a subtype or a supertype of a particular class. To express these boundaries, Java provides:</p><ul><li>? (Unbounded wildcard)</li><li>? extends T (Upper bounded wildcard)</li><li>? super T (Lower bounded wildcard)</li></ul><p>Understanding the purpose and use of each helps avoid confusion and improves the flexibility and correctness of your code.</p><h3>1. Unbounded Wildcard: ?</h3><p>? is used when you do not care what the actual type parameter is. It simply represents “some type.”</p><p>Example:</p><pre>public void printList(List&lt;?&gt; list) {<br><br>    for (Object item : list) {<br><br>        System.out.println(item);<br>    }<br>}</pre><p>This method can accept a list of any type. You can read from the list, but you cannot add anything to it (except null) because the compiler does not know the actual type stored inside.</p><blockquote>Use an unbounded wildcard when your code only needs to <strong>read</strong> values and will not modify the collection.</blockquote><h3>2. Upper Bounded Wildcard: ? extends T</h3><p>? extends T means the unknown type is T or any subclass of T. This is useful when you want to <strong>read</strong> elements and treat them all as type T.</p><p>Example:</p><pre>public double sum(List&lt;? extends Number&gt; numbers) {<br><br>    double total = 0.0;<br><br>    for (Number n : numbers) {<br><br>        total += n.doubleValue();<br>    }<br><br>    return total;<br>}</pre><p>This can accept lists like List&lt;Integer&gt;, List&lt;Double&gt;, or List&lt;Float&gt; because they all extend Number.</p><p>However, you cannot safely add new elements to such a list because the compiler cannot tell which specific subtype it is.</p><blockquote>Use ? extends when your code only <strong>retrieves</strong> items.</blockquote><h3>3. Lower Bounded Wildcard: ? super T</h3><p>? super T means the unknown type is T or any <strong>superclass</strong> of T. This is used when you want to <strong>add</strong> elements to the collection.</p><p>Example:</p><pre>public void addIntegers(List&lt;? super Integer&gt; list) {<br>    list.add(10);<br>    list.add(20);<br>}</pre><p>This method can accept lists like List&lt;Integer&gt;, List&lt;Number&gt;, or List&lt;Object&gt;. All of them are capable of storing Integer values.</p><p>But when reading from the list, the type you get back will be Object because the compiler cannot know the precise type.</p><blockquote>Use ? super when your code <strong>inserts</strong> items.</blockquote><h3>The PECS Rule</h3><p>A simple rule to remember when choosing between extends and super is:</p><p><strong>PECS: Producer Extends, Consumer Super</strong></p><ul><li>If the object <strong>produces</strong> data for you to read, use ? extends.</li><li>If the object <strong>consumes</strong> data you provide (you want to write to it), use ? super.</li></ul><h3>Summary</h3><p>Think of the wildcards this way:</p><ul><li>Use <strong>?</strong> when you do not care about the type and are only going to <strong>look at</strong> the elements.</li><li>Use <strong>? extends T</strong> when you want to <strong>read</strong> elements as type T.</li><li>Use <strong>? super T</strong> when you want to <strong>add</strong> elements of type T.</li></ul><p>In short:</p><ul><li><strong>Read = extends</strong></li><li><strong>Write = super</strong></li><li><strong>Unknown = only read, no write</strong></li></ul><p>Generics and wildcards help Java maintain type safety while remaining flexible. When used correctly, they lead to cleaner, reusable, and more robust code.</p><p>Understanding these concepts deeply will make your work with Java collections significantly clearer and more predictable. Hope this helps!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c14e61faac52" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>