<?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 Satyam Singh on Medium]]></title>
        <description><![CDATA[Stories by Satyam Singh on Medium]]></description>
        <link>https://medium.com/@satyamror1109?source=rss-074f7c74c1b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Fx0rmKZwqEwqT2rC</url>
            <title>Stories by Satyam Singh on Medium</title>
            <link>https://medium.com/@satyamror1109?source=rss-074f7c74c1b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:24:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satyamror1109/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[How Does HashMap Work Internally in Java?]]></title>
            <link>https://medium.com/@satyamror1109/how-does-hashmap-work-internally-in-java-09dc3ed0e2b1?source=rss-074f7c74c1b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/09dc3ed0e2b1</guid>
            <dc:creator><![CDATA[Satyam Singh]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 06:15:20 GMT</pubDate>
            <atom:updated>2026-10-05T06:15:20.157Z</atom:updated>
            <content:encoded><![CDATA[<p>A HashMap lookup feels almost instant:</p><pre>Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();<br><br>map.put(&quot;A&quot;, 10);<br>map.get(&quot;A&quot;);</pre><p>But Java is not scanning every entry to find &quot;A&quot;.</p><p>It uses hashing to narrow the search down to a small bucket first, then uses equals() to locate the exact key.</p><p>That is what makes HashMap fast, and also why concepts like collisions, hashCode(), and resizing matter.</p><p><strong>The core idea is:</strong></p><blockquote><em>HashMap uses the key&#39;s </em><em>hashCode() to find a bucket, then uses </em><em>equals() to find the exact key inside that bucket.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFBqBiByKOkXEaXqDYylZA.png" /></figure><h3>1. Hashing: Finding the Bucket</h3><p>When we call:</p><pre>map.put(&quot;A&quot;, 10);</pre><p>Java gets the key’s hashCode().</p><p>That hash is then processed and converted into a bucket index.</p><p>Simplified:</p><pre>Key<br> ↓<br>hashCode()<br> ↓<br>hash<br> ↓<br>bucket index</pre><p>So instead of searching the entire map, HashMap first jumps directly to a smaller location called a <strong>bucket</strong>.</p><h3>2. What Is a Bucket?</h3><p>Internally, HashMap maintains an array of buckets.</p><p>You can imagine it like:</p><pre>Bucket 0<br>Bucket 1<br>Bucket 2<br>Bucket 3<br>...</pre><p>Each bucket can hold one or more entries.</p><p>An entry mainly contains:</p><pre>key<br>value<br><br>hash<br>next</pre><p>The next reference helps connect multiple entries stored in the same bucket.</p><h3>3. What Happens During a Collision?</h3><p>Different keys can sometimes end up in the same bucket.</p><pre>Key A → Bucket 5<br>Key B → Bucket 5</pre><p>This is called a <strong>collision</strong>.</p><p>HashMap does not throw away one of them.</p><p>It keeps both entries in the same bucket:</p><pre>Bucket 5</pre><pre>[A, 10] → [B, 20]</pre><p>When we call:</p><pre>map.get(key);</pre><p>HashMap first finds the bucket using hashCode().</p><p>Then it uses equals() to find the exact key inside that bucket.</p><p>So:</p><pre>hashCode() → where should I look?</pre><pre>equals()   → which exact key is mine?</pre><h3>4. Why Must equals() and hashCode() Agree?</h3><p>Java follows an important rule:</p><blockquote><em>If two objects are equal according to </em><em>equals(), they must return the same </em><em>hashCode()</em></blockquote><p>If they return different hashes, HashMap may search for them in different buckets.</p><p>That is why custom key classes should correctly implement both:</p><pre>equals()<br>hashCode()</pre><h3>5. Why Do Multiple Keys Keep Landing in the Same Bucket?</h3><p>A HashMap can contain a huge number of possible hash values, but it only has a limited number of buckets.</p><p>For example, imagine the map currently has:</p><pre>16 buckets</pre><p>Different keys may produce different hash values:</p><pre>Key A → hash 105<br>Key B → hash 809<br>Key C → hash 1545</pre><p>But HashMap must convert all of those hashes into bucket indexes between:</p><pre>0 to 15</pre><p>Because there are only 16 buckets.</p><p>So different hash values can eventually map to the <strong>same bucket</strong>.</p><p>For example:</p><pre>Key A → Bucket 5<br>Key B → Bucket 5<br>Key C → Bucket 5</pre><p>This is why collisions are normal.</p><p>They do not necessarily mean hashCode() is broken.</p><p>There are simply far more possible keys than available buckets.</p><p>But if too many entries keep landing in the same buckets, lookup starts becoming slower because HashMap has to compare more entries using equals().</p><p>So HashMap needs more buckets.</p><h3>6. This Is Where Load Factor Comes In</h3><p>The <strong>load factor</strong> tells HashMap when its internal bucket array is becoming too full.</p><p>The default load factor is:</p><pre>0.75</pre><p>Suppose the current capacity is:</p><pre>16 buckets</pre><p>Then the resize threshold is:</p><pre>16 × 0.75 = 12</pre><p>So once the number of entries crosses that threshold, HashMap increases its capacity.</p><p>Usually:</p><pre>16 buckets<br>    ↓<br>32 buckets</pre><p>This is called <strong>resizing</strong>.</p><p>Why does this help?</p><p>Because now the entries have more buckets available.</p><pre>Before:<br>16 buckets<br>Lots of entries competing<br>for the same buckets<br><br>After:<br>32 buckets<br>Entries can spread out more</pre><p>Fewer crowded buckets usually means fewer collisions and faster lookup.</p><p>So the load factor is basically a balance:</p><blockquote><em>Don’t resize too early and waste memory, but don’t let the buckets become too crowded either</em></blockquote><h3>Final Takeaway</h3><p>The complete idea is surprisingly simple:</p><pre>Key<br> ↓<br>hashCode()<br> ↓<br>Find Bucket<br> ↓<br>Collision?<br> ↓<br>Use equals() to find exact key</pre><p>As more entries are added:</p><pre>Buckets become crowded<br>        ↓<br>Load factor threshold reached<br>        ↓<br>HashMap resizes<br>        ↓<br>More buckets become available</pre><p>So HashMap stays fast by combining two things:</p><p><strong>Hashing narrows down where to search, and resizing prevents those search locations from becoming too crowded.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09dc3ed0e2b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JDBC, Hibernate, and Flyway: They All Touch the Database, but They Solve Different Problems]]></title>
            <link>https://medium.com/@satyamror1109/jdbc-hibernate-and-flyway-they-all-touch-the-database-but-they-solve-different-problems-da159ae6638e?source=rss-074f7c74c1b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/da159ae6638e</guid>
            <dc:creator><![CDATA[Satyam Singh]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 09:12:47 GMT</pubDate>
            <atom:updated>2026-10-02T09:12:47.402Z</atom:updated>
            <content:encoded><![CDATA[<p>If Hibernate can talk to the database and even create tables, why do we still need JDBC underneath it? And if Hibernate can update the schema, why introduce Flyway at all?</p><p>The answer is that these tools are not replacements for one another.</p><p>They solve three different layers of the same database problem:</p><p><strong>JDBC → database communication</strong><br><strong>Hibernate/JPA → object-to-database mapping</strong><br><strong>Flyway → database schema evolution ( database versioning )</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXZl7D1vymlAzbQkGrmZlA.png" /></figure><h3>1. JDBC: Talk to the Database Directly</h3><p>With JDBC, we write SQL ourselves:</p><pre>String sql = &quot;SELECT * FROM users WHERE id = ?&quot;;</pre><pre><strong>PreparedStatement</strong> ps = connection.prepareStatement(sql);<br>ps.setLong(1, id);</pre><pre><strong>ResultSet</strong> rs = ps.executeQuery(); </pre><pre><em>// </em><strong><em>ResultSet</em></strong><em> contains the rows returned by the database.</em></pre><p>JDBC gives us direct control over:</p><ul><li>SQL</li><li>connections</li><li>statements</li><li>result sets</li></ul><p>The downside is obvious: <strong>a lot of repetitive code.</strong></p><p>We also have to manually <strong>convert database rows into Java objects.</strong></p><p>If the table contains:</p><pre>id | name   | email<br>1  | Ankit  | Ankit@gmail.com</pre><p>with JDBC we would manually read each column:</p><pre>if (rs.next()) {<br>    User user = new User();<br><br>    user.setId(rs.getLong(&quot;id&quot;));<br>    user.setName(rs.getString(&quot;name&quot;));<br>    user.setEmail(rs.getString(&quot;email&quot;));<br>}</pre><p>So JDBC gives us the row through ResultSet, but <strong>we are responsible for converting that row into a </strong><strong>User object</strong>.</p><p>JDBC solves one problem:</p><p><strong>How does Java communicate with a relational database?</strong></p><h3>2. Hibernate: Work With Objects Instead of Rows</h3><p>Hibernate works at a higher level.</p><p>Instead of manually reading columns from a ResultSet, <strong><em>Hibernate maps a Java class to a database table, a single table row to an object, and individual columns to the class fields.</em></strong></p><pre>@Entity<br>class User {<br><br>    @Id<br>    private Long id;<br>    private String name;<br>    private String email;<br>}</pre><p>Then:</p><pre>User user = repository.findById(1L).get();</pre><p>Hibernate generates and executes the SQL behind the scenes and maps the database row into the User object for us.</p><p>It also provides features like:</p><ul><li><strong>Object-relational mapping</strong> → maps database rows to Java objects</li><li><strong>Dirty checking</strong> → detects changes in managed objects and updates the database</li><li><strong>Relationships</strong> → maps associations like OneToMany and ManyToOne</li><li><strong>Lazy loading</strong> → loads related data only when needed</li><li><strong>Persistence context</strong> → tracks managed entities during a transaction</li></ul><p>So Hibernate solves a different problem:</p><p><strong>How do I map and manage Java objects against relational database data without writing SQL and mapping every row manually?</strong></p><p>But Hibernate introduces another question.</p><p>What happens when the <strong>database structure itself changes?</strong></p><h3>3. Hibernate Can Create Tables. So Why Do We Need Flyway?</h3><p>Spring Boot can use Hibernate to create or update the schema:</p><pre>spring.jpa.hibernate.ddl-auto=update</pre><p>If you add:</p><pre>private String phoneNumber;  // to an already existing Class</pre><p>Hibernate may alter the database table automatically.</p><p>That sounds convenient.</p><p>And for local development, it often is.</p><p>But imagine production.</p><p>Version 1 of your application has:</p><pre>users<br>- id<br>- name<br>- email</pre><p>Version 2 requires:</p><pre>users<br>- id<br>- name<br>- email<br>- phone_number</pre><p>You now need to change databases across different Environments :</p><pre>DEV<br>QA<br>UAT<br>PROD</pre><p>You need to know:</p><ul><li>exactly what SQL ran</li><li>which environments already received the change</li><li>in what order migrations were applied</li><li>whether old data needs transformation</li><li>how the same schema can be recreated later</li></ul><p>This is not really Hibernate’s job.</p><p>This is where <strong>Flyway</strong> comes in.</p><h3>4. Flyway: Version Control for Your Database</h3><p>Flyway manages database schema changes using migration scripts.</p><p>For example:</p><pre>V1__create_users_table.sql<br>V2__add_phone_number.sql<br>V3__create_orders_table.sql</pre><p>A migration might contain:</p><pre>ALTER TABLE users<br>ADD COLUMN phone_number VARCHAR(20);</pre><p>When the application starts, Flyway checks which migrations have already been executed.</p><p>If the database has:</p><pre>V1 ✅<br>V2 ✅<br>V3 ❌</pre><p>Flyway executes only:</p><pre>V3</pre><p>It records migration history in a table such as:</p><pre>flyway_schema_history</pre><p>So your database schema now has a <strong>version history</strong>, just like your application code.</p><p><strong>Why doesn’t it run </strong><strong>V1 and </strong><strong>V2 again?</strong></p><p>Because Flyway records every successfully applied migration in:</p><pre>flyway_schema_history</pre><p>That table stores information such as the migration version, description, <strong>checksum</strong>, and execution status.</p><p>So on the next startup, Flyway compares the available migration files with flyway_schema_history and runs only the migrations that are still pending.</p><p>That is why the same migration is not executed repeatedly.</p><h3>5. Hibernate and Flyway Are Not Competitors</h3><p>This is the most important distinction.</p><h3>Hibernate manages data at runtime</h3><pre>repository.save(user);<br>repository.findById(id);</pre><p>It maps:</p><pre>Java Object ↔ Database Row</pre><h3>Flyway manages how the database structure evolves</h3><pre>CREATE TABLE<br>ALTER TABLE<br>CREATE INDEX<br>ADD COLUMN</pre><p>It manages:</p><pre>Database Version 1<br>        ↓<br>Database Version 2<br>        ↓<br>Database Version 3</pre><p>They solve completely different problems.</p><h3>How They Work Together</h3><p>A production Spring Boot application commonly looks like this:</p><pre>Application startup<br>       |<br>       v<br>     Flyway<br>       |<br>       | Apply pending migrations<br>       v<br>Database schema ready<br>       |<br>       v<br>   Hibernate / JPA<br>       |<br>       | Read and write application data<br>       v<br>    Application</pre><p>Flyway prepares the schema.</p><p>Hibernate works with that schema during application execution.</p><p>For production systems, it is common to let Flyway control schema changes and configure Hibernate to <strong>validate</strong> rather than modify the schema automatically.</p><pre>spring.jpa.hibernate.ddl-auto=validate</pre><p>This allows Hibernate to warn you if the entity model does not match the database without silently changing production tables.</p><h3>Final Takeaway</h3><p>Think about the three tools this way:</p><pre>JDBC<br>&quot;How do I talk to the database?<br><br>Hibernate<br>&quot;How do I work with database data as Java objects?&quot;<br><br>Flyway<br>&quot;How do I safely evolve the database structure over time?&quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da159ae6638e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Does @Transactional Sometimes Do Absolutely Nothing?]]></title>
            <link>https://medium.com/@satyamror1109/why-does-transactional-sometimes-do-absolutely-nothing-7cb7ad17759b?source=rss-074f7c74c1b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cb7ad17759b</guid>
            <dc:creator><![CDATA[Satyam Singh]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 08:18:26 GMT</pubDate>
            <atom:updated>2026-09-27T08:18:26.253Z</atom:updated>
            <content:encoded><![CDATA[<p>We usually expect this:</p><pre>@Transactional<br>public void saveUser() {<br>    // database operations<br>}</pre><p>to mean:</p><blockquote><em>Run this method inside a transaction.</em></blockquote><p>Most of the time, that works.</p><p>But sometimes @Transactional seems to be ignored completely.</p><p>The reason is simple:</p><blockquote><strong>Spring applies </strong><strong>@Transactional through a proxy. If the method call does not pass through that proxy, the transactional behavior is not applied.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OT9yySZOEhn88pKCz32TAA.png" /></figure><h3>How @Transactional Actually Works</h3><p>Suppose we have:</p><pre>@Service<br>public class UserService {<br>@Transactional<br>    public void saveUser() {<br>        // database operations<br>    }<br>}</pre><p>Spring usually creates a proxy around the actual UserService object.</p><pre>Caller<br>  |<br>  v<br>UserService Proxy<br>  |<br>  | Start Transaction<br>  v<br>Actual UserService.saveUser()<br>  |<br>  | Commit / Rollback<br>  v<br>Database</pre><p>So when another bean calls:</p><pre>userService.saveUser();</pre><p>the call first reaches the proxy.</p><p>The proxy sees @Transactional, starts the transaction, and then calls the real method.</p><h3>Where Does It Fail?</h3><p>Now consider:</p><pre>@Service<br>public class UserService {<br><br>public void createUser() {<br>        saveUser();<br>    }<br><br>    @Transactiojavanal<br>    public void saveUser() {<br>        // database operations<br>    }<br>}</pre><p>Another class calls:</p><pre>userService.createUser();</pre><p>The first call still goes through the proxy:</p><pre>Caller<br>  |<br>  v<br>UserService Proxy<br>  |<br>  v<br>Actual UserService.createUser()</pre><p>But inside createUser() we call:</p><pre>saveUser();</pre><p>which is effectively:</p><pre>this.saveUser();</pre><p>And this refers to the <strong>actual UserService object</strong>, not the proxy.</p><p>So the flow becomes:</p><pre>Actual UserService.createUser()<br>        |<br>        v<br>Actual UserService.saveUser(). // not the proxy proxy object , but UserService obj</pre><p>The second call never passes through the Spring proxy.</p><p>Therefore Spring never gets the chance to apply the @Transactional logic on saveUser().</p><p>This is called <strong>self-invocation</strong>.</p><h3>Final Takeaway</h3><p>@Transactional is not activated simply because execution reaches an annotated method.</p><p>It works because <strong>Spring intercepts the method call through a proxy</strong>.</p><pre>External call<br>→ Proxy<br>→ @Transactional works<br><br>Internal self-call<br>→ Direct method call<br>→ Proxy bypassed<br>→ Transactional advice not applied</pre><p>So the real question is not:</p><p><strong>“Is this method annotated with </strong><strong>@Transactional?”</strong></p><p>The better question is:</p><p><strong>“Did this method call pass through the Spring proxy?”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cb7ad17759b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Can a HashMap Entry Exist but get() Still Return null?]]></title>
            <link>https://medium.com/@satyamror1109/why-can-a-hashmap-entry-exist-but-get-still-return-null-aaea8c613ce5?source=rss-074f7c74c1b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaea8c613ce5</guid>
            <dc:creator><![CDATA[Satyam Singh]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 13:22:09 GMT</pubDate>
            <atom:updated>2026-09-26T13:22:09.606Z</atom:updated>
            <content:encoded><![CDATA[<p>A HashMap stores key-value pairs, and we normally expect this:</p><pre>map.put(key, value);</pre><pre>map.get(key); // returns value</pre><p>But there is an interesting case where the entry still exists inside the map, yet get(key) returns null.</p><p>The reason is a <strong>mutable key</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vm1Y4hCsY3gBLmx_JYgnaw.png" /></figure><h3>The Problem</h3><p>Consider this class:</p><pre>class UserKey {<br><br>    String email;<br><br>    UserKey(String email) {<br>        this.email = email;<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        return email.hashCode();<br>    }<br><br>    @Override<br>    public boolean equals(Object obj) {<br><br>        if (this == obj) {<br>            return true;<br>        }<br><br>        UserKey other = (UserKey) obj;<br><br>        return email.equals(other.email);<br>    }<br>}</pre><p>Now use <strong>UserKey</strong> as a HashMap key:</p><pre>Map&lt;UserKey, String&gt; map = new HashMap&lt;&gt;();</pre><pre>UserKey key = new UserKey(&quot;a@gmail.com&quot;);</pre><pre>map.put(key, &quot;User Data&quot;);</pre><pre>System.out.println(map.get(key));<br>// User Data</pre><p>Everything works.</p><p>Now change the email:</p><pre>key.email = &quot;b@gmail.com&quot;;<br><br>System.out.println(map.get(key));<br>// null</pre><p>The strange part is:</p><p><strong>The entry was never removed from the map.</strong></p><p>So why can’t HashMap find it?</p><h3>How HashMap Finds a Key</h3><p>When we call:</p><pre>map.put(key, value);</pre><p>HashMap uses the key&#39;s hashCode() to determine where the entry should be stored.</p><p>Simplified:</p><pre>key<br> ↓<br>hashCode()<br> ↓<br>bucket<br> ↓<br>store entry</pre><p>With:</p><pre>&quot;a@gmail.com&quot;</pre><p>the key might be placed in something like:</p><pre>Bucket 5<br>┌──────────────────────────────┐<br>│ UserKey(&quot;a@gmail.com&quot;)       │<br>│ &quot;User Data&quot;                  │<br>└──────────────────────────────┘</pre><p>When we later call:</p><pre>map.get(key);</pre><p>HashMap again calculates the key’s hash and uses it to locate the correct bucket.</p><h3>What Changes When the Key Is Modified?</h3><p>We change:</p><pre>key.email = &quot;b@gmail.com&quot;;</pre><p>But email is also used by hashCode().</p><p>So the same object now produces a different hash.</p><pre>Before:<br><br>&quot;a@gmail.com&quot;<br>     ↓<br>   Hash A<br>     ↓<br> Bucket 5<br><br>After modification:<br>&quot;b@gmail.com&quot;<br>     ↓<br>   Hash B<br>     ↓<br> Bucket 9</pre><p>The entry is still sitting in <strong>Bucket 5</strong>.</p><p>But get(key) now searches <strong>Bucket 9</strong>.</p><p>It never reaches the original entry.</p><p>Therefore:</p><pre>map.get(key); // null</pre><p>The object still exists in the map.</p><p>The HashMap simply no longer knows how to reach it using that key.</p><h3>Where Does equals() Come In?</h3><p>hashCode() helps HashMap locate the correct bucket.</p><p>Then equals() helps identify the correct key when multiple entries exist in that bucket.</p><p>A simplified lookup is:</p><pre>hashCode()<br>   ↓<br>Find bucket<br>   ↓<br>equals()<br>   ↓<br>Find exact key</pre><p>So changing fields used by either hashCode() or equals() after insertion can break the assumptions HashMap relies on.</p><h3>The Important Rule</h3><p>If an object is used as a HashMap key:</p><p><strong>Do not modify the fields used by its </strong><strong>equals() and </strong><strong>hashCode() while that object remains a key in the map.</strong></p><p>This is why immutable objects make excellent HashMap keys.</p><p>For example:</p><pre>final class UserKey {<br>private final String email;<br>    UserKey(String email) {<br>        this.email = email;<br>    }<br>}</pre><p>Now the field affecting the hash cannot change after construction.</p><h3>Final Takeaway</h3><p>A HashMap does not search through every entry when you call get().</p><p>It first uses the key’s hash to decide <strong>where to search</strong>.</p><p>If the key changes after insertion and its hash changes, the entry may remain inside the map while normal lookup can no longer find it.</p><p><strong>The entry isn’t missing. Its address changed, but the entry never moved.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaea8c613ce5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Cost of Inheritance: Why Java Interfaces Cannot Own Object State while abstract Class…]]></title>
            <link>https://medium.com/@satyamror1109/the-hidden-cost-of-inheritance-why-java-interfaces-cannot-own-object-state-while-abstract-class-d36867f90826?source=rss-074f7c74c1b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d36867f90826</guid>
            <dc:creator><![CDATA[Satyam Singh]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 17:46:29 GMT</pubDate>
            <atom:updated>2026-09-24T17:46:29.652Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Hidden Cost of Inheritance: Why Java Interfaces Cannot Own Object State while abstract Class can ?</h3><p>An abstract class can have instance variables just like a normal class. Although we cannot instantiate an abstract class directly, <strong>its instance variables become part of the subclass object</strong>.</p><pre>abstract class Animal {<br>    int age;<br>}</pre><pre>class Dog extends Animal {<br>}</pre><p>When we create a Dog, the object contains the inherited age field:</p><pre>Dog object<br>┌──────────────┐<br>│ Animal.age   │<br>│ Dog&#39;s fields │<br>└──────────────┘</pre><p>An abstract class can therefore contribute both <strong>state and behavior</strong> to its subclasses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKfa-rD6MypAmZpAP3bwQg.png" /></figure><h3>Why Can’t an Interface Do the Same?</h3><p>Every field declared in an interface is implicitly public static final. It belongs to the interface, not to individual implementing objects.</p><p>But the distinction goes deeper than the fact that interface fields are constants.</p><p><strong>Java allows a class to implement multiple interfaces.</strong> If interfaces could contribute instance state, Java would need additional rules to determine how that state is inherited and initialized.</p><p>Imagine this <strong><em>hypothetical example</em></strong>, which is <strong>not valid Java</strong>:</p><pre>interface Walker {<br>    int count = 0; // Imagine this is an instance field<br>}<br><br>interface Runner {<br>    int count = 0; // Imagine this is an instance field<br>}<br><br>class Athlete implements Walker, Runner {<br>}</pre><p>Should an Athlete object contain <strong>one shared </strong><strong>count field or two separate copies</strong>, one inherited through each interface?</p><p>Java avoids this complexity by preventing interfaces from contributing instance fields to implementing objects.</p><p>Simply having two interfaces declare fields with the same name is not, by itself, an impossible problem. The deeper challenge is defining consistent rules for <strong>shared inherited state</strong>, particularly when multiple inheritance paths lead back to the same interface.</p><h3>But Why Are Default Methods Allowed?</h3><p>Interfaces can inherit conflicting behavior:</p><pre>interface Walker {<br>    default void move() {<br>        System.out.println(&quot;Walking&quot;);<br>    }<br>}</pre><pre>interface Runner {<br>    default void move() {<br>        System.out.println(&quot;Running&quot;);<br>    }<br>}</pre><pre>class Athlete implements Walker, Runner {</pre><pre>    @Override<br>    public void move() {<br>        Walker.super.move();<br>    }<br>}</pre><p>Here, Java requires Athlete to resolve the conflict by overriding move().</p><p><strong>A method conflict can be resolved by choosing an implementation. Instance state also requires decisions about storage, ownership, and initialization.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d36867f90826" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Memory Explained: What Really Happens Inside the JVM When You Create an Object?]]></title>
            <link>https://medium.com/@satyamror1109/java-memory-explained-what-really-happens-inside-the-jvm-when-you-create-an-object-998b64b54867?source=rss-074f7c74c1b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/998b64b54867</guid>
            <dc:creator><![CDATA[Satyam Singh]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 07:24:44 GMT</pubDate>
            <atom:updated>2026-09-24T07:24:44.054Z</atom:updated>
            <content:encoded><![CDATA[<p>JVM memory management is categorised into 3 main parts -<br><strong>Method area<br>Stack area<br>Heap area</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCbOiBXouaLlcorn_GBHFg.png" /></figure><p>while execution of the bytecode by the JVM the method area comes into picture first</p><h3><strong>1. Method Area</strong></h3><p>The Method Area stores class-level metadata such as class structure, methods, fields, static variables, and runtime constant pool.</p><p>During execution, the JVM uses this metadata to create <strong>stack frames ( based on method scope )</strong> for method calls and to allocate and initialize <strong>objects</strong> in heap memory <strong>( based on the class definition present in the method area )</strong>.</p><h3>✔ Method Area stores:</h3><ul><li>Class metadata ✔</li><li>Method definitions (bytecode) ✔</li><li>Field definitions ✔</li><li>Static members ✔</li></ul><h3>✔ Stack &amp; Heap depend on Method Area</h3><ul><li><em>“Stack frames”</em> are created <strong>using method metadata</strong></li><li><em>“Heap objects”</em> are created <strong>using class field layout</strong></li></ul><p>Without Method Area:</p><ul><li>JVM doesn’t know <strong>what a class looks like</strong></li><li>JVM doesn’t know <strong>what instructions to execute</strong></li><li>JVM doesn’t know <strong>how much memory to allocate for objects</strong></li></ul><p>So yes — <strong>Method Area comes first</strong>.</p><p>Tiny correction for accuracy:</p><h3>❌ Stack and heap are created from metadata</h3><h3>✅ Stack frames and heap objects are created using metadata</h3><h3>🧩 Why Method Area Is NOT Just “Another Memory”</h3><p>Unlike stack and heap:</p><ul><li>It is <strong>not scope-based</strong></li><li>It is <strong>not per-object</strong></li><li>It is <strong>not per-thread</strong></li></ul><p>Instead:</p><ul><li>It is <strong>class-based</strong></li><li>Loaded once per class</li><li>Shared across all threads</li></ul><p>That’s why:</p><pre>static int x;</pre><p>is shared everywhere.</p><h3>🎯 When Does Method Area Get Cleaned?</h3><ul><li>When a class is <strong>unloaded</strong></li></ul><h3>2. Stack memory</h3><p>Generally we say that after method area comes stack memory creation<br> but that’s wrong as <em>stack memory already exists when JVM starts</em> ..</p><p>Method area is just used to initiate that stack memory as stack doesn’t know how the method looks like and what it contains. and what is its order in the class.</p><p><strong>Method Area is used first to load class metadata, and then stack frames are created during method execution.</strong></p><p>Stack frames are created in the stack memory once the method is invoked ( not when method is loaded ) because method can be loaded in the method area but but if it is nowhere invoked in the code then stack frame will not be created. Even recursive method calls create separate stack frames for the same method.</p><p>Every Stack frame contains contains — local variable ( primitive values and references ), and <strong>references</strong> in the stack frame points to the objects and Collections that are stored in <strong>heap</strong> memory .</p><p><strong><em>When a method completes execution, its stack frame is removed, and any heap objects that are no longer referenced become eligible for garbage collection.</em></strong></p><h3>3. Heap Memory</h3><p><strong>Heap memory is the runtime memory area where all objects, arrays and Collections are stored.</strong></p><p>Whenever you write:</p><pre>new Object();<br>new ArrayList&lt;&gt;();<br>new int[10];</pre><p>👉 memory is allocated in <strong>heap</strong>, not stack.</p><h3>Heap properties</h3><ul><li>Shared across all threads</li><li>Not scope-based</li><li>Managed by Garbage Collector</li><li>Exists for JVM lifetime</li><li>Slower than stack (but optimized)</li></ul><h3>2️⃣ What Lives in Heap Memory (Very Important)</h3><h4>✔ Objects</h4><pre>User u=new User();</pre><h4>✔ Arrays</h4><pre>int[] arr =new int[5];</pre><h4><strong>✔ Collections</strong></h4><pre>List&lt;String&gt; list =new ArrayList&lt;&gt;()</pre><h4>✔ String objects (including String Pool)</h4><pre>Strings=&quot;hello&quot;;</pre><p>📌 Since Java 7, <strong>String Pool is part of heap</strong>.</p><h3>4️⃣ Heap and Method Area Relationship (Blueprint → Instance)</h3><p>Heap <strong>cannot work independently</strong>.</p><h4>Object creation flow:</h4><pre>User u=new User();</pre><ol><li>JVM looks into <strong>Method Area</strong></li><li>Reads User class metadata</li><li>Determines:</li></ol><ul><li>Field count</li><li>Field types</li><li>Memory layout</li></ul><p>4. Allocates memory in <strong>heap</strong></p><p>5. Initializes fields</p><p>6. Returns reference to <strong>stack</strong></p><p>📌 Heap objects are <strong>created based on Method Area definitions</strong>.</p><h4>Heap and Stack Relationship (Data ↔ Execution)</h4><p>This relationship is critical.</p><h4>Example:</h4><pre>void test() {<br>User u=new User();<br>}</pre><p>Memory view:</p><pre>Stack Frame:<br>u---&gt;reference</pre><pre>Heap:<br>User object {fields }</pre><h3>Important rules:</h3><ul><li>Stack <strong>never stores objects</strong></li><li>Heap <strong>never stores stack frames</strong></li><li>Stack stores <strong>references</strong></li><li>Heap stores <strong>actual objects</strong></li></ul><h4>Lifetime of Heap Objects</h4><p>Heap objects:</p><ul><li>Outlive method execution</li><li><em>Exist as long as </em><strong><em>reachable</em></strong></li></ul><p>Example:</p><pre>User u;</pre><pre>void create() {<br>    u = new User();<br>}</pre><p>Here:</p><ul><li>Object survives even after method ends</li><li>Because reference still exists (global/static/field)</li></ul><p>Object lifetime is <strong>reachability-based</strong>, not scope-based.</p><h3>Garbage Collection (High-Level Flow)</h3><p>GC decides:</p><ul><li>Which objects are still reachable</li><li>Which objects can be reclaimed</li></ul><h3>GC roots include:</h3><ul><li>Stack references</li><li>Static variables</li><li>JNI references</li></ul><p>If an object is <strong>not reachable from any GC root</strong>, it becomes eligible for GC.</p><h3>Heap Is Generational (Key Design Insight)</h3><p>Heap is divided because of this observation:</p><blockquote><em>Most objects die young</em></blockquote><h3>Heap structure:</h3><pre>Heap<br> ├── Young Generation<br> │     ├── Eden<br> │     ├── Survivor S0<br> │     └── Survivor S1<br> │<br> └──Old Generation</pre><h3>Young Generation — Object Birthplace</h3><h4>Eden</h4><ul><li>New objects allocated here</li><li>Fast allocation</li></ul><p>When Eden fills:</p><p>➡ Minor GC happens</p><h4>Survivor Spaces</h4><ul><li>Objects that survive Minor GC are copied here</li><li>Objects age as they survive multiple GCs</li></ul><h4>Aging &amp; Promotion (Why Heap Is Efficient)</h4><ul><li>JVM tracks object age</li><li>After threshold, object promoted to Old Gen</li><li>Prevents repeated scanning of long-lived objects</li></ul><p>This keeps memory usage efficient and GC fast.</p><h3>Old Generation</h3><ul><li>Stores long-lived objects</li><li>GC less frequent</li><li>Uses advanced GC algorithms</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=998b64b54867" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Functional Interfaces Power Lambda Expressions and the Stream API in Java]]></title>
            <link>https://medium.com/@satyamror1109/how-functional-interfaces-power-lambda-expressions-and-the-stream-api-in-java-5f40191e1edc?source=rss-074f7c74c1b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f40191e1edc</guid>
            <dc:creator><![CDATA[Satyam Singh]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 16:49:30 GMT</pubDate>
            <atom:updated>2026-09-21T16:49:30.525Z</atom:updated>
            <content:encoded><![CDATA[<p>Java 8 introduced three important features that changed how developers write Java code: <strong>Functional Interfaces, Lambda Expressions, and the Stream API.</strong></p><p>You might have used all three while working with Java, but have you ever wondered how they are connected?</p><p>Why does filter() accept a lambda expression? How does Java know which method that lambda implements? And why do we need functional interfaces in the first place?<br>Let’s understand how these three features work together, starting with the problem they solve.</p><h3>The Problem: How Do We Pass Behavior to a Method?</h3><p>Imagine we want to check whether a number is even, positive, or greater than 10.</p><p>Instead of writing separate methods for every condition, wouldn’t it be better if we could <strong>pass the required logic directly to a method?</strong></p><p>Unlike JavaScript, Java does not treat methods as independent first-class values. Traditionally, we had to represent behavior using objects.</p><p>For example:</p><pre>interface NumberChecker {<br>    boolean check(int number);<br>}</pre><p>To check whether a number is even, we would create a separate implementation:</p><pre>class EvenNumberChecker implements NumberChecker {<br><br>    public boolean check(int number) {<br>        return number % 2 == 0;<br>    }<br>}</pre><p>We could then pass this implementation to a method:</p><pre>void verifyNumber(int number, NumberChecker checker) {<br>    System.out.println(checker.check(number));<br>}</pre><p><strong>The problem?</strong> Creating a separate class for every small operation requires unnecessary code.</p><p>Java 8 simplified this with <strong>lambda expressions</strong>, allowing us to provide the implementation directly:</p><pre>// Check if the number is even<br>verifyNumber(10, n -&gt; n % 2 == 0);<br><br>// Check if the number is positive<br>verifyNumber(10, n -&gt; n &gt; 0);<br><br>// Check if the number is greater than 10<br>verifyNumber(10, n -&gt; n &gt; 10);</pre><p>No separate implementation class needed!</p><h3>1. Functional Interfaces: The Foundation</h3><p>Imagine you want to pass some logic to a method, such as checking whether a number is even.</p><p>In Java, we cannot directly pass a standalone method as an argument. Traditionally, we represent behavior using objects.</p><p>This is where functional interfaces come in.</p><p>A <strong>functional interface</strong> is an interface with exactly one abstract method. It can also have multiple default and static methods.</p><pre>@FunctionalInterface<br>interface NumberChecker {<br>    boolean check(int number);<br>}</pre><p>Before Java 8, we could implement this interface using a separate class or an anonymous class.</p><p>But Java 8 introduced a much simpler approach: <strong>Lambda Expressions.</strong></p><h3>2. Lambda Expressions: Providing the Implementation</h3><p>A lambda expression provides the implementation of a functional interface’s single abstract method without requiring us to create a separate implementation class.</p><pre>NumberChecker checker = n -&gt; n % 2 == 0;</pre><p>Here, the lambda expression:</p><pre>n -&gt; n % 2 == 0</pre><p>provides the implementation of:</p><pre>boolean check(int number);</pre><p>We can execute this logic using:</p><pre>checker.check(10); // true</pre><p><strong>But what actually happens?</strong></p><p>Java uses the functional interface as the target type of the lambda expression.</p><p>At runtime, the JVM provides an object implementing that interface, allowing us to invoke the supplied behavior through its abstract method.</p><p>Also, lambda expressions are not inherently asynchronous. The code above executes synchronously.</p><p><strong>The relationship so far:</strong> A functional interface defines the contract, and a lambda expression provides its implementation.</p><h3>3. Stream API: Where Everything Comes Together</h3><p>Now imagine we have a list of ages and want to find all the adults.</p><pre>List&lt;Integer&gt; ages = List.of(12, 25, 17, 30, 40);</pre><p>Using the Stream API:</p><pre>List&lt;Integer&gt; adults = ages.stream()<br>        .filter(age -&gt; age &gt;= 18)<br>        .toList();</pre><p>Output:</p><pre>[25, 30, 40]</pre><p><em>Note: </em><em>toList() was introduced in Java 16. In Java 8, use </em><em>collect(Collectors.toList()).</em></p><p>But how does filter() know which elements to keep?</p><p><strong>Because </strong><strong>filter() accepts a functional interface called </strong><strong>Predicate.</strong></p><p>Its abstract method is:</p><pre>boolean test(T t);</pre><p>Our lambda expression:</p><pre>age -&gt; age &gt;= 18</pre><p>provides the implementation of Predicate.test().</p><p>We could also write the same code as:</p><pre>Predicate&lt;Integer&gt; isAdult = age -&gt; age &gt;= 18;</pre><pre>List&lt;Integer&gt; adults = ages.stream()<br>        .filter(isAdult)<br>        .toList();</pre><p>When the stream processes an element, it invokes the supplied predicate to check whether that element should be retained.</p><p><strong>This is how functional interfaces and lambda expressions work together inside the Stream API.</strong></p><h3>4. Different Stream Operations Use Different Functional Interfaces</h3><p>The Stream API uses different functional interfaces depending on the operation.</p><p>Stream methodFunctional interfacePurposefilter()Predicate&lt;T&gt;Checks a condition and returns a boolean.map()Function&lt;T, R&gt;Transforms an element into another value.forEach()Consumer&lt;T&gt;Performs an action without returning a result.</p><p>For example:</p><pre>List&lt;Integer&gt; result = ages.stream()<br>        .filter(age -&gt; age &gt;= 18)<br>        .map(age -&gt; age * 2)<br>        .toList();</pre><p>Here, filter() uses a Predicate to select adults, while map() uses a Function to double their ages.</p><p>The final result is:</p><pre>[50, 60, 80]</pre><h3>5. The Complete Picture</h3><pre>FUNCTIONAL INTERFACE<br>               |<br>        Defines the contract<br>               |<br>               v<br>      Predicate&lt;Integer&gt;<br>               |<br>               v<br>      boolean test(Integer n)<br>               |<br>               |<br>       LAMBDA EXPRESSION<br>               |<br>      Provides implementation<br>               |<br>               v<br>         n -&gt; n &gt;= 18<br>               |<br>               |<br>           STREAM API<br>               |<br>       Uses the supplied logic<br>               |<br>               v<br>      filter(n -&gt; n &gt;= 18)<br>               |<br>               v<br>       Keeps matching element</pre><h3>Key Takeaway</h3><p><strong>Functional interfaces define the contract, lambda expressions provide the implementation, and the Stream API uses that implementation to process data.</strong></p><p>However, the Stream API does not strictly depend on lambda expressions. It depends on functional interface contracts, which can also be implemented using ordinary classes or anonymous classes.</p><p>Lambda expressions simply make the implementation much easier and more readable.</p><p>And that’s how these three Java features work together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f40191e1edc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>