<?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 Shivampatel on Medium]]></title>
        <description><![CDATA[Stories by Shivampatel on Medium]]></description>
        <link>https://medium.com/@shivapatel1102001?source=rss-cfe90cde530b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ws4EMAxutFMJHjTy</url>
            <title>Stories by Shivampatel on Medium</title>
            <link>https://medium.com/@shivapatel1102001?source=rss-cfe90cde530b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:46:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivapatel1102001/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[ Docker from Scratch — A Beginner Friendly Guide (With Examples)]]></title>
            <link>https://medium.com/@shivapatel1102001/docker-from-scratch-a-beginner-friendly-guide-with-examples-2e146340e180?source=rss-cfe90cde530b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e146340e180</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-networking]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Shivampatel]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 13:32:33 GMT</pubDate>
            <atom:updated>2025-09-09T13:32:56.383Z</atom:updated>
            <content:encoded><![CDATA[<h3>🐳 Docker from Scratch — A Beginner Friendly Guide (With Examples)</h3><p>Hi friends 👋,<br> Today we will learn <strong>Docker from zero to hero</strong> in the <strong>most simple way possible</strong>.<br> I’ll explain every concept step by step, with <strong>real-world examples, emojis, and fun stories</strong> 🧃.</p><p>By the end, you will <strong>understand Docker completely</strong> and will be able to <strong>use it in real projects</strong> 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1T2dPUwM3IkXLdcC.png" /></figure><h3><strong>Part 1</strong></h3><blockquote>🧠 1. Problem Statement — Why Docker?</blockquote><blockquote>🐳 2. Installation of Docker CLI and Desktop</blockquote><blockquote>📦 3. Images vs Containers</blockquote><blockquote>🧃 4. Running Ubuntu Image in Container</blockquote><blockquote>🧱 5. Multiple Containers</blockquote><blockquote>📘 6. Port Mappings</blockquote><blockquote>🌍 7. Environment Variables</blockquote><blockquote>🐳8. Dockerization of a Java Spring Boot Application</blockquote><h3><strong>Part 2</strong></h3><blockquote>🔗 1. Docker Networking</blockquote><blockquote>📥 2. Volume Mounting</blockquote><blockquote>🚀 3. Efficient Caching in Layers⚡</blockquote><blockquote>🛠️ 4. Docker Multi-Stage Builds</blockquote><h3>Part 1</h3><p>🧠 1. Problem Statement — Why Docker?</p><p>Imagine you bought a <strong>video game CD</strong> 🎮. It works perfectly on your friend’s computer, but when you bring it home, it says <strong>“Missing Graphics Card”</strong> or <strong>“Install Java First”</strong> ⚠️.</p><p>This is what happens in <strong>software development</strong>:</p><ul><li>Developers say: “It works on my machine ✅”</li><li>But in testing or production, it <strong>fails</strong> 🚫 because the environment is different.</li></ul><p>👉 <strong>Docker solves this problem</strong>.<br> It allows you to <strong>package your application + everything it needs (libraries, tools, configs)</strong> into a small <strong>box (container 📦)</strong> and run it anywhere.</p><h3>🐳 2. Installation of Docker CLI and Desktop</h3><ul><li><strong>Docker CLI (Command Line Interface)</strong> = Terminal commands you type 🖥️</li><li><strong>Docker Desktop</strong> = Nice UI + Engine to run containers</li></ul><p>Steps:</p><ol><li>Download Docker Desktop (Windows/Mac/Linux) from <a href="https://hub.docker.com/welcome">Docker Hub.</a></li><li>Install it just like any software.</li><li>Open terminal and type:</li></ol><pre>docker --version</pre><p>✅ If you see version → Docker is installed.</p><h3>📦 3. Images vs Containers</h3><ul><li><strong>Image 🖼️</strong> = A recipe book 📘<br> Example: A recipe for making <strong>Pizza 🍕</strong>.</li><li>Ingredients: flour, cheese, sauce.</li><li>Instructions: bake at 200°C.<br> In Docker → Image = app + dependencies + instructions.</li><li><strong>Container 📦</strong> = A Pizza made from that recipe 🍕.</li><li>You can make many pizzas (containers) from one recipe (image).</li><li>Containers are <strong>running instances</strong> of an image.</li><li>In case there is some change, We cannot update the image, we have to make new image.</li></ul><p>👉 Example:</p><pre># Pull Ubuntu image<br>docker pull ubuntu</pre><pre># Run a container<br>docker run -it ubuntu</pre><h3>🧃 4. Running Ubuntu Image in Container</h3><p>Want to try Ubuntu Linux on your Windows? Simple with Docker:</p><pre>docker run -it ubuntu</pre><ul><li>-it = interactive terminal 👨‍💻</li><li>You are now <strong>inside Ubuntu</strong> shell 🐧</li><li>Type ls, pwd etc.</li></ul><p>⚡ Real-life use:<br> Developers use this to test apps in different OS environments <strong>without installing the OS</strong>.</p><h3>🧱 5. Multiple Containers</h3><p>Like <strong>many lunch boxes 🍱 in a fridge</strong> — each one separate, no mixing.</p><p>Example:</p><ul><li>Container 1 → MySQL Database 🗄️</li><li>Container 2 → Java API ☕</li><li>Container 3 → React Frontend 🌐</li></ul><p>Each one runs independently but can <strong>talk to each other</strong> if you allow.</p><p>👉 Run two containers:</p><pre>docker run -d --name db mysql<br>docker run -d --name web nginx</pre><h3>📘 6. Port Mappings</h3><p>Imagine you live in a big apartment 🏢. To reach your home, people need to know your <strong>door number (port)</strong>.</p><ul><li>A container also lives inside a house (Docker engine).</li><li>To access it from outside, you must open a <strong>door (port mapping)</strong>.</li></ul><p>👉 Example:</p><pre>docker run -d -p 8080:80 nginx</pre><ul><li>8080 → Door on your computer 🚪</li><li>80 → Door inside container</li></ul><p>So, visit <a href="http://localhost:8080/"><strong>http://localhost:8080</strong></a> and 🎉 you’ll see Nginx welcome page.</p><h3>🌍 7. Environment Variables</h3><p>Think of <strong>environment variables</strong> as <strong>secret notes</strong> 📜 you give to your app.</p><ul><li>Example: Database password, API key, config settings.</li><li>Instead of writing them inside code ❌, we pass them securely at runtime ✅.</li></ul><p>👉 Example:</p><pre>docker run -e DB_USER=admin -e DB_PASS=12345 myapp</pre><h3>🐳8. Dockerization of a Java Spring Boot Application</h3><p>Imagine you have made a <strong>Spring Boot project</strong> 🎉. You want to run it anywhere without worrying about<br> 👉 Java version,<br> 👉 OS,<br> 👉 dependencies,<br> 👉 or “works on my machine” problems 🐞.</p><p>That’s where <strong>Docker</strong> comes in 🚀.<br> We <strong>package the Spring Boot app inside a Docker Image</strong>, and then run it as a <strong>container</strong>.</p><h3>⚙️ Steps of Dockerization</h3><h3>🧱 1. Create a Spring Boot JAR</h3><p>First, package your project into a <strong>JAR file</strong>.</p><p>👉 Command:</p><pre>./mvnw clean package -DskipTests</pre><p>This creates a file like:</p><pre>target/myapp-0.0.1-SNAPSHOT.jar</pre><h3>📘 2. Create Dockerfile</h3><p>This file tells Docker how to build an image of your app.<br> Think of it like a <strong>recipe card 📜</strong>.</p><p>👉 Example Dockerfile:</p><pre># Use Java as base image (parent image)<br>FROM openjdk:17-jdk-slim<br># Set working directory inside container<br>WORKDIR /app<br># Copy jar file into container<br>COPY target/*.jar app.jar<br># Expose application port<br>EXPOSE 8080<br># Command to run app<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><h3>🚫 3. Add .dockerignore</h3><p>This tells Docker which files <strong>NOT</strong> to include in the image (like .gitignore).</p><p>👉 Example .dockerignore:</p><pre>target/<br>*.iml<br>*.md<br>*.git<br>*.idea</pre><h3>📦 4. Build Docker Image</h3><p>Now, build the image of your Spring Boot app.</p><p>👉 Command:</p><pre>docker build -t springboot-app:v1 .</pre><p>✅ Here:</p><ul><li>springboot-app → name of image</li><li>v1 → version</li></ul><h3>🚀 5. Run Docker Container</h3><p>Now run the image as a container 🎉.</p><p>👉 Command:</p><pre>docker run -d --name springboot-container -p 8080:8080 springboot-app:v1</pre><p>✅ Here:</p><ul><li>-d → run in background</li><li>--name → give a name to the container</li><li>-p 8080:8080 → map container’s port 8080 to your computer’s port 8080</li></ul><p>Now open 👉 http://localhost:8080 🎉 and you will see your app running.</p><h3>📥 6. Publishing Image (Optional)</h3><p>If you want to share your app with the world, push it to <strong>Docker Hub</strong>.</p><p>👉 Steps:</p><pre># Login<br>docker login<br># Tag the image<br>docker tag springboot-app:v1 your-dockerhub-username/springboot-app:v1<br># Push the image<br>docker push your-dockerhub-username/springboot-app:v1</pre><p>Now anyone can pull it with:</p><pre>docker pull your-dockerhub-username/springboot-app:v1</pre><h3>🧃 Example Folder Structure</h3><pre>springboot-app/<br> ┣ src/<br> ┣ target/<br> ┣ Dockerfile<br> ┣ .dockerignore<br> ┗ pom.xml</pre><h3>🔍 Why Dockerize Spring Boot?</h3><ul><li>✅ Run anywhere (Windows, Mac, Linux, Cloud ☁️)</li><li>✅ No need to install Java on host machine</li><li>✅ Easy deployment</li><li>✅ Consistency between Dev, Test, Prod</li></ul><h3>🎯 Real-World Example</h3><p>Imagine you made a <strong>School Management App</strong> 🏫 in Spring Boot.<br> You can:</p><ol><li>Build a JAR (school.jar)</li><li>Create a Dockerfile</li><li>Build → docker build -t school:v1 .</li><li>Run → docker run -p 8081:8080 school:v1</li></ol><p>Now your app runs in a container at 👉 localhost:8081.</p><h3>🧰 9. Docker Compose</h3><p>Think of <strong>Compose</strong> as a <strong>restaurant menu 📜</strong> where you order many dishes at once.<br> Instead of running each container separately, you define all in <strong>docker-compose.yml</strong>.</p><p>In spring boot microservice project, there are many services, so instead of running each dockerfile separately, create one docker compose file and add all the configuration into docker-compose file.</p><p>👉 Example:</p><pre>version: &quot;3&quot;<br>services:<br>  db:<br>    image: mysql<br>    environment:<br>      MYSQL_ROOT_PASSWORD: root<br>  web:<br>    image: node:18<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - db</pre><p>Run:</p><pre>docker-compose up</pre><p>✅ Both DB and Web app will start together.</p><h3>Part 2</h3><h3>🔗 1. Docker Networking</h3><p>Like phones 📱 calling each other, containers also need a <strong>network</strong>.</p><ul><li><strong>Bridge 🌉</strong> → Default network. Containers talk using IP inside Docker.</li><li><strong>Host 🏠</strong> → Container shares host’s network. Faster but less secure.</li></ul><p>👉 Example:</p><pre>docker network create mynet<br>docker run -d --name c1 --network mynet nginx<br>docker run -d --name c2 --network mynet ubuntu</pre><p>Now c1 and c2 can chat with each other 🗣️.</p><h3>🔗 Docker Networking — Explained in Detail</h3><p>Think of <strong>Docker containers as houses 🏠</strong> in a city.<br> For houses to talk to each other (send letters ✉️, make calls 📞), they need <strong>roads (networks)</strong>.</p><p>By default, each container is <strong>separate</strong> (like houses without roads).<br> But with <strong>Docker networking</strong>, we can connect them in different ways.</p><h3>⚙️ Types of Docker Networking</h3><p>Docker provides different network drivers. Let’s explore <strong>all important types</strong>:</p><h3>🌉 1. Bridge Network (Default)</h3><p><strong>Bridge = Private street in an apartment complex 🏢.</strong></p><ul><li>By default, containers connect to a <strong>bridge network</strong> created by Docker.</li><li>Containers on the same bridge can talk to each other using <strong>container name</strong> or <strong>IP address</strong>.</li><li>Outside world can reach them <strong>only if you open ports (port mapping)</strong>.</li></ul><p>👉 Example:</p><pre># Create a bridge network<br>docker network create my-bridge<br># Run 2 containers inside the same bridge<br>docker run -d --name c1 --network my-bridge nginx<br>docker run -it --name c2 --network my-bridge ubuntu<br># Inside c2 terminal<br>apt-get update &amp;&amp; apt-get install -y curl<br>curl c1</pre><p>✅ Container c2 can access c1 using its <strong>name</strong>.</p><p>📌 Use case:<br> Web app container ↔ Database container inside same bridge.</p><h3>🏠 2. Host Network</h3><p><strong>Host = No walls, same living room 🏡.</strong></p><ul><li>Container shares the <strong>same network as the host machine</strong>.</li><li>No isolation. Whatever port is inside container is directly available on host.</li><li>Faster 🚀 but less secure ⚠️.</li></ul><p>👉 Example:</p><pre>docker run -d --network host nginx</pre><ul><li>Nginx will be available directly on localhost:80.</li><li>No need for port mapping (-p).</li></ul><p>📌 Use case:<br> When you need <strong>high performance networking</strong> (e.g., monitoring tools like Prometheus, Grafana).</p><h3>🛑 3. None Network</h3><p><strong>None = Lonely house 🏚️ with no doors, no roads.</strong></p><ul><li>Container is <strong>fully isolated</strong>.</li><li>No internet, no communication with other containers.</li></ul><p>👉 Example:</p><pre>docker run -d --network none nginx</pre><p>📌 Use case:<br> For <strong>security testing</strong> 🔒 or apps that don’t need internet (e.g., offline calculation).</p><h3>☁️ 4. Overlay Network</h3><p><strong>Overlay = Highway connecting different cities 🌍.</strong></p><ul><li>Used when you have <strong>multiple Docker hosts</strong> (different machines).</li><li>Allows containers on different machines to talk securely.</li><li>Needs <strong>Docker Swarm / Kubernetes</strong>.</li></ul><p>👉 Example (Docker Swarm mode):</p><pre>docker swarm init<br>docker network create -d overlay my-overlay<br>docker service create --name web --network my-overlay nginx<br>docker service create --name db --network my-overlay mysql</pre><p>📌 Use case:<br> Microservices across multiple servers in production 🚀.</p><h3>🔗 5. Macvlan Network</h3><p><strong>Macvlan = Each container gets its own house with its own postal address 🏠📬.</strong></p><ul><li>Assigns a <strong>MAC address</strong> to each container.</li><li>Makes container appear as a <strong>physical device</strong> on your LAN.</li><li>Other devices in your local network can talk to it directly.</li></ul><p>👉 Example:</p><pre>docker network create -d macvlan \<br>  --subnet=192.168.1.0/24 \<br>  --gateway=192.168.1.1 \<br>  -o parent=eth0 my-macvlan</pre><p>📌 Use case:<br> When you want containers to look like <strong>real devices on your LAN</strong> (IoT devices, network simulations).</p><h3>🧰 6. Custom Networks</h3><p>You can create your <strong>own networks</strong> with rules.</p><p>👉 Example:</p><pre>docker network create mynet<br>docker run -d --name app1 --network mynet nginx<br>docker run -d --name app2 --network mynet ubuntu</pre><p>Now app1 ↔ app2 can chat using names.</p><p>📌 Use case:<br> Organizing containers into separate logical networks.</p><h3>📋 Networking Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*EWc_xMrzZW6eptSZYcjlpQ.png" /></figure><h3>🎯 Real-World Analogy</h3><ul><li><strong>Bridge</strong> → Apartments with internal road 🏢.</li><li><strong>Host</strong> → Everyone lives in the same hall 🏠.</li><li><strong>None</strong> → Locked basement 🚪🔒.</li><li><strong>Overlay</strong> → Highway between different cities 🌍.</li><li><strong>Macvlan</strong> → Each house with its own postal address 📬.</li></ul><h3>📥 2. Volume Mounting</h3><p>Containers are temporary ⚠️. If you delete → data is gone.<br> Solution: <strong>Volumes = external hard drive 💾</strong>.</p><p>👉 Example:</p><pre>docker run -v mydata:/var/lib/mysql mysql</pre><p>✅ Data stays safe even if container stops.</p><h3>🚀 3. Efficient Caching in Layers⚡</h3><p>Remember 🎂 cake layers?</p><ul><li>Keep commands like COPY package.json before code, so dependencies are cached.</li><li>This makes builds <strong>super fast</strong> ⚡.</li></ul><p>👉 In Docker, <strong>each line in Dockerfile = a layer</strong>.<br> When you rebuild an image, Docker <strong>reuses unchanged layers</strong> from cache instead of rebuilding them again.</p><p>This saves <strong>time</strong> ⏳ and <strong>resources</strong> 💾.</p><h3>🧱 Example 1: Bad Dockerfile (Inefficient ❌)</h3><pre>FROM openjdk:17-jdk-slim<br>WORKDIR /app<br># Copy everything at once<br>COPY . .<br>RUN ./mvnw clean package -DskipTests<br>EXPOSE 8080<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;target/app.jar&quot;]</pre><p>⚠️ Problem:</p><ul><li>If you change <strong>one line in your code</strong>, Docker will re-run COPY . . → rebuild everything → run Maven build again.</li><li>Very <strong>slow</strong> 🐌 for large apps.</li></ul><h3>✅ Example 2: Good Dockerfile (Efficient Caching ✔️)</h3><pre># Step 1: Use parent image<br>FROM openjdk:17-jdk-slim AS builder<br>WORKDIR /app<br># Step 2: Copy only Maven wrapper + pom.xml first<br>COPY mvnw .<br>COPY .mvn .mvn<br>COPY pom.xml .<br># Step 3: Download dependencies (cached unless pom.xml changes)<br>RUN ./mvnw dependency:go-offline -B<br># Step 4: Copy source code<br>COPY src src<br># Step 5: Build application<br>RUN ./mvnw clean package -DskipTests<br># --------------------<br># Final lightweight image<br>FROM openjdk:17-jdk-slim<br>WORKDIR /app<br>COPY --from=builder /app/target/*.jar app.jar<br>EXPOSE 8080<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><h3>🔍 Why is this Efficient?</h3><ol><li><strong>Dependencies cached</strong></li></ol><ul><li>Docker caches the RUN ./mvnw dependency:go-offline step.</li><li>So next time, if you don’t change pom.xml, it won’t download all dependencies again. 🎉</li></ul><p><strong>2. Code changes only rebuild last step</strong></p><ul><li>If you only edit a file in src/, only Step 4 + Step 5 run again.</li><li>Dependencies remain cached.</li></ul><p><strong>3. Smaller final image</strong></p><ul><li>We used <strong>multi-stage build</strong> → only final JAR goes in final image.</li><li>No Maven, no extra files → lightweight ⚡</li></ul><h3>🧃 Example Build &amp; Run</h3><p>👉 Build:</p><pre>docker build -t springboot-app-cache:v1 .</pre><p>👉 Run:</p><pre>docker run -d --name springboot-cache -p 8080:8080 springboot-app-cache:v1</pre><h3>🎯 Real-World Example</h3><p>Imagine a <strong>large Spring Boot microservice</strong> with 100+ dependencies.<br>Without caching → every rebuild downloads 1GB+ dependencies.</p><p>🐌 With caching → only code changes rebuild quickly (seconds ⚡).</p><p>✅ <strong>Golden Rule for Efficient Dockerfiles</strong>:</p><ul><li>Put <strong>rarely changing steps first</strong> (pom.xml, dependency install).</li><li>Put <strong>frequently changing steps last</strong> (source code).</li></ul><h3>🛠️ 4. Docker Multi-Stage Builds</h3><p>👉 <strong>Problem before multi-stage</strong>:<br> If we use only <strong>one Dockerfile stage</strong>, our final image will contain:</p><ul><li>Maven Wrapper (mvnw)</li><li>Source code (src)</li><li>.mvn folder</li><li>Build tools + dependencies</li></ul><p>❌ This makes the <strong>image size huge</strong> (500MB+).</p><h3>✅ Solution: Multi-Stage Build</h3><p>Multi-stage builds let us:</p><ul><li><strong>Stage 1 (Builder)</strong> → build the app (needs Maven + JDK + sources).</li><li><strong>Stage 2 (Runner)</strong> → copy only the built JAR into a slim JDK image.</li></ul><p>That means: 🏗️ build heavy things → 🎯 keep only what’s needed.</p><h3>🔹 Example: Spring Boot Multi-Stage Dockerfile</h3><pre># ---------- Stage 1: Build ----------<br>FROM maven:3.9.6-eclipse-temurin-17 AS builder<br>WORKDIR /app<br># Copy Maven configuration first (to cache dependencies)<br>COPY pom.xml .<br>COPY mvnw .<br>COPY .mvn .mvn<br># Download dependencies (cached layer)<br>RUN ./mvnw dependency:go-offline -B<br># Copy source code<br>COPY src src<br># Build the JAR file<br>RUN ./mvnw clean package -DskipTests</pre><pre># ---------- Stage 2: Run ----------<br>FROM openjdk:17-jdk-slim<br>WORKDIR /app</pre><pre># Copy only the final JAR from builder stage<br>COPY --from=builder /app/target/*.jar app.jar</pre><pre>EXPOSE 8080<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><h3>🧩 How it Works</h3><ol><li><strong>Stage 1</strong> (builder):</li></ol><ul><li>Uses <strong>Maven image</strong> → builds the JAR.</li><li>Contains source code, Maven cache, and build tools.</li></ul><p><strong>2. Stage 2</strong> (runner):</p><ul><li>Starts from a <strong>slim Java image</strong> (very lightweight).</li><li>Copies only the final app.jar.</li><li>Runs it with java -jar.</li></ul><p>👉 The final image is <strong>small &amp; production-ready</strong> 🎯.</p><h3>📊 Size Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*WdOpIugfWnDAPZDpngXsww.png" /></figure><h3>🚀 Build &amp; Run</h3><pre># Build image<br>docker build -t springboot-multistage:v1 .</pre><pre># Run container<br>docker run -d -p 8080:8080 --name springboot-multistage springboot-multistage:v1</pre><p>Now visit 👉 <a href="http://localhost:8080/">http://localhost:8080</a></p><h3>🧃 Real-World Analogy (for beginners)</h3><p>Imagine you are <strong>baking a cake 🎂</strong>:</p><ul><li>You need <strong>ingredients, oven, tools</strong> → that’s the builder stage.</li><li>But when serving the cake, you don’t carry the oven or dirty dishes → you only serve the <strong>cake</strong>. 🍰</li></ul><p>👉 That’s exactly what multi-stage build does: it <strong>keeps the cake (JAR)</strong>, throws away the kitchen mess (Maven, sources, tools).</p><h3>🎉 Conclusion</h3><p>Docker is like a <strong>magic lunchbox 📦</strong>:</p><ul><li>Put your app inside once, run it anywhere 🌍.</li><li>No more “works on my machine” problems ❌.</li><li>Makes deployment fast ⚡, consistent ✅, and reliable 🔒.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e146340e180" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Java 8 (Part-2) — Comparator vs Comparable , Predicate, Function, Consumer, Supplier —…]]></title>
            <link>https://medium.com/@shivapatel1102001/java-8-part-2-comparator-vs-comparable-predicate-function-consumer-supplier-269092f8e615?source=rss-cfe90cde530b------2</link>
            <guid isPermaLink="false">https://medium.com/p/269092f8e615</guid>
            <category><![CDATA[suppliers]]></category>
            <category><![CDATA[predicate]]></category>
            <category><![CDATA[java-8-feature]]></category>
            <category><![CDATA[consumer]]></category>
            <category><![CDATA[function]]></category>
            <dc:creator><![CDATA[Shivampatel]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 11:05:27 GMT</pubDate>
            <atom:updated>2025-08-01T11:05:27.158Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔥 Java 8 (Part-2) — Comparator vs Comparable , Predicate, Function, Consumer, <strong>Supplier</strong> — Explained with Lambda and All Edge Cases</h3><p>✅ What is Comparable<br> ✅ What is Comparator<br> ✅ Syntax, examples, and output<br> ✅ Using <strong>lambda expressions</strong> with Comparator<br> ✅ Sorting List, Set, Map<br> ✅ Real-time use cases<br> ✅ Valid &amp; invalid cases<br> ✅ All edge cases with explanations</p><h3>🔍 Java 8: Comparator vs Comparable — Explained with Lambda and All Edge Cases</h3><h3>🔷 1. What is Comparable?</h3><blockquote><em>Comparable&lt;T&gt; is an </em><strong><em>interface used for natural ordering</em></strong><em> of objects.<br> It has one method:</em></blockquote><pre>int compareTo(T o);</pre><ul><li>Defined inside the class (self-comparison)</li><li>A class implements Comparable to allow sorting its instances</li></ul><h3>✅ Syntax</h3><pre>public class Student implements Comparable&lt;Student&gt; {<br>    int rollno;<br>    String name;<br><br>    public Student(int rollno, String name) {<br>        this.rollno = rollno;<br>        this.name = name;<br>    }<br><br>    @Override<br>    public int compareTo(Student s) {<br>        return this.rollno - s.rollno;  // Ascending order<br>    }<br>    public String toString() {<br>        return rollno + &quot; - &quot; + name;<br>    }<br>    public static void main(String[] args) {<br>        List&lt;Student&gt; list = new ArrayList&lt;&gt;();<br>        list.add(new Student(3, &quot;Ram&quot;));<br>        list.add(new Student(1, &quot;Shyam&quot;));<br>        list.add(new Student(2, &quot;Mohan&quot;));<br>        Collections.sort(list);  // Uses compareTo()<br>        System.out.println(list);<br>    }<br>}</pre><h3>✅ Output:</h3><pre>[1 - Shyam, 2 - Mohan, 3 - Ram]</pre><h3>🔴 Invalid Case with Comparable</h3><pre>public class Demo implements Comparable&lt;Demo&gt; {<br>    int x;<br>    @Override<br>    public int compareTo(Demo d) {<br>        // return; // ❌ Compile error – must return int<br>    }<br>}</pre><h3>✅ Advantages of Comparable</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*mmT617ZoSM6X4weuS1G7Dg.png" /></figure><h3>❌ Disadvantages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*eJN_o_FdGj2gS5S4w5rsMg.png" /></figure><h3>🔷 2. What is Comparator?</h3><blockquote><em>Comparator&lt;T&gt; is used to define </em><strong><em>custom sorting</em></strong><em> logic </em><strong><em>outside</em></strong><em> the class.<br> It has one method:</em></blockquote><pre>int compare(T o1, T o2);</pre><p>✅ It is a <strong>functional interface</strong> — can be used with <strong>lambda expressions</strong></p><h3>✅ Classic Way: Create a Separate Class</h3><pre>class SortByRollDesc implements Comparator&lt;Student&gt; {<br>    public int compare(Student s1, Student s2) {<br>        return s2.rollno - s1.rollno;<br>    }<br>}<br>public class ComparatorDemo {<br>    public static void main(String[] args) {<br>        List&lt;Student&gt; list = Arrays.asList(<br>            new Student(3, &quot;Ram&quot;),<br>            new Student(1, &quot;Shyam&quot;),<br>            new Student(2, &quot;Mohan&quot;)<br>        );<br>        Collections.sort(list, new SortByRollDesc());<br>        System.out.println(list);<br>    }<br></pre><h3>✅ Output:</h3><pre>[3 - Ram, 2 - Mohan, 1 - Shyam]</pre><h3>✅ Java 8 Way — Lambda Expression with Comparator</h3><pre>public class LambdaSort {<br>    public static void main(String[] args) {<br>        List&lt;Student&gt; list = Arrays.asList(<br>            new Student(3, &quot;Ram&quot;),<br>            new Student(1, &quot;Shyam&quot;),<br>            new Student(2, &quot;Mohan&quot;)<br>        );<br>        // Sort by rollno descending using lambda<br>        Collections.sort(list, (s1, s2) -&gt; s2.rollno - s1.rollno);<br>        System.out.println(list);<br>        // Sort by name ascending<br>        Collections.sort(list, (s1, s2) -&gt; s1.name.compareTo(s2.name));<br>        System.out.println(list);<br>    }<br>}</pre><h3>✅ Output:</h3><pre>[3 - Ram, 2 - Mohan, 1 - Shyam]<br>[2 - Mohan, 3 - Ram, 1 - Shyam]</pre><h3>✅ Using Comparator in Set and Map</h3><h3>🔹 TreeSet with Comparator</h3><pre>Set&lt;Integer&gt; set = new TreeSet&lt;&gt;((a, b) -&gt; b - a);<br>set.addAll(Arrays.asList(1, 4, 2, 3));<br>System.out.println(set);  // Descending order</pre><h3>🔹 Output:</h3><pre>[4, 3, 2, 1]</pre><h3>🔹 TreeMap with Comparator</h3><pre>Map&lt;Integer, String&gt; map = new TreeMap&lt;&gt;((a, b) -&gt; b - a);<br>map.put(1, &quot;A&quot;);<br>map.put(3, &quot;C&quot;);<br>map.put(2, &quot;B&quot;);<br>System.out.println(map);  // Sorted by descending keys</pre><h3>🔹 Output:</h3><pre>{3=C, 2=B, 1=A}</pre><h3>✅ Comparing Comparable vs Comparator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*ZdleGIH2b2ZOJsWrxL-7QQ.png" /></figure><h3>🔴 Invalid Lambda with Comparator</h3><pre>Collections.sort(list, (a, b) -&gt; {  // ❌ Missing return<br>    a - b;<br>});</pre><h3>🔴 Compile Error:</h3><pre>missing return statement</pre><h3>✅ Valid Case with Return</h3><pre>Collections.sort(list, (a, b) -&gt; {<br>    return b - a;<br>});</pre><h3>✅ Using Method Reference for Comparator</h3><pre>List&lt;String&gt; names = Arrays.asList(&quot;Ram&quot;, &quot;Shyam&quot;, &quot;Aman&quot;);<br>names.sort(String::compareToIgnoreCase);<br>System.out.println(names);</pre><h3>✅ Output:</h3><pre>[Aman, Ram, Shyam]</pre><h3>✅ Real-Time Use Case</h3><p>Sorting a list of employees by salary:</p><pre>class Employee {<br>    int id;<br>    String name;<br>    double salary;<br>    public Employee(int id, String name, double salary) {<br>        this.id = id; this.name = name; this.salary = salary;<br>    }<br>    public String toString() {<br>        return id + &quot; - &quot; + name + &quot; - &quot; + salary;<br>    }<br>}<br>public class EmployeeSort {<br>    public static void main(String[] args) {<br>        List&lt;Employee&gt; emps = Arrays.asList(<br>            new Employee(1, &quot;Amit&quot;, 70000),<br>            new Employee(2, &quot;Sumit&quot;, 50000),<br>            new Employee(3, &quot;Ravi&quot;, 60000)<br>        );<br>        // Sort by salary descending<br>        emps.sort((e1, e2) -&gt; Double.compare(e2.salary, e1.salary));<br>        System.out.println(emps);<br>    }<br>}</pre><h3>✅ Output:</h3><pre>[1 - Amit - 70000.0, 3 - Ravi - 60000.0, 2 - Sumit - 50000.0]</pre><h3>📌 Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*OkcxjIUcsOv3Z-EpCGsbkA.png" /></figure><h3>✅ Conclusion</h3><ul><li>Use <strong>Comparable</strong> when the default/natural sorting is sufficient.</li><li>Use <strong>Comparator</strong> when you need <strong>custom</strong> or <strong>multiple sorting orders</strong>.</li><li>With <strong>Java 8</strong>, use <strong>lambda expressions</strong> for cleaner, more expressive sorting logic.</li><li>Works across List, Set, and Map easily.</li></ul><h3>✅ Java 8 — Predicate Functional Interface: Explained with Examples</h3><p>✅ What is Predicate<br> ✅ Syntax, usage, and benefits<br> ✅ Valid &amp; invalid cases<br> ✅ Examples with public static void main()<br> ✅ Real-time use cases<br> ✅ Chaining with and(), or(), negate()<br> ✅ Output for each case</p><h3>🔷 What is Predicate?</h3><blockquote><em>Predicate&lt;T&gt; is a </em><strong><em>functional interface</em></strong><em> introduced in Java 8 in the </em><em>java.util.function package.<br> It is used to represent a </em><strong><em>boolean-valued function</em></strong><em> of a single input.</em></blockquote><h3>📘 Functional Interface Signature</h3><pre>@FunctionalInterface<br>public interface Predicate&lt;T&gt; {<br>    boolean test(T t);<br></pre><p>✅ It takes one input of type T and returns a boolean result<br> ✅ It&#39;s often used for <strong>filtering</strong>, <strong>validation</strong>, and <strong>conditional logic</strong></p><h3>✅ Basic Example</h3><pre>import java.util.function.Predicate;<br>public class PredicateExample {<br>    public static void main(String[] args) {<br>        Predicate&lt;Integer&gt; isOdd = x -&gt; x % 2 == 1;<br>        System.out.println(isOdd.test(3));  // true<br>        System.out.println(isOdd.test(4));  // false<br>    }<br>}</pre><h3>✅ Output:</h3><pre>true<br>false</pre><h3>✅ Why Use Predicate?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*29ko6ZAaTrUrw5o73k7sDQ.png" /></figure><h3>✅ Real-Time Use Case — Filtering a List</h3><pre>import java.util.*;<br>import java.util.function.Predicate;<br>public class FilterEven {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; list = Arrays.asList(10, 15, 20, 25, 30);<br>        Predicate&lt;Integer&gt; isEven = n -&gt; n % 2 == 0;<br>        list.stream()<br>            .filter(isEven)<br>            .forEach(System.out::println);<br>    }<br>}</pre><h3>✅ Output:</h3><pre>10<br>20<br>30</pre><h3>✅ Predicate with Custom Class</h3><pre>class Employee {<br>    String name;<br>    int salary;<br>    Employee(String name, int salary) {<br>        this.name = name;<br>        this.salary = salary;<br>    }<br>    public String toString() {<br>        return name + &quot; - ₹&quot; + salary;<br>    }<br>}<br>public class EmployeeFilter {<br>    public static void main(String[] args) {<br>        List&lt;Employee&gt; emps = Arrays.asList(<br>            new Employee(&quot;Amit&quot;, 50000),<br>            new Employee(&quot;Ravi&quot;, 30000),<br>            new Employee(&quot;Neha&quot;, 70000)<br>        );<br>        Predicate&lt;Employee&gt; highSalary = e -&gt; e.salary &gt; 40000;<br>        emps.stream()<br>            .filter(highSalary)<br>            .forEach(System.out::println);<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Amit - ₹50000<br>Neha - ₹70000</pre><h3>✅ Chaining Predicates with and(), or(), negate()</h3><h3>Example:</h3><pre>public class PredicateChaining {<br>    public static void main(String[] args) {<br>        Predicate&lt;String&gt; startsWithA = s -&gt; s.startsWith(&quot;A&quot;);<br>        Predicate&lt;String&gt; lengthGT3 = s -&gt; s.length() &gt; 3;<br>        String testStr = &quot;Abhi&quot;;<br>        System.out.println(&quot;AND: &quot; + startsWithA.and(lengthGT3).test(testStr));   // true<br>        System.out.println(&quot;OR: &quot; + startsWithA.or(lengthGT3).test(&quot;Bob&quot;));       // true<br>        System.out.println(&quot;NEGATE: &quot; + startsWithA.negate().test(&quot;Bob&quot;));        // true<br>    }<br>}</pre><h3>✅ Output:</h3><pre>AND: true<br>OR: true<br>NEGATE: true</pre><h3>🔴 Invalid Case — Predicate Must Return Boolean</h3><pre>Predicate&lt;Integer&gt; invalid = x -&gt; x + 10;  // ❌ compile-time error</pre><h3>🔴 Error:</h3><pre>Type mismatch: cannot convert from int to boolean</pre><h3>✅ Using Predicate with RemoveIf()</h3><pre>public class RemoveIfDemo {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = new ArrayList&lt;&gt;(Arrays.asList(&quot;Ajay&quot;, &quot;Ram&quot;, &quot;Ankit&quot;, &quot;Ravi&quot;));<br>        Predicate&lt;String&gt; startsWithA = name -&gt; name.startsWith(&quot;A&quot;);<br>        names.removeIf(startsWithA);</pre><pre>        System.out.println(names);  // Only names not starting with A<br>    }<br>}</pre><h3>✅ Output:</h3><pre>[Ram, Ravi]</pre><h3>✅ Combining Predicates for Complex Filtering</h3><pre>public class ComplexFilter {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = Arrays.asList(&quot;Apple&quot;, &quot;Banana&quot;, &quot;Avocado&quot;, &quot;Berry&quot;);<br>        Predicate&lt;String&gt; startsWithA = s -&gt; s.startsWith(&quot;A&quot;);<br>        Predicate&lt;String&gt; lengthGT5 = s -&gt; s.length() &gt; 5;</pre><pre>        names.stream()<br>            .filter(startsWithA.and(lengthGT5))<br>            .forEach(System.out::println);<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Avocado</pre><h3>✅ Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*quGKIQiWLEdhXmxS-n3IDg.png" /></figure><h3>✅ Predefined Predicates in Java 11+</h3><pre>Predicate.isEqual(&quot;test&quot;).test(&quot;test&quot;);     // true<br>Predicate.not(String::isEmpty).test(&quot;abc&quot;); // true</pre><h3>✅ Real World Scenarios</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*G650xvAB9rTBrD7ufbpvzw.png" /></figure><h3>✅ Conclusion</h3><ul><li><strong>Predicate</strong> simplifies conditional logic by wrapping it into reusable objects.</li><li>It works great with <strong>streams</strong>, <strong>collections</strong>, and <strong>lambda expressions</strong>.</li><li>By using chaining (and, or, negate), you can build <strong>dynamic filters</strong>.</li><li>It’s one of the most powerful and widely used <strong>functional interfaces</strong> in Java 8 and beyond.</li></ul><h3>🔍 Java 8 — Function Functional Interface Explained with Examples</h3><p>✅ Complete explanation<br> ✅ Syntax and types<br> ✅ Function chaining: andThen(), compose()<br> ✅ identity() method<br> ✅ Valid and invalid cases<br> ✅ Real-world use cases<br> ✅ Code with public static void main() and outputs</p><h3>🔷 What is Function&lt;T, R&gt;?</h3><blockquote><em>The </em><em>Function&lt;T, R&gt; interface is a functional interface in </em><em>java.util.function package.<br> It takes an input of type </em><em>T and returns a result of type </em><em>R.</em></blockquote><h3>✅ Interface Signature</h3><pre>@FunctionalInterface<br>public interface Function&lt;T, R&gt; {<br>    R apply(T t);<br>}</pre><ul><li>Takes one argument</li><li>Produces one result</li><li>Supports <strong>function composition</strong> via andThen() and compose()</li><li>Has a static method: Function.identity()</li></ul><h3>✅ 1. Basic Usage of Function</h3><pre>import java.util.function.Function;<br>public class FunctionExample {<br>    public static void main(String[] args) {<br>        Function&lt;String, Integer&gt; length = str -&gt; str.length();<br>        System.out.println(&quot;Length: &quot; + length.apply(&quot;Shivam&quot;));<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Length: 6</pre><h3>✅ 2. Using Function with Transformation</h3><pre>Function&lt;String, String&gt; upper = str -&gt; str.toUpperCase();<br>Function&lt;String, String&gt; sub = str -&gt; str.substring(0, 3);</pre><pre>public class StringTransform {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Upper: &quot; + upper.apply(&quot;java&quot;));   // JAVA<br>        System.out.println(&quot;Sub: &quot; + sub.apply(&quot;java&quot;));       // jav<br>    }<br>}</pre><h3>✅ 3. Function Chaining: andThen() vs compose()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*h2r6ILt7pZOiko2VPoyqhw.png" /></figure><h3>🔹 Example with andThen()</h3><pre>Function&lt;String, String&gt; upper = x -&gt; x.toUpperCase();<br>Function&lt;String, String&gt; sub = x -&gt; x.substring(0, 3);<br>Function&lt;String, String&gt; chain = upper.andThen(sub);<br>System.out.println(chain.apply(&quot;function&quot;));  // FUN</pre><h3>🔹 Example with compose()</h3><pre>Function&lt;String, String&gt; upper = x -&gt; x.toUpperCase();<br>Function&lt;String, String&gt; sub = x -&gt; x.substring(0, 3);<br>Function&lt;String, String&gt; chain = upper.compose(sub);<br>System.out.println(chain.apply(&quot;function&quot;));  // FUN</pre><h3>✅ Output for Both:</h3><pre>FUN<br>FUN</pre><p>🧠 They look similar in this case, but their order of execution is different!</p><h3>✅ 4. Function.identity() – Identity Function</h3><blockquote><em>Returns a function that always returns its input.</em></blockquote><h3>🔹 Syntax:</h3><pre>Function&lt;T, T&gt; identity = Function.identity();<br>System.out.println(identity.apply(&quot;Shivam&quot;)); // Shivam</pre><h3>🔴 Invalid Cases with Function</h3><h3>❌ 1. Returning Wrong Type</h3><pre>Function&lt;String, Integer&gt; f = str -&gt; str.toUpperCase(); // ❌ compile error</pre><h3>🔴 Error:</h3><pre>Type mismatch: cannot convert from String to Integer</pre><h3>❌ 2. Null Input Without Null Safety</h3><pre>Function&lt;String, Integer&gt; length = str -&gt; str.length();<br>System.out.println(length.apply(null));  // ❌ NullPointerException</pre><h3>✅ Real-Time Use Case — Salary Bonus Calculation</h3><pre>class Employee {<br>    String name;<br>    double salary;<br>    Employee(String name, double salary) {<br>        this.name = name;<br>        this.salary = salary;<br>    }<br>}<br>public class BonusCalculator {<br>    public static void main(String[] args) {<br>        Employee emp = new Employee(&quot;Shivam&quot;, 50000);<br>        Function&lt;Employee, Double&gt; bonusCalc = e -&gt; e.salary * 0.10;<br>        System.out.println(&quot;Bonus: ₹&quot; + bonusCalc.apply(emp));  // ₹5000.0<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Bonus: ₹5000.0</pre><h3>✅ Use with Map/Stream Transformations</h3><pre>List&lt;String&gt; names = Arrays.asList(&quot;Shivam&quot;, &quot;Amit&quot;, &quot;Ravi&quot;);<br>Function&lt;String, String&gt; upper = x -&gt; x.toUpperCase();<br>List&lt;String&gt; result = names.stream()<br>    .map(upper)<br>    .collect(Collectors.toList());<br>System.out.println(result);</pre><h3>✅ Output:</h3><pre>[SHIVAM, AMIT, RAVI]</pre><h3>✅ Function Chaining Complex Example</h3><pre>Function&lt;String, String&gt; removeSpaces = s -&gt; s.replace(&quot; &quot;, &quot;&quot;);<br>Function&lt;String, String&gt; toUpper = s -&gt; s.toUpperCase();<br>Function&lt;String, String&gt; finalFunction = removeSpaces.andThen(toUpper);<br>System.out.println(finalFunction.apply(&quot;hello world&quot;));  // HELLOWORLD</pre><h3>✅ Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*uumg7A6Y1FNSbokBKrA52Q.png" /></figure><h3>✅ Differences: Predicate vs Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*lzgC0r-zHKI-nVZcam7ajQ.png" /></figure><h3>✅ Conclusion</h3><ul><li>Function&lt;T, R&gt; helps with transformations and logic pipelines.</li><li>Great for converting, mapping, and modifying data.</li><li>Chaining via compose() and andThen() enables cleaner logic flow.</li><li>Used extensively in Stream.map(), data processing, and functional patterns.</li></ul><h3>🔍 Java 8 — Consumer Functional Interface Explained with Examples</h3><p>✅ What is Consumer&lt;T&gt;<br> ✅ Syntax, usage, and benefits<br> ✅ Examples with public static void main()<br> ✅ Chaining with andThen()<br> ✅ Valid and invalid cases<br> ✅ Real-time use cases<br> ✅ Output for each case</p><h3>🔷 What is Consumer&lt;T&gt;?</h3><blockquote><em>The </em><em>Consumer&lt;T&gt; is a </em><strong><em>functional interface</em></strong><em> introduced in Java 8 (in </em><em>java.util.function) that represents an </em><strong><em>operation that takes an input but returns no result</em></strong><em>.</em></blockquote><h3>✅ Interface Signature</h3><pre>@FunctionalInterface<br>public interface Consumer&lt;T&gt; {<br>    void accept(T t);<br>}</pre><ul><li>Accepts one input of type T</li><li>Returns void</li><li>Commonly used for <strong>printing</strong>, <strong>logging</strong>, <strong>storing</strong>, or <strong>applying side effects</strong></li></ul><h3>✅ 1. Basic Usage of Consumer</h3><pre>import java.util.function.Consumer;<br>public class ConsumerExample {<br>    public static void main(String[] args) {<br>        Consumer&lt;String&gt; printer = name -&gt; System.out.println(&quot;Hello, &quot; + name);<br>        printer.accept(&quot;Shivam&quot;);<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Hello, Shivam</pre><h3>✅ 2. Consumer with Integer List</h3><pre>import java.util.function.Consumer;<br>import java.util.Arrays;<br>import java.util.List;<br><br>public class ConsumerList {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4);<br>        Consumer&lt;Integer&gt; add100 = x -&gt; System.out.println(x + 100);<br>        for (Integer num : numbers) {<br>            add100.accept(num);<br>        }<br>    }<br>}</pre><h3>✅ Output:</h3><pre>101<br>102<br>103<br>104</pre><h3>✅ 3. Consumer with forEach() in Streams</h3><pre>import java.util.Arrays;<br>import java.util.List;<br>import java.util.function.Consumer;<br><br>public class ForEachExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = Arrays.asList(&quot;Shivam&quot;, &quot;Amit&quot;, &quot;Ravi&quot;);<br>        Consumer&lt;String&gt; printName = name -&gt; System.out.println(&quot;Name: &quot; + name);        names.forEach(printName);  // Or directly: names.forEach(System.out::println);<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Name: Shivam<br>Name: Amit<br>Name: Ravi</pre><h3>✅ 4. Chaining Consumers using andThen()</h3><pre>import java.util.function.Consumer;<br>public class ConsumerChain {<br>    public static void main(String[] args) {<br>        Consumer&lt;String&gt; upper = x -&gt; System.out.println(&quot;Upper: &quot; + x.toUpperCase());<br>        Consumer&lt;String&gt; lower = x -&gt; System.out.println(&quot;Lower: &quot; + x.toLowerCase());<br>        Consumer&lt;String&gt; both = upper.andThen(lower);<br>        both.accept(&quot;Java8&quot;);<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Upper: JAVA8<br>Lower: java8</pre><p>🧠 andThen() allows you to <strong>combine multiple consumers</strong> to run sequentially.</p><h3>🔴 Invalid Case — Wrong Lambda Structure</h3><pre>Consumer&lt;String&gt; wrong = s -&gt; return s.toUpperCase(); // ❌ Invalid</pre><h3>🔴 Error:</h3><pre>Void methods cannot return a value</pre><p>✔️ Fix:</p><pre>Consumer&lt;String&gt; correct = s -&gt; System.out.println(s.toUpperCase());</pre><h3>✅ Real-Time Use Case — Logging Transactions</h3><pre>class Transaction {<br>    int id;<br>    double amount;<br>    Transaction(int id, double amount) {<br>        this.id = id;<br>        this.amount = amount;<br>    }<br>    public String toString() {<br>        return &quot;Transaction ID: &quot; + id + &quot;, Amount: ₹&quot; + amount;<br>    }<br>}</pre><pre>import java.util.Arrays;<br>import java.util.List;<br>import java.util.function.Consumer;</pre><pre>public class TransactionLogger {<br>    public static void main(String[] args) {<br>        List&lt;Transaction&gt; txns = Arrays.asList(<br>            new Transaction(101, 5000),<br>            new Transaction(102, 15000)<br>        );</pre><pre>        Consumer&lt;Transaction&gt; logger = t -&gt; System.out.println(&quot;Logging: &quot; + t);<br>        txns.forEach(logger);<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Logging: Transaction ID: 101, Amount: ₹5000.0<br>Logging: Transaction ID: 102, Amount: ₹15000.0</pre><h3>✅ Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*xFzGQe5gGNxObay7R2oxKQ.png" /></figure><h3>✅ Differences: Consumer vs Function vs Predicate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*MVOjl7t3ZTW_WRIOvYfLpg.png" /></figure><h3>✅ Functionally Equivalent Examples</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*u0-SUmqiGIUo2Rkni1xhdA.png" /></figure><h3>✅ Conclusion</h3><ul><li>Consumer&lt;T&gt; is useful when you want to <strong>perform an operation</strong> (print, log, modify) but <strong>don’t need to return</strong> anything.</li><li>Great for <strong>side effects</strong>, especially in streams (forEach()).</li><li>Can be combined with andThen() to build sequences of actions.</li><li>Clean, expressive, and functional approach for action-based logic.</li></ul><h3>🔍 Java 8 — Supplier&lt;T&gt; Functional Interface Explained with Examples</h3><p>✅ Full explanation and syntax<br> ✅ Examples with public static void main()<br> ✅ Valid and invalid cases<br> ✅ Real-world use cases<br> ✅ Integration with Predicate, Function, and Consumer<br> ✅ Output for each case</p><h3>🔷 What is Supplier&lt;T&gt;?</h3><blockquote><em>The </em><em>Supplier&lt;T&gt; interface is a </em><strong><em>functional interface</em></strong><em> in </em><em>java.util.function package.<br> It </em><strong><em>supplies a result</em></strong><em> of type </em><em>T and </em><strong><em>takes no input</em></strong><em>.</em></blockquote><h3>✅ Interface Signature</h3><pre>@FunctionalInterface<br>public interface Supplier&lt;T&gt; {<br>    T get();<br>}</pre><ul><li>Takes <strong>no argument</strong></li><li>Returns <strong>one result of type T</strong></li><li>Often used for <strong>lazy initialization</strong>, <strong>generating values</strong>, or <strong>providing configuration</strong></li></ul><h3>✅ 1. Basic Example of Supplier</h3><pre>import java.util.function.Supplier;<br>public class SupplierExample {<br>    public static void main(String[] args) {<br>        Supplier&lt;Integer&gt; supplyNumber = () -&gt; 100;<br>        System.out.println(&quot;Supplied: &quot; + supplyNumber.get());<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Supplied: 100</pre><h3>✅ 2. Supplier for Random Number</h3><pre>import java.util.function.Supplier;<br>import java.util.Random;<br><br>public class RandomSupplier {<br>    public static void main(String[] args) {<br>        Supplier&lt;Integer&gt; randomSupplier = () -&gt; new Random().nextInt(100);<br>        System.out.println(&quot;Random Number: &quot; + randomSupplier.get());<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Random Number: 57  // Output may vary each time</pre><h3>✅ 3. Supplier of Current Timestamp</h3><pre>import java.util.function.Supplier;<br>import java.time.LocalDateTime;<br><br>public class TimeSupplier {<br>    public static void main(String[] args) {<br>        Supplier&lt;LocalDateTime&gt; timeSupplier = () -&gt; LocalDateTime.now();<br>        System.out.println(&quot;Time: &quot; + timeSupplier.get());<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Time: 2025-08-01T11:25:38.456</pre><h3>✅ 4. Supplier with List — Lazy Evaluation</h3><pre>import java.util.List;<br>import java.util.ArrayList;<br>import java.util.function.Supplier;<br>public class ListSupplier {<br>    public static void main(String[] args) {<br>        Supplier&lt;List&lt;String&gt;&gt; listSupplier = () -&gt; {<br>            List&lt;String&gt; names = new ArrayList&lt;&gt;();<br>            names.add(&quot;Shivam&quot;);<br>            names.add(&quot;Ravi&quot;);<br>            return names;<br>        };<br>        System.out.println(listSupplier.get());  // [Shivam, Ravi]<br>    }<br>}</pre><h3>✅ 5. Supplier Combined with Predicate, Function, Consumer</h3><pre>import java.util.function.*;<br>public class CombinedFunctionalExample {<br>    public static void main(String[] args) {<br>        Predicate&lt;Integer&gt; isEven = x -&gt; x % 2 == 0;<br>        Function&lt;Integer, Integer&gt; square = x -&gt; x * x;<br>        Consumer&lt;Integer&gt; print = x -&gt; System.out.println(&quot;Result: &quot; + x);<br>        Supplier&lt;Integer&gt; valueSupplier = () -&gt; 10;<br>        if (isEven.test(valueSupplier.get())) {<br>            print.accept(square.apply(valueSupplier.get())); // Output: Result: 100<br>        }<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Result: 100</pre><p>🧠 This example shows <strong>how all four interfaces work together</strong> to:</p><ul><li>Supply a value</li><li>Check a condition</li><li>Transform it</li><li>Perform an action</li></ul><h3>🔴 Invalid Case — Missing Return</h3><pre>Supplier&lt;String&gt; supplier = () -&gt; { System.out.println(&quot;Hello&quot;); }; // ❌</pre><h3>🔴 Error:</h3><pre>This method must return a result of type String</pre><p>✅ Fix:</p><pre>Supplier&lt;String&gt; supplier = () -&gt; {<br>    System.out.println(&quot;Hello&quot;);<br>    return &quot;Hello&quot;;<br>};</pre><h3>✅ Real-World Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*87DXceavqfDUJ9uM4I13MQ.png" /></figure><h3>✅ Using Supplier with Optional</h3><pre>import java.util.Optional;<br>import java.util.function.Supplier;<br>public class OptionalExample {<br>    public static void main(String[] args) {<br>        Supplier&lt;String&gt; defaultSupplier = () -&gt; &quot;Default&quot;;<br>        Optional&lt;String&gt; name = Optional.ofNullable(null);<br>        System.out.println(name.orElseGet(defaultSupplier));  // Default<br>    }<br>}</pre><h3>✅ Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*3JZS0TWOsIrFQN4ND0c_6A.png" /></figure><h3>✅ Differences: Supplier vs Consumer vs Predicate vs Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*XEW5iJDGgh4rKJzJtyYEdQ.png" /></figure><h3>✅ Conclusion</h3><ul><li><strong>Supplier</strong> is ideal when you need to <strong>defer creation</strong> or <strong>generate a value</strong> without passing input.</li><li>It’s simple, clean, and powerful when combined with other functional interfaces.</li><li>You can use it for <strong>random values</strong>, <strong>configuration</strong>, <strong>database connections</strong>, <strong>object factories</strong>, etc.</li></ul><h3>🔍 Java 8 Bi-Functional Interfaces &amp; Specialized Operators</h3><p>✅ BiPredicate&lt;T, U&gt;<br> ✅ BiFunction&lt;T, U, R&gt;<br> ✅ BiConsumer&lt;T, U&gt;<br> ✅ Why no BiSupplier&lt;T, U&gt;<br> ✅ UnaryOperator&lt;T&gt;<br> ✅ BinaryOperator&lt;T&gt;</p><p>Each section includes:</p><ul><li>✔️ Definition and purpose</li><li>✔️ Syntax and valid usage</li><li>✔️ public static void main example</li><li>✔️ Real-world use case</li><li>✔️ Output</li><li>❌ Invalid/compile-time error scenarios</li></ul><h3>✅ BiPredicate&lt;T, U&gt;</h3><blockquote><em>Represents a predicate (boolean-valued function) of two arguments.</em></blockquote><h3>🔹 Syntax:</h3><pre>@FunctionalInterface<br>public interface BiPredicate&lt;T, U&gt; {<br>    boolean test(T t, U u);<br>}</pre><h3>🔹 Example:</h3><pre>import java.util.function.BiPredicate;</pre><pre>public class BiPredicateExample {<br>    public static void main(String[] args) {<br>        BiPredicate&lt;Integer, String&gt; checkLength = (x, str) -&gt; str.length() == x;</pre><pre>        System.out.println(checkLength.test(5, &quot;Shiva&quot;));   // true<br>        System.out.println(checkLength.test(3, &quot;Java&quot;));    // false<br>    }<br>}</pre><h3>✅ Output:</h3><pre>true<br>false</pre><h3>✅ BiFunction&lt;T, U, R&gt;</h3><blockquote><em>Represents a function that accepts two arguments and produces a result.</em></blockquote><h3>🔹 Syntax:</h3><pre>@FunctionalInterface<br>public interface BiFunction&lt;T, U, R&gt; {<br>    R apply(T t, U u);<br>}</pre><h3>🔹 Example:</h3><pre>import java.util.function.BiFunction;</pre><pre>public class BiFunctionExample {<br>    public static void main(String[] args) {<br>        BiFunction&lt;String, String, Integer&gt; totalLength = (str1, str2) -&gt; str1.length() + str2.length();</pre><pre>        System.out.println(&quot;Total Length: &quot; + totalLength.apply(&quot;Java&quot;, &quot;World&quot;));  // 9<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Total Length: 9</pre><h3>✅ BiConsumer&lt;T, U&gt;</h3><blockquote><em>Represents an operation that takes two input arguments and returns no result.</em></blockquote><h3>🔹 Syntax:</h3><pre>@FunctionalInterface<br>public interface BiConsumer&lt;T, U&gt; {<br>    void accept(T t, U u);<br>}</pre><h3>🔹 Example:</h3><pre>import java.util.function.BiConsumer;</pre><pre>public class BiConsumerExample {<br>    public static void main(String[] args) {<br>        BiConsumer&lt;Integer, String&gt; printCombined = (x, str) -&gt; <br>            System.out.println(&quot;Result: &quot; + (x + str.length()));</pre><pre>        printCombined.accept(10, &quot;Hello&quot;);  // 10 + 5 = 15<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Result: 15</pre><h3>❓ Why No BiSupplier&lt;T, U&gt;?</h3><ul><li><strong>Supplier&lt;T&gt;</strong> takes <strong>no argument</strong> and returns a single value of type T.</li><li>Since a method can return only <strong>one value</strong>, there’s <strong>no practical need</strong> for a BiSupplier.</li><li>If you need to return a compound object, just return a List, Map.Entry, Pair, or custom class.</li></ul><h3>✅ UnaryOperator&lt;T&gt; (extends Function&lt;T, T&gt;)</h3><blockquote><em>A specialization of </em><em>Function&lt;T, R&gt; for the case where input and output are the </em><strong><em>same type</em></strong><em>.</em></blockquote><h3>🔹 Syntax:</h3><pre>@FunctionalInterface<br>public interface UnaryOperator&lt;T&gt; extends Function&lt;T, T&gt; {<br>}</pre><h3>🔹 Example:</h3><pre>import java.util.function.UnaryOperator;<br>public class UnaryOperatorExample {<br>    public static void main(String[] args) {<br>        UnaryOperator&lt;Integer&gt; square = x -&gt; x * x;<br>        System.out.println(&quot;Square: &quot; + square.apply(6));  // 36<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Square: 36</pre><h3>✅ BinaryOperator&lt;T&gt; (extends BiFunction&lt;T, T, T&gt;)</h3><blockquote><em>A specialization of </em><em>BiFunction&lt;T, U, R&gt; for </em><strong><em>same-type arguments and return</em></strong><em>.</em></blockquote><h3>🔹 Syntax:</h3><pre>@FunctionalInterface<br>public interface BinaryOperator&lt;T&gt; extends BiFunction&lt;T, T, T&gt; {<br>}</pre><h3>🔹 Example:</h3><pre>import java.util.function.BinaryOperator;</pre><pre>public class BinaryOperatorExample {<br>    public static void main(String[] args) {<br>        BinaryOperator&lt;String&gt; concat = (a, b) -&gt; a + b;<br>        System.out.println(&quot;Concatenated: &quot; + concat.apply(&quot;Java&quot;, &quot;8&quot;));  // Java8<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Concatenated: Java8</pre><h3>🔴 Invalid/Compile-Time Errors</h3><h3>❌ 1. Returning value in BiConsumer</h3><pre>BiConsumer&lt;Integer, String&gt; invalid = (x, y) -&gt; { return x + y.length(); }; // ❌</pre><p>🛑 Error:</p><pre>Void methods cannot return a value</pre><p>✔️ Correct:</p><pre>BiConsumer&lt;Integer, String&gt; valid = (x, y) -&gt; System.out.println(x + y.length());</pre><h3>❌ 2. Using BiPredicate with only one parameter</h3><pre>BiPredicate&lt;String, String&gt; wrong = s -&gt; s.length() &gt; 3;  // ❌</pre><p>🛑 Error:</p><pre>Lambda expression&#39;s signature does not match the signature of the functional interface method</pre><p>✔️ Fix:</p><pre>BiPredicate&lt;String, String&gt; correct = (s1, s2) -&gt; s1.length() &gt; s2.length();</pre><h3>✅ Real-Time Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*Mm8qHO44eowX2Aviei3PAw.png" /></figure><h3>✅ Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*tPhrhia2sx858Ke3x4YB_w.png" /></figure><h3>✅ Conclusion</h3><ul><li>Java 8 introduced BiPredicate, BiFunction, and BiConsumer to handle <strong>2-input scenarios</strong> elegantly.</li><li>UnaryOperator and BinaryOperator are optimized versions of Function and BiFunction where input and output types are the same.</li><li>They enable clean, readable, and reusable functional-style code.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=269092f8e615" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Java 8 (Part-1) — Lambda Expression, Functional Interface , Default and Static Methods in…]]></title>
            <link>https://medium.com/@shivapatel1102001/java-8-part-1-lambda-expression-functional-interface-default-and-static-methods-in-67b98c9ad445?source=rss-cfe90cde530b------2</link>
            <guid isPermaLink="false">https://medium.com/p/67b98c9ad445</guid>
            <category><![CDATA[functionalinterface]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Shivampatel]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 07:30:12 GMT</pubDate>
            <atom:updated>2025-08-01T07:30:12.237Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔥 Java 8 (Part-1) — Lambda Expression, Functional Interface , Default and Static Methods in Interface — Explained with All Scenarios Explained with Examples</h3><blockquote>✅ What is Lambda Expression<br> ✅ Step-by-step transformation into lambda<br> ✅ Valid/invalid cases<br> ✅ Detailed examples with public static void main()<br> ✅ Output<br> ✅ Real-world use case<br> ✅ Advantages &amp; limitations</blockquote><h3>🔷 What is Lambda Expression?</h3><blockquote><strong><em>Lambda expression</em></strong><em> is an </em><strong><em>anonymous function</em></strong><em> (i.e., a function without a name) introduced in </em><strong><em>Java 8</em></strong><em>, used primarily to implement </em><strong><em>functional interfaces</em></strong><em> in a cleaner and more concise way.</em></blockquote><h3>✅ Characteristics of Lambda Expression</h3><ul><li>❌ No <strong>name</strong></li><li>❌ No <strong>return type</strong> (inferred automatically)</li><li>❌ No <strong>access modifier</strong> (public, private, etc.)</li><li>✅ Introduced using -&gt; (arrow token)</li><li>✅ Used to implement interfaces with a <strong>single abstract method</strong> (functional interfaces)</li></ul><h3>🔧 Step-by-Step: Convert Method to Lambda</h3><h3>👇 Consider a method:</h3><pre>public int square(int x) {<br>    return x * x;<br>}</pre><h3>🔁 Convert it to Lambda Expression:</h3><ol><li>❌ Remove access modifier</li><li>❌ Remove return type</li><li>❌ Remove method name</li><li>✅ Add -&gt;</li><li>❌ If single statement: remove {} and return</li></ol><h3>✅ Lambda Equivalent:</h3><pre>x -&gt; x * x;</pre><h3>📘 Syntax Forms of Lambda</h3><pre>() -&gt; System.out.println(&quot;Hello&quot;)                      // No parameter<br>(int a, int b) -&gt; System.out.println(a * b)            // Multiple parameters<br>(String s) -&gt; return s.toLowerCase();                  // With return<br>(s) -&gt; s.toLowerCase();                                // Single param with inferred return<br>s -&gt; s.toLowerCase();                                  // Simplified - no parentheses</pre><h3>❌ Invalid Lambda Cases</h3><pre>// Cannot assign lambda to non-functional interface<br>Runnable r = () -&gt; { return &quot;hello&quot;; };  // Valid<br>Object o = () -&gt; {};                     // ❌ Invalid — Object is not functional<br>// Cannot access non-final local variable<br><br>int x = 10;<br>Runnable r = () -&gt; {<br>    x++;  // ❌ Compile error - variable used in lambda should be effectively final<br>};</pre><h3>✅ Full Working Examples</h3><h3>Example 1: No Parameter Lambda</h3><pre>public class Demo1 {<br>    public static void main(String[] args) {<br>        Runnable r = () -&gt; System.out.println(&quot;Hello from Lambda&quot;);<br>        r.run();<br>    }<br>}</pre><h3>Output:</h3><pre>Hello from Lambda</pre><h3>Example 2: With Parameters</h3><pre>@FunctionalInterface<br>interface MathOperation {<br>    int operate(int a, int b);<br>}<br>public class Demo2 {<br>    public static void main(String[] args) {<br>        MathOperation add = (a, b) -&gt; a + b;<br>        MathOperation mul = (a, b) -&gt; a * b;<br>        System.out.println(&quot;Add: &quot; + add.operate(5, 3));<br>        System.out.println(&quot;Mul: &quot; + mul.operate(5, 3));<br>    }<br>}</pre><h3>Output:</h3><pre>Add: 8<br>Mul: 15</pre><h3>Example 3: Lambda Returning Value</h3><pre>@FunctionalInterface<br>interface StringConverter {<br>    String convert(String input);<br>}<br><br>public class Demo3 {<br>    public static void main(String[] args) {<br>        StringConverter toLower = s -&gt; s.toLowerCase();<br>        System.out.println(toLower.convert(&quot;HELLO&quot;));<br>    }<br>}</pre><h3>Output:</h3><pre>hello</pre><h3>🧠 Real-World Example — Filter List with Lambda</h3><pre>import java.util.Arrays;<br>import java.util.List;<br><br>public class Demo4 {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = Arrays.asList(&quot;Ram&quot;, &quot;Shyam&quot;, &quot;Mohan&quot;);<br>        names.stream()<br>            .filter(name -&gt; name.startsWith(&quot;S&quot;))<br>            .forEach(System.out::println);<br>    }<br>}</pre><h3>Output:</h3><pre>Shyam</pre><h3>⚠️ Lambda Expression and Final Variables</h3><pre>public class Demo5 {<br>    public static void main(String[] args) {<br>        int num = 10;<br>        Runnable r = () -&gt; {<br>            // num++;  // ❌ Compile error<br>            System.out.println(&quot;Value is: &quot; + num);<br>        };<br>        r.run();<br>    }<br>}</pre><h3>Output:</h3><pre>Value is: 10</pre><blockquote><em>⚠️ Variables used inside lambdas must be </em><strong><em>effectively final</em></strong><em>.</em></blockquote><h3>❌ Lambda with More than One Abstract Method (INVALID Case)</h3><h3>📘 Rule Reminder:</h3><blockquote><em>Lambda expressions can only be used with </em><strong><em>functional interfaces</em></strong><em> — interfaces having </em><strong><em>only one abstract method</em></strong><em>.</em></blockquote><h3>❌ Invalid Case: Interface with More Than One Abstract Method</h3><h3>🧾 Code</h3><pre>interface MyInvalidFunctional {<br>    void method1();           // 1st abstract method<br>    void method2();           // 2nd abstract method - breaks functional interface rule<br>}<br><br>public class InvalidLambdaExample {<br>    public static void main(String[] args) {<br>        // ❌ Compile-time error: Lambda expression&#39;s target type is not a functional interface<br>        MyInvalidFunctional obj = () -&gt; System.out.println(&quot;Hello&quot;);<br>        obj.method1();<br>    }<br>}</pre><h3>❌ Compile-Time Error</h3><pre>Error: incompatible types: InvalidLambdaExample.MyInvalidFunctional is not a functional interface<br>    - multiple non-overriding abstract methods found in interface InvalidLambdaExample.MyInvalidFunctional</pre><h3>✅ Valid Case: Interface with Only One Abstract Method</h3><h3>🧾 Code</h3><pre>@FunctionalInterface<br>interface MyFunctional {<br>    void method1();  // only one abstract method<br>    // static or default methods are allowed<br>    default void method2() {<br>        System.out.println(&quot;Default method&quot;);<br>    }<br>}<br><br>public class ValidLambdaExample {<br>    public static void main(String[] args) {<br>        MyFunctional obj = () -&gt; System.out.println(&quot;Hello from method1&quot;);<br>        obj.method1();    // lambda implementation<br>        obj.method2();    // default method<br>    }<br>}</pre><h3>✅ Output</h3><pre>Hello from method1<br>Default method</pre><h3>✅ Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*r-PQB--cOg6KNtea4Ya9Ew.png" /></figure><h3>✅ Advantages of Lambda Expressions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*8o3oFS2sW3scNg5dub9sxQ.png" /></figure><h3>❌ Disadvantages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*0uAoXURyqKDkEMNNstRQew.png" /></figure><h3>✅ When to Use Lambda Expressions?</h3><ul><li>For <strong>single-method interfaces</strong> like Runnable, Comparator, Callable</li><li>With <strong>Stream API</strong> for filtering, mapping, reducing</li><li>For <strong>event handling</strong> (like in Swing or Android)</li><li><strong>Asynchronous programming</strong> with Java 8’s CompletableFuture</li></ul><h3>✅ Functional Interfaces Commonly Used with Lambdas</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*MGERFf5E9Xb612-JXdw1dQ.png" /></figure><h3>📌 Conclusion</h3><p>Lambda expressions are one of the <strong>most powerful features in Java 8</strong>, enabling <strong>functional programming</strong>, <strong>cleaner syntax</strong>, and <strong>enhanced performance</strong>.</p><p>If you’re writing a <strong>functional interface implementation</strong>, <strong>stream operation</strong>, or even a simple <strong>thread</strong>, lambdas help you <strong>reduce clutter</strong> and <strong>write elegant code</strong>.</p><h3>✅ Java 8 — Functional Interface Explained in Detail</h3><blockquote>✅ Detailed explanation<br> ✅ Valid &amp; invalid cases<br> ✅ Real-world analogy<br> ✅ Examples with public static void main and <strong>outputs</strong><br> ✅ Use of @FunctionalInterface<br> ✅ Inheritance behavior</blockquote><h3>🔷 What is a Functional Interface?</h3><blockquote><em>A </em><strong><em>Functional Interface</em></strong><em> is an interface that contains </em><strong><em>exactly one abstract method</em></strong><em>. It can contain </em><strong><em>default</em></strong><em> and </em><strong><em>static methods</em></strong><em>, but only </em><strong><em>one abstract method</em></strong><em>.</em></blockquote><p>Functional interfaces are the foundation for <strong>lambda expressions</strong> and <strong>method references</strong> in Java 8.</p><h3>📌 Example of a Functional Interface</h3><pre>@FunctionalInterface<br>public interface MyInterface {<br>    void greet();  // only one abstract method<br><br>    default void defaultMethod() {<br>        System.out.println(&quot;Default Method&quot;);<br>    }<br><br>    static void staticMethod() {<br>        System.out.println(&quot;Static Method&quot;);<br>    }<br>}</pre><h3>✅ Why Use @FunctionalInterface Annotation?</h3><p>Although it’s not mandatory, using @FunctionalInterface provides the following <strong>advantages</strong>:</p><ol><li>🔒 Ensures the interface has <strong>only one abstract method</strong>.</li><li>🧑‍💻 Helps <strong>avoid mistakes</strong> — adding more abstract methods will result in <strong>compile-time error</strong>.</li><li>🤝 Useful when working with <strong>lambda expressions</strong> — ensures compatibility.</li></ol><h3>❌ Invalid Functional Interface — More Than One Abstract Method</h3><pre>@FunctionalInterface<br>interface InvalidInterface {<br>    void method1();<br>    void method2();  // ❌ compile-time error: Multiple abstract methods not allowed<br>}</pre><h3>✅ Full Working Example with Lambda and Functional Interface</h3><pre>@FunctionalInterface<br>interface Printer {<br>    void print(String message);  // Single abstract method<br><br>    default void defaultPrint() {<br>        System.out.println(&quot;Default print&quot;);<br>    }<br><br>    static void staticPrint() {<br>        System.out.println(&quot;Static print&quot;);<br>    }<br>}<br><br>public class FunctionalInterfaceDemo {<br>    public static void main(String[] args) {<br>        Printer p = (msg) -&gt; System.out.println(&quot;Message: &quot; + msg);<br>        p.print(&quot;Hello from Lambda!&quot;);<br>        p.defaultPrint();  // default method call<br>        Printer.staticPrint();  // static method call<br>    }<br>}</pre><h3>✅ Output</h3><pre>Message: Hello from Lambda!<br>Default print<br>Static print</pre><h3>🧠 Real-World Analogy</h3><p>Think of a <strong>remote control interface</strong> — it must define <strong>one action</strong> (like turnOn()). It may have <strong>default behaviors</strong> (getBatteryLevel()), but the primary behavior must remain singular.</p><h3>🧬 Inheritance in Functional Interfaces</h3><p>Let’s understand how <strong>inheritance</strong> affects a functional interface.</p><h3>✅ Valid Inherited Functional Interface (Same Abstract Method)</h3><pre>@FunctionalInterface<br>interface ParentInterface {<br>    void sayHi();<br>}<br><br>@FunctionalInterface<br>interface ChildInterface extends ParentInterface {<br>    // Re-declaring same method – still valid<br>    void sayHi();<br>}</pre><p>✔ No compiler error — still one abstract method</p><h3>❌ Invalid Inherited Functional Interface (Adds Another Abstract Method)</h3><pre>@FunctionalInterface<br>interface ParentInterface {<br>    void sayHi();<br>}<br><br>@FunctionalInterface<br>interface ChildInterface extends ParentInterface {<br>    void sayHi();      // OK – same method<br>    void sayHello();   // ❌ Additional abstract method – not allowed<br>}</pre><h3>🔴 Error:</h3><pre>ChildInterface is not a functional interface<br>multiple non-overriding abstract methods found</pre><h3>🔁 Functional Interfaces in Java 8 Library</h3><p>Java 8 provides many <strong>predefined functional interfaces</strong> in the java.util.function package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*3wGM9xi6XwZi6gEmOq0LGw.png" /></figure><p>✅ Example: Using Built-In Functional Interface</p><pre>import java.util.function.Predicate;<br><br>public class BuiltInFunctionalDemo {<br>    public static void main(String[] args) {<br>        Predicate&lt;String&gt; isNotEmpty = str -&gt; !str.isEmpty();<br>        System.out.println(isNotEmpty.test(&quot;Hello&quot;));  // true<br>        System.out.println(isNotEmpty.test(&quot;&quot;));       // false<br>    }<br>}</pre><h3>✅ Output</h3><pre>true<br>false</pre><p>✅ Summary Table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*R1S7_52TwSaenVYg8im6sg.png" /></figure><h3>📌 Final Notes</h3><ul><li>Lambda expressions work <strong>only</strong> with <strong>functional interfaces</strong>.</li><li>Use @FunctionalInterface to <strong>safeguard</strong> your interface from accidental additions.</li><li>You can <strong>extend</strong> a functional interface but must ensure <strong>only one abstract method</strong> exists in the hierarchy.</li></ul><h3>🧠 Java 8: Default and Static Methods in Interface — Explained with All Scenarios</h3><h3>🔷 Before Java 8 — Limitations in Interfaces</h3><p>Before Java 8, an interface could contain only:</p><ol><li>✅ public abstract methods</li><li>✅ public static final constants</li><li>❌ <strong>NO</strong> method implementations</li></ol><pre>public interface OldInterface {<br>    void show();              // implicitly public abstract<br>    int MAX = 100;            // implicitly public static final<br>}</pre><h3>🔥 Java 8 Revolution — What’s New?</h3><p>Since Java 8, an interface can contain:</p><ol><li>✅ <strong>Default methods</strong> (with body)</li><li>✅ <strong>Static methods</strong> (with body)</li><li>✅ <strong>Still only one abstract method if used as a Functional Interface</strong></li></ol><h3>✅ What is a Default Method?</h3><blockquote><em>A </em><strong><em>default method</em></strong><em> is a method inside an interface that provides a </em><strong><em>default implementation</em></strong><em> using the </em><em>default keyword.</em></blockquote><h3>🔹 Syntax</h3><pre>default void methodName() {<br>    // method body<br>}</pre><h3>✅ Full Working Example of Default Method</h3><pre>interface MyInterface {<br>    default void greet() {<br>        System.out.println(&quot;Hello from default method!&quot;);<br>    }<br>}<br>public class Demo1 implements MyInterface {<br>    public static void main(String[] args) {<br>        Demo1 obj = new Demo1();<br>        obj.greet();<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Hello from default method!</pre><h3>✅ Overriding Default Method in Implementation Class</h3><pre>interface MyInterface {<br>    default void greet() {<br>        System.out.println(&quot;Default greeting&quot;);<br>    }<br>}<br>public class Demo2 implements MyInterface {<br>    @Override<br>    public void greet() {<br>        System.out.println(&quot;Custom greeting from class&quot;);<br>    }<br>    public static void main(String[] args) {<br>        new Demo2().greet();<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Custom greeting from class</pre><h3>❌ Default Method Conflict — Multiple Inheritance Issue</h3><p>When a class implements <strong>two interfaces</strong> that define <strong>default methods with the same signature</strong>, it results in a <strong>compile-time error</strong>.</p><h3>🔴 Problematic Code</h3><pre>interface A {<br>    default void show() {<br>        System.out.println(&quot;A&quot;);<br>    }<br>}<br>interface B {<br>    default void show() {<br>        System.out.println(&quot;B&quot;);<br>    }<br>}<br>// ❌ Compile-time error<br>public class Demo3 implements A, B {<br>    public static void main(String[] args) {<br>        new Demo3().show();<br>    }<br>}</pre><h3>🔴 Error:</h3><pre>class Demo3 inherits unrelated defaults for show() from types A and B</pre><h3>✅ Solution: Override the Conflicting Method</h3><pre>public class Demo3 implements A, B {<br>    @Override<br>    public void show() {<br>        // Choose manually which one to call<br>        A.super.show();  // or B.super.show();<br>    }<br>    public static void main(String[] args) {<br>        new Demo3().show();  // Output: A<br>    }<br>}</pre><h3>✅ What is a Static Method in Interface?</h3><blockquote><em>A </em><strong><em>static method</em></strong><em> in an interface is a method that belongs to the interface itself, </em><strong><em>not to the implementation class</em></strong><em>.</em></blockquote><h3>🔹 Syntax</h3><pre>static void methodName() {<br>    // method body<br>}</pre><h3>✅ Full Working Example of Static Method</h3><pre>interface MyStaticInterface {<br>    static void display() {<br>        System.out.println(&quot;Static method in interface&quot;);<br>    }<br>}<br>public class Demo4 {<br>    public static void main(String[] args) {<br>        MyStaticInterface.display();  // ✅ Access via interface name<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Static method in interface</pre><h3>❌ Cannot Override Static Method</h3><p>Even if you define a <strong>method with the same signature</strong> in the implementing class, it is NOT an override — it’s a <strong>new method</strong>.</p><pre>interface MyStaticInterface {<br>    static void hello() {<br>        System.out.println(&quot;Interface static hello()&quot;);<br>    }<br>}<br>public class Demo5 implements MyStaticInterface {<br>    public static void hello() {<br>        System.out.println(&quot;Class static hello()&quot;);<br>    }<br>    public static void main(String[] args) {<br>        MyStaticInterface.hello();  // Interface method<br>        Demo5.hello();              // Class method<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Interface static hello()<br>Class static hello()</pre><h3>✅ Can We Have public static void main(String[] args) Inside Interface?</h3><p><strong>Yes!</strong> Since static methods are allowed in interfaces from Java 8, we can define a main method inside an interface and run it directly.</p><pre>interface MainInterface {<br>    static void main(String[] args) {<br>        System.out.println(&quot;Main method inside interface&quot;);<br>    }<br>}</pre><h3>✅ Output (when you run MainInterface):</h3><pre>Main method inside interface</pre><h3>🔁 Inheriting Interfaces with Default and Static Methods</h3><h3>✅ Interface A with default method</h3><h3>✅ Interface B with same default method</h3><h3>❌ Compile-time conflict unless overridden</h3><pre>interface A {<br>    default void show() {<br>        System.out.println(&quot;A&quot;);<br>    }<br>}<br>interface B {<br>    default void show() {<br>        System.out.println(&quot;B&quot;);<br>    }<br>}<br>class Demo6 implements A, B {<br>    public void show() {<br>        System.out.println(&quot;Overridden to resolve conflict&quot;);<br>    }<br>    public static void main(String[] args) {<br>        new Demo6().show();<br>    }<br>}</pre><h3>✅ Output:</h3><pre>Overridden to resolve conflict</pre><h3>✅ Summary Table: Default &amp; Static Methods in Interfaces</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*BNmWBbJAqizZX_FO1bneJw.png" /></figure><h3>✅ Real-Time Use Case</h3><p>You might have a <strong>payment processing</strong> interface with default method:</p><pre>interface PaymentGateway {<br>    default void logTransaction() {<br>        System.out.println(&quot;Default transaction logging&quot;);<br>    }<br><br>    static void getSupportedCurrencies() {<br>        System.out.println(&quot;USD, INR, EUR&quot;);<br>    }<br>}</pre><p>Now each service like CreditCardPayment or UPIPayment can override logging behavior or call static configuration methods.</p><h3>📌 Final Thoughts</h3><p>Java 8 has made interfaces much more powerful and flexible:</p><ul><li>default methods make it easy to evolve APIs without breaking existing implementations.</li><li>static methods enable utility logic without needing separate utility classes.</li><li>With careful handling, <strong>multiple inheritance via interfaces</strong> is now safe and manageable.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67b98c9ad445" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering Java 8 Features — Complete Guide With Real Examples]]></title>
            <link>https://medium.com/@shivapatel1102001/mastering-java-8-features-complete-guide-with-real-examples-0f571678ba8a?source=rss-cfe90cde530b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f571678ba8a</guid>
            <category><![CDATA[java-8-feature]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[stream]]></category>
            <dc:creator><![CDATA[Shivampatel]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 06:30:21 GMT</pubDate>
            <atom:updated>2025-08-01T11:36:36.424Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧠 Mastering Java 8 Features — Complete Guide With Real Examples</h3><p>Great! Below is a complete, structured, and Medium-ready article that covers <strong>all Java 8 features</strong> with:</p><p>✅ Overview<br> ✅ Why it is used<br> ✅ How to use<br> ✅ Advantages &amp; Disadvantages<br> ✅ Valid &amp; Invalid Cases<br> ✅ Real-world Examples<br> ✅ Output-ready code samples</p><p>Java 8 was a revolutionary release that introduced functional-style programming to Java. It brought several powerful features that enhanced productivity, code readability, and performance.</p><h3>🔥 Java 8 Features Overview</h3><p>Here’s a high-level list of Java 8 features:</p><blockquote><strong>1. Lambda Expressions</strong></blockquote><blockquote><strong>2. Functional Interfaces</strong></blockquote><blockquote><strong>3. Stream API</strong></blockquote><blockquote><strong>4. Default and Static Methods in Interfaces</strong></blockquote><blockquote><strong>5. Method References</strong></blockquote><blockquote><strong>6. Optional Class</strong></blockquote><blockquote><strong>7. Date and Time API (java.time package)</strong></blockquote><blockquote><strong>8. Collectors and Collectors.toList()</strong></blockquote><blockquote><strong>9. Nashorn JavaScript Engine</strong></blockquote><blockquote><strong>10. CompletableFuture and java.util.concurrent Enhancements</strong></blockquote><blockquote><strong>11. Base64 Encoding and Decoding</strong></blockquote><blockquote><strong>12. Parallel Streams</strong></blockquote><blockquote><strong>13. New APIs in Collections</strong></blockquote><blockquote><strong>14. Annotations Enhancements</strong></blockquote><blockquote><strong>15. Type Inference Improvements</strong></blockquote><blockquote><strong>16. Repeatable Annotations</strong></blockquote><h3>🔥 Java 8 (Part-1) — Lambda Expression, Functional Interface , Default and Static Methods in Interface — Explained with All Scenarios Explained with Examples</h3><p><a href="https://medium.com/@shivapatel1102001/java-8-part-1-lambda-expression-functional-interface-default-and-static-methods-in-67b98c9ad445">🔥 Java 8 (Part-1) — Lambda Expression, Functional Interface , Default and Static Methods in…</a></p><h3>🔥 Java 8 (Part-2) — Comparator vs Comparable , Predicate, Function, Consumer, Supplier — Explained with Lambda and All Edge Cases</h3><p><a href="https://medium.com/@shivapatel1102001/java-8-part-2-comparator-vs-comparable-predicate-function-consumer-supplier-269092f8e615">🔥 Java 8 (Part-2) — Comparator vs Comparable , Predicate, Function, Consumer, Supplier —…</a></p><h3>1️⃣ Lambda Expressions</h3><blockquote><strong><em>Lambda expression</em></strong><em> is an </em><strong><em>anonymous function</em></strong><em> (i.e., a function without a name) introduced in </em><strong><em>Java 8</em></strong><em>, used primarily to implement </em><strong><em>functional interfaces</em></strong><em> in a cleaner and more concise way.</em></blockquote><h4>✅ Overview</h4><ul><li>Introduced functional programming.</li><li>Enables writing anonymous functions.</li><li>Shorter syntax for implementing functional interfaces.</li></ul><h4>❓ Why Used</h4><ul><li>Reduces boilerplate code.</li><li>Used in Stream API, Runnable, Comparator, etc.</li></ul><h4>💡 How to Use</h4><pre>Runnable r = () -&gt; System.out.println(&quot;Running thread...&quot;);<br>new Thread(r).start();</pre><h4>✅ Valid</h4><pre>(x, y) -&gt; x + y   // two parameters<br>() -&gt; 10          // no parameter<br>x -&gt; x * x        // single parameter</pre><h4>❌ Invalid</h4><pre>(x, y) -&gt; { return x + y }  // missing semicolon or return block issue<br>(int x, y) -&gt; x + y         // type mismatch</pre><h4>📘 Real-Time Example</h4><p>Filtering data from a list:</p><pre>List&lt;String&gt; names = Arrays.asList(&quot;Ram&quot;, &quot;Shyam&quot;, &quot;Mohan&quot;);<br>names.stream().filter(s -&gt; s.startsWith(&quot;S&quot;)).forEach(System.out::println);</pre><h4>✅ Output</h4><pre>Shyam</pre><h4>✅ Advantages</h4><ul><li>Clean and concise syntax.</li><li>Enhances readability.</li><li>Boosts parallel and collection processing.</li></ul><h4>❌ Disadvantages</h4><ul><li>Harder to debug.</li><li>Can be complex for beginners.</li></ul><h3>2️⃣ Functional Interfaces</h3><ul><li>Annotated using @FunctionalInterface.</li></ul><h4>💡 Example</h4><pre>@FunctionalInterface<br>interface MyFunc {<br>    int operate(int a, int b);<br>}</pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        MyFunc add = (a, b) -&gt; a + b;<br>        System.out.println(add.operate(5, 3));  // Output: 8<br>    }<br>}</pre><h4>✅ Output</h4><pre>8</pre><h4>❌ Invalid</h4><pre>@FunctionalInterface<br>interface MyFunc {<br>    int a();<br>    int b(); // Compile-time error: More than one abstract method<br>}</pre><h4>✅ Real-Time Use</h4><p>Used in Comparator, Runnable, Callable, etc.</p><h4>✅ Advantages</h4><ul><li>Encourages functional programming.</li><li>Used with Lambda and Stream APIs.</li></ul><h4>❌ Disadvantages</h4><ul><li>One abstract method limit.</li><li>Misunderstanding can lead to runtime issues.</li></ul><h3>3️⃣ Stream API</h3><h4>✅ Overview</h4><ul><li>Enables functional-style operations on collections.</li><li>Supports sequential and parallel processing.</li></ul><h4>💡 How to Use</h4><pre>List&lt;String&gt; names = Arrays.asList(&quot;John&quot;, &quot;Jane&quot;, &quot;Jack&quot;,&quot;Bob&quot;);<br>names.stream().filter(s -&gt; s.startsWith(&quot;J&quot;)).forEach(System.out::println);</pre><h4>✅ Output</h4><pre>John<br>Jane<br>Jack</pre><h4>✅ Real-Time Example</h4><p>Find employees earning more than 50k:</p><pre>List&lt;Employee&gt; emps = getAllEmployees();<br>List&lt;Employee&gt; highEarners = emps.stream()<br>    .filter(e -&gt; e.getSalary() &gt; 50000)<br>    .collect(Collectors.toList());</pre><h4>✅ Advantages</h4><ul><li>Clean pipeline processing.</li><li>Supports parallelism (parallelStream()).</li></ul><h4>❌ Disadvantages</h4><ul><li>Not reusable.</li><li>Can affect performance if misused.</li></ul><h3>4️⃣ Default and Static Methods in Interfaces</h3><h4>✅ Overview</h4><ul><li>Allow method implementation in interfaces.</li></ul><h4>💡 Example</h4><pre>interface Vehicle {<br>    default void start() {<br>        System.out.println(&quot;Vehicle started&quot;);<br>    }</pre><pre>    static void info() {<br>        System.out.println(&quot;Vehicle interface&quot;);<br>    }<br>}</pre><pre>public class Car implements Vehicle {<br>    public static void main(String[] args) {<br>        new Car().start();     // Output: Vehicle started<br>        Vehicle.info();        // Output: Vehicle interface<br>    }<br>}</pre><h4>❌ Invalid</h4><pre>interface A {<br>    default void m();  // Invalid: No body<br>}</pre><h3>5️⃣ Method References</h3><h4>✅ Overview</h4><ul><li>Shorthand for lambda calling existing method.</li></ul><h4>💡 Example</h4><pre>public class Demo {<br>    public static void print(String s) {<br>        System.out.println(s);<br>    }</pre><pre>    public static void main(String[] args) {<br>        List&lt;String&gt; names = Arrays.asList(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;);<br>        names.forEach(Demo::print); // method reference<br>    }<br>}</pre><h4>✅ Output</h4><pre>A<br>B<br>C</pre><h3>6️⃣ Optional Class</h3><h4>✅ Overview</h4><ul><li>Prevents NullPointerException.</li><li>Represents optional value: present or empty.</li></ul><h4>💡 Example</h4><pre>Optional&lt;String&gt; name = Optional.ofNullable(getName());<br>System.out.println(name.orElse(&quot;Default&quot;));</pre><h4>❌ Invalid</h4><pre>Optional&lt;String&gt; name = Optional.of(null);  // Throws NullPointerException</pre><h3>7️⃣ Date and Time API (java.time)</h3><h4>✅ Overview</h4><ul><li>Replaces legacy Date and Calendar.</li><li>Immutable and thread-safe.</li></ul><h4>💡 Example</h4><pre>LocalDate today = LocalDate.now();<br>LocalDate birthday = LocalDate.of(1990, Month.JANUARY, 1);<br>System.out.println(Period.between(birthday, today).getYears());</pre><h3>8️⃣ Collectors</h3><h4>✅ Overview</h4><ul><li>Part of java.util.stream.Collectors.</li><li>Used to collect Stream elements into a collection.</li></ul><h4>💡 Example</h4><pre>List&lt;String&gt; list = Stream.of(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;).collect(Collectors.toList());</pre><h3>9️⃣ Nashorn JavaScript Engine</h3><h4>✅ Overview</h4><ul><li>Execute JavaScript from Java.</li><li>Replaced by GraalVM later.</li></ul><h4>💡 Example</h4><pre>ScriptEngine engine = new ScriptEngineManager().getEngineByName(&quot;nashorn&quot;);<br>engine.eval(&quot;print(&#39;Hello from JavaScript&#39;);&quot;);</pre><h3>🔟 CompletableFuture</h3><h4>✅ Overview</h4><ul><li>Asynchronous programming.</li><li>Non-blocking operations.</li></ul><h4>💡 Example</h4><pre>CompletableFuture.runAsync(() -&gt; System.out.println(&quot;Task completed&quot;));</pre><h3>1️⃣1️⃣ Base64 Encoding/Decoding</h3><h4>✅ Overview</h4><ul><li>Added in java.util.Base64.</li></ul><h4>💡 Example</h4><pre>String original = &quot;Java8&quot;;<br>String encoded = Base64.getEncoder().encodeToString(original.getBytes());<br>System.out.println(encoded);</pre><h3>1️⃣2️⃣ Parallel Streams</h3><h4>✅ Overview</h4><ul><li>Parallel processing using multiple threads.</li></ul><h4>💡 Example</h4><pre>List&lt;Integer&gt; numbers = Arrays.asList(1,2,3,4,5);<br>numbers.parallelStream().forEach(System.out::println);</pre><h3>1️⃣3️⃣ New Methods in Collections</h3><h4>✅ Overview</h4><ul><li>forEach, removeIf, replaceAll, etc.</li></ul><h4>💡 Example</h4><pre>List&lt;String&gt; list = new ArrayList&lt;&gt;(Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;));<br>list.removeIf(s -&gt; s.equals(&quot;b&quot;));<br>System.out.println(list);</pre><h3>1️⃣4️⃣ Annotations Enhancements</h3><ul><li>Can be used on types (TYPE_USE, TYPE_PARAMETER).</li></ul><h3>1️⃣5️⃣ Type Inference Improvements</h3><ul><li>No need to declare diamond operator with explicit types.</li></ul><pre>List&lt;String&gt; list = new ArrayList&lt;&gt;();</pre><h3>1️⃣6️⃣ Repeatable Annotations</h3><h4>✅ Overview</h4><ul><li>You can apply the same annotation multiple times.</li></ul><pre>@Schedule(day = &quot;Monday&quot;)<br>@Schedule(day = &quot;Friday&quot;)<br>class Work { }</pre><h3>🧾 Final Thoughts</h3><p>Java 8 was a paradigm shift in how Java developers write code. It introduced functional programming while maintaining backward compatibility. By mastering these features, you can write cleaner, more efficient, and modern Java code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f571678ba8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Collection Framework — Complete Guide]]></title>
            <link>https://medium.com/@shivapatel1102001/java-collection-framework-complete-guide-b2b31947f2f6?source=rss-cfe90cde530b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2b31947f2f6</guid>
            <category><![CDATA[iterables]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[java-collection]]></category>
            <dc:creator><![CDATA[Shivampatel]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 18:54:13 GMT</pubDate>
            <atom:updated>2025-07-31T11:31:24.907Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔰Java Collection Framework — Complete Guide</h3><h4><strong>This medium covers :- Overview, Null Handling, Examples, ⚠️ Disadvantages, Ways to Create particular collection, ❌ Invalid or Edge Cases, Comparison Table, Real-Time Use Cases, 📌 Interview Tip</strong></h4><p>for below topics :</p><blockquote><strong>What is the Java Collection Framework?</strong></blockquote><blockquote><strong>📘 1. List Interface</strong></blockquote><blockquote><strong>🔹 a. ArrayList</strong></blockquote><blockquote><strong>🔹 b. LinkedList</strong></blockquote><blockquote><strong>🔹 c. Vector</strong></blockquote><blockquote><strong>🔹 d. Stack</strong></blockquote><blockquote><strong>🔹 e. CopyOnWriteArrayList</strong></blockquote><blockquote><strong>📗 2. Set Interface</strong></blockquote><blockquote><strong>🔹 a. HashSet</strong></blockquote><blockquote><strong>🔹 b. LinkedHashSet</strong></blockquote><blockquote><strong>🔹 c. TreeSet</strong></blockquote><blockquote><strong>📙 3. Queue Interface</strong></blockquote><blockquote><strong>🔹 a. 🥇 </strong><strong>PriorityQueue</strong></blockquote><blockquote><strong>🔹 b. ArrayDeque</strong></blockquote><blockquote><strong>🗺️ Java </strong><strong>Map Interface</strong></blockquote><h4>🔷 What is the Java Collection Framework?</h4><p>The <strong>Java Collection Framework (JCF)</strong> is a unified architecture introduced in <strong>JDK 1.2</strong> for storing and manipulating groups of objects. It standardizes how data is collected, organized, processed, and accessed across the Java platform.</p><p>Before JCF, developers relied on disjointed classes like Vector, Stack, and Hashtable, which were inconsistent and hard to maintain.</p><p>It contains:</p><ul><li><strong>Interfaces</strong>: Abstract data types (e.g., List, Set, Queue, Map)</li><li><strong>Implementations</strong>: Concrete classes (e.g., ArrayList, HashSet, LinkedList)</li><li><strong>Algorithms</strong>: Methods to perform operations such as sorting and searching</li></ul><h3>🔰 Java Collection Framework Hierarchy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*zkwP1dXbtS01yHir.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*_HV_XvQTI7fCe7UIK9jE0g.png" /></figure><h3>📘 1. List Interface</h3><blockquote>📦 Package: java.util</blockquote><blockquote>✅ <strong>Allows :-</strong> Duplicates, multiple null values</blockquote><blockquote>✅ Maintains insertion order <strong>[ORDER PRESERVATION]</strong></blockquote><blockquote>✅ Supports index-based access</blockquote><blockquote>🚫 Not thread-safe (except Vector)</blockquote><blockquote>✅ <strong>Resizable</strong></blockquote><h3>🔹 a. ArrayList</h3><h4>➤ Overview:</h4><ul><li>Dynamic array implementation.</li><li>Quick access via indices.</li><li>Best suited for frequent <strong>read</strong> operations.</li></ul><h4>➤ Null Handling:</h4><p>✅ Multiple nulls allowed</p><h4>➤ Performance:</h4><ul><li>Add: O(1) (amortized)</li><li>Get: O(1)</li><li>Remove (middle): O(n)</li></ul><pre>import java.util.*;<br><br>public class ArrayListDemo {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; list = new ArrayList&lt;&gt;();<br>        list.add(&quot;Java&quot;);<br>        list.add(null);<br>        list.add(&quot;Java&quot;);<br>        System.out.println(list);  // Output: [Java, null, Java]<br>    }<br>}</pre><h4>➤ Usage:</h4><ul><li>Product listings in e-commerce</li><li>Temporary results storage</li></ul><h4>✅ When to Use:</h4><ul><li>Random access needed</li><li>Frequent reads</li></ul><h4>❌ When Not to Use:</h4><ul><li>Frequent insert/remove in middle</li></ul><h4>⚖️ Advantages:</h4><ul><li>Fast random access</li><li>Simple to use</li></ul><h4>⚠️ Disadvantages:</h4><ul><li>Resizing is costly</li><li>Not synchronized</li></ul><h3><strong>Ways to Create ArrayList :-</strong></h3><h3>✅ 1. <strong>Using </strong><strong>new ArrayList&lt;&gt;() – Fully Modifiable List</strong></h3><pre>import java.util.*;<br><br>public class Example1 {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; list = new ArrayList&lt;&gt;();<br>        list.add(&quot;Ram&quot;);<br>        list.add(&quot;Krishna&quot;);<br>        list.add(&quot;Shiv&quot;);<br><br>        list.set(0, &quot;Raj&quot;);          // Modify existing<br>        list.remove(2);              // Remove by index<br><br>        System.out.println(list);    // Output: [Raj, Krishna]<br>    }<br>}</pre><h4>🔹 Allowed Operations:</h4><ul><li>Add, remove, set, get, clear, etc.</li><li>Fully dynamic, modifiable list</li></ul><h4>✅ When to use:</h4><ul><li>If you want a <strong>resizable list</strong> that supports all kinds of operations</li><li>Best for general-purpose list manipulation</li></ul><h4>⚠️ Nulls:</h4><ul><li><strong>Allowed</strong>, including <strong>multiple </strong><strong>null values</strong></li></ul><pre>list.add(null);<br>list.add(null); // ✅ No error</pre><h3>🚫 2. Using Arrays.asList() – Fixed-Size Backed List</h3><pre>import java.util.*;<br><br>  <br>public class Example2 {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; list = Arrays.asList(&quot;Shivam&quot;, &quot;Shivani&quot;, &quot;Niki&quot;);<br>        list.set(1, &quot;Ravi&quot;);  // ✅ Allowed<br>        System.out.println(list);<br>        <br>        // list.add(&quot;New&quot;);   ❌ Throws java.lang.UnsupportedOperationException<br>        // list.remove(0);    ❌ Throws java.lang.UnsupportedOperationException<br>    }<br>}</pre><h4>⚠️ Allowed:</h4><ul><li>You <strong>can update</strong> values using set()</li></ul><h4>❌ Not Allowed:</h4><ul><li><strong>No add/remove</strong>, because it returns a <strong>fixed-size list</strong> backed by the array</li></ul><h4>📌 Runtime Exception:</h4><pre>list.add(&quot;Extra&quot;); // ❌ java.lang.UnsupportedOperationException</pre><h4>✅ When to use:</h4><ul><li>When working with <strong>fixed data</strong>, e.g., as a parameter to a method</li><li>For lightweight read/update operations (but not structural modification)</li></ul><h3>❌ 3. Using List.of() – Unmodifiable List</h3><pre>import java.util.*;<br><br>public class Example3 {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; list = List.of(&quot;Ram&quot;, &quot;Krishna&quot;);<br><br>        // list.set(0, &quot;Ravi&quot;);    ❌ Throws UnsupportedOperationException<br>        // list.add(&quot;Shiv&quot;);       ❌ Throws UnsupportedOperationException<br>  <br>        System.out.println(list); // Output: [Ram, Krishna]<br>    }<br>}</pre><h4>⚠️ Characteristics:</h4><ul><li>Completely <strong>immutable</strong></li><li>No modifications allowed — <strong>not even </strong><strong>set()</strong></li></ul><h4>🚫 All Below Are Illegal:</h4><pre>list.add(&quot;Item&quot;);    // ❌ java.lang.UnsupportedOperationException<br>list.set(0, &quot;New&quot;);  // ❌ java.lang.UnsupportedOperationException<br>list.remove(0);      // ❌ java.lang.UnsupportedOperationException</pre><h4>🧠 When to use:</h4><ul><li>Ideal for creating <strong>read-only constants</strong></li><li>Used in multi-threaded environments to <strong>avoid accidental modification</strong></li></ul><h4>❌ Null Values:</h4><pre>List&lt;String&gt; list = List.of(null); <br>// ❌ java.lang.NullPointerException (runtime)</pre><h3>✅ BONUS: How to Make an Unmodifiable List Modifiable</h3><p>You can wrap it in a new ArrayList:</p><pre>List&lt;String&gt; unmodifiable = List.of(&quot;A&quot;, &quot;B&quot;);<br>List&lt;String&gt; modifiable = new ArrayList&lt;&gt;(unmodifiable);<br><br>modifiable.add(&quot;C&quot;);  // ✅ Now it&#39;s modifiable<br>System.out.println(modifiable); // Output: [A, B, C]</pre><h3>📊 Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nON8R1NDg6mPWo_-mlU1nA.png" /></figure><p>💼 Real-Time Usage in Software</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*7rKsNcXkIwAXKhqM6AErVg.png" /></figure><h3>🔹 b. LinkedList</h3><p><strong>LinkedList </strong>is a linear data structure where each element is separate by the object called as <strong>Node.</strong></p><p>Each node contains two parts <strong>Data </strong>and <strong>Pointer [two pointers] </strong>where first pointer points to next node and another pointer points to previous node.</p><p><strong>LinkedList is very powerful, it can behave as Stack and Queue also.</strong></p><h4>➤ Overview:</h4><ul><li>Doubly linked list</li><li>Better for <strong>insertions and deletions</strong></li></ul><h4>➤ Null Handling:</h4><p>✅ Multiple nulls allowed</p><h4>➤ Time Complexities:</h4><ul><li>Add at beginning/end: O(1)</li><li>Get (by index): O(n)</li></ul><h4>➤ Example:</h4><pre>LinkedList&lt;String&gt; ll = new LinkedList&lt;&gt;();<br>ll.add(&quot;A&quot;);<br>ll.addFirst(&quot;B&quot;);<br>System.out.println(ll); // [B, A]</pre><p>➤ LinkedList can be use as Stack:</p><pre>ll.addLast(&quot;X&quot;);     // push<br>ll.getLast();        // peek<br>ll.removeLast();     // pop</pre><h4>✅ When to Use:</h4><ul><li>Frequent insert/delete</li><li>Need deque behavior (FIFO/LIFO)</li></ul><h4>⚠️ Disadvantages:</h4><ul><li>Slower random access than ArrayList</li></ul><h3>✅ 1. Ways to Create a LinkedList</h3><h3>1.1. Create an Empty LinkedList</h3><pre>import java.util.LinkedList;<br><br>public class Example {<br>    public static void main(String[] args) {<br>        LinkedList&lt;String&gt; list = new LinkedList&lt;&gt;();<br>        list.add(&quot;Ram&quot;);<br>        list.add(&quot;Krishna&quot;);<br>        System.out.println(list);  // Output: [Ram, Krishna]<br>    }<br>}</pre><h3>1.2. Create from Another Collection</h3><pre>import java.util.*;<br><br>public class Example {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; base = List.of(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;);<br>        LinkedList&lt;String&gt; list = new LinkedList&lt;&gt;(base);<br>        System.out.println(list); // Output: [A, B, C]<br>    }<br>}</pre><h3>⚙️ Core Characteristics of LinkedList</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*hvD0kaBl2buPHsDAeAGBRQ.png" /></figure><h3>🧪 Allowed Operations with Examples</h3><h3>✅ Add, Remove, Set, Get</h3><pre>LinkedList&lt;String&gt; list = new LinkedList&lt;&gt;();<br>list.add(&quot;Apple&quot;);<br>list.add(&quot;Banana&quot;);<br>list.add(1, &quot;Cherry&quot;);   // Insert at index<br><br>System.out.println(list); // Output: [Apple, Cherry, Banana]<br><br>list.set(1, &quot;Blueberry&quot;); // Update<br>list.remove(&quot;Banana&quot;);    // Remove by value<br>list.remove(0);           // Remove by index<br>System.out.println(list); // Output: [Blueberry]</pre><h3>🔁 Special Deque Operations (Not Available in ArrayList)</h3><h3>✅ Add/Remove from Head and Tail</h3><pre>LinkedList&lt;String&gt; list = new LinkedList&lt;&gt;();<br>list.addFirst(&quot;One&quot;);<br>list.addLast(&quot;Three&quot;);<br>list.add(1, &quot;Two&quot;);<br><br>System.out.println(list);  // Output: [One, Two, Three]<br><br>list.removeFirst();        // Removes &quot;One&quot;<br>list.removeLast();         // Removes &quot;Three&quot;<br>System.out.println(list);  // Output: [Two]</pre><h3>❌ Invalid/Edge Cases</h3><h3>1. Index Out of Bounds</h3><pre>list.get(5);  <br>// ❌ java.lang.IndexOutOfBoundsException if index &gt;= size</pre><h3>2. Concurrent Modification (Single-threaded list)</h3><pre>LinkedList&lt;String&gt; list = new LinkedList&lt;&gt;();<br>list.add(&quot;A&quot;);<br>for (String s : list) {<br>    list.add(&quot;B&quot;);  <br>    // ❌ java.util.ConcurrentModificationException (at runtime)<br>}</pre><h3>🧪 Null Handling</h3><pre>LinkedList&lt;String&gt; list = new LinkedList&lt;&gt;();<br>list.add(null);<br>list.add(null);<br>System.out.println(list);  // Output: [null, null] ✅ Allowed</pre><p>📊 Summary Table — ArrayList vs LinkedList</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*HT8PTtPLN67GRHoud0C0bQ.png" /></figure><h3>💼 Real-Time Use Cases of LinkedList</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*NByMus7TC9ma9gTF5Uo0Tw.png" /></figure><h3>✅ Best Practice: When to Use LinkedList</h3><ul><li>Choose LinkedList <strong>only</strong> if:</li><li>You need frequent <strong>insertions/removals at the beginning or middle</strong> of the list</li><li>You are using it as a <strong>queue</strong>, <strong>deque</strong>, or <strong>stack</strong></li><li>For <strong>index-based random access</strong>, use ArrayList instead</li></ul><h3>📌 Interview Tip</h3><p><strong>Q: Why is LinkedList slower for random access than ArrayList?</strong><br> <strong>A:</strong> Because in LinkedList, to access element at index i, Java must <strong>traverse from the head or tail</strong> (O(n) time). In contrast, ArrayList accesses elements directly using index offset (O(1) time).</p><h3>🔹 c. Vector</h3><h4>➤ Overview:</h4><ul><li>Legacy synchronized list</li><li>Grows by <strong>doubling</strong> size</li></ul><h4>➤ Thread-safe:</h4><p>✅ Yes (all methods synchronized)</p><h4>➤ Null Handling:</h4><p>✅ Allowed</p><h4>➤ Usage:</h4><ul><li>Rare in new code but useful in multi-threaded environments</li></ul><h4>✅ When to Use:</h4><ul><li>You need thread safety and legacy support</li></ul><h4>⚠️ Disadvantages:</h4><ul><li>Slower due to synchronization overhead</li></ul><h3>✅ 1. Ways to Create a Vector</h3><h3>1.1. Create an Empty Vector</h3><pre>import java.util.Vector;<br><br>public class Example {<br>    public static void main(String[] args) {<br>        Vector&lt;String&gt; vector = new Vector&lt;&gt;();<br>        vector.add(&quot;Ram&quot;);<br>        vector.add(&quot;Krishna&quot;);<br>        System.out.println(vector);  // Output: [Ram, Krishna]<br>    }<br>}</pre><h3>1.2. Create a Vector with Initial Capacity</h3><pre>Vector&lt;String&gt; vector = new Vector&lt;&gt;(10); // initial capacity = 10</pre><h3>1.3. Create a Vector from Another Collection</h3><pre>List&lt;String&gt; list = List.of(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;);<br>Vector&lt;String&gt; vector = new Vector&lt;&gt;(list);<br>System.out.println(vector);  // Output: [A, B, C]</pre><h3>⚙️ Core Characteristics of Vector</h3><p>FeatureDescription</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*d56HHcYa666YWbH8ygTh2w.png" /></figure><h3>🧪 Common Operations with Examples</h3><h3>✅ Add, Remove, Set, Get</h3><pre>Vector&lt;String&gt; vector = new Vector&lt;&gt;();<br>vector.add(&quot;Apple&quot;);<br>vector.add(&quot;Banana&quot;);<br>vector.add(1, &quot;Cherry&quot;);<br><br>System.out.println(vector); // Output: [Apple, Cherry, Banana]<br><br>vector.set(1, &quot;Blueberry&quot;);  // Update<br>System.out.println(vector); // Output: [Apple, Blueberry, Banana]<br><br>vector.remove(&quot;Banana&quot;);    // Remove by value<br>vector.remove(0);           // Remove by index<br>System.out.println(vector); // Output: [Blueberry]</pre><h3>✅ Get Size, Capacity, Contains</h3><pre>Vector&lt;String&gt; vector = new Vector&lt;&gt;(5);<br>vector.add(&quot;A&quot;);<br>vector.add(&quot;B&quot;);<br><br>System.out.println(vector.size());      // Output: 2<br>System.out.println(vector.capacity());  // Output: 5<br>System.out.println(vector.contains(&quot;A&quot;));  // Output: true</pre><h3>❌ Invalid/Edge Cases</h3><h3>❌1. Index Out of Bounds</h3><pre>vector.get(10); <br>// ❌ java.lang.ArrayIndexOutOfBoundsException</pre><h3>✅2. Concurrent Access in Non-Synchronized Collection (Vector handles it correctly)</h3><pre>Vector&lt;String&gt; vector = new Vector&lt;&gt;();<br>vector.add(&quot;A&quot;);<br><br>for (String s : vector) {<br>    vector.add(&quot;B&quot;);  <br>    // ✅ No ConcurrentModificationException (unlike ArrayList)<br>}<br>System.out.println(vector); // Output: [A, B]</pre><h3>🧪 Null Handling</h3><pre>Vector&lt;String&gt; vector = new Vector&lt;&gt;();<br>vector.add(null);<br>vector.add(null);<br>System.out.println(vector);  // Output: [null, null] ✅ Allowed</pre><h3>📊 Summary Table — Vector vs ArrayList vs LinkedList</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*Vg6Xxbpvq5UDr141v3hzUw.png" /></figure><h3>💼 Real-Time Use Cases of Vector</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*Ke1CVh-TKMZDSO_qxthrpQ.png" /></figure><h3>✅ Best Practice: When to Use Vector</h3><ul><li>Use Vector <strong>only</strong> when:</li><li>You need <strong>thread safety</strong> and cannot use Collections.synchronizedList()</li><li>You’re maintaining <strong>legacy code</strong></li><li>Otherwise, use:</li><li>ArrayList for general use</li><li>CopyOnWriteArrayList for thread-safe operations in modern code</li><li>LinkedList for frequent insertions/deletions</li></ul><h3>🔁 Alternative: Collections.synchronizedList(new ArrayList&lt;&gt;())</h3><pre>List&lt;String&gt; safeList = Collections.synchronizedList(new ArrayList&lt;&gt;());</pre><p>Provides modern thread-safe list without Vector’s overhead.</p><h3>📌 Interview Tip</h3><p><strong>Q: Why is </strong><strong>Vector slower than </strong><strong>ArrayList?</strong><br> <strong>A:</strong> Because every method in Vector is synchronized, making it <strong>thread-safe but slower</strong> due to the cost of locking. In single-threaded contexts, ArrayList is preferred.</p><h3>🔹 d. Stack</h3><p>Stack is a <strong>legacy</strong> class in Java that represents a <strong>Last-In-First-Out (LIFO)</strong> data structure. It is a subclass of Vector and is <strong>thread-safe</strong> by default.</p><h4>➤ Overview:</h4><ul><li>Extends Vector</li><li>Follows <strong>LIFO</strong></li></ul><h4>➤ Null Handling:</h4><p>✅ Allowed</p><h4>➤ Methods:</h4><ul><li>push(), pop(), peek(), search()</li></ul><h4>➤ Example:</h4><pre>Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();<br>stack.push(10);<br>stack.push(20);<br>System.out.println(stack.pop());  // 20<br>System.out.println(stack.peek()); // 10</pre><h4>⚠️ Disadvantages:</h4><ul><li>Legacy; prefer Deque (ArrayDeque or LinkedList) for modern stack usage</li></ul><h3>✅ 1. Ways to Create a Stack</h3><h3>1.1. Create an Empty Stack</h3><pre>import java.util.Stack;<br><br>public class Example {<br>    public static void main(String[] args) {<br>        Stack&lt;String&gt; stack = new Stack&lt;&gt;();<br>        stack.push(&quot;Ram&quot;);<br>        stack.push(&quot;Krishna&quot;);<br>        System.out.println(stack);  // Output: [Ram, Krishna]<br>    }<br>}</pre><h3>⚙️ Core Characteristics of Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*gNWiKuT5rMzPNivr7YcZFQ.png" /></figure><h3>🧪 Stack Operations with Examples</h3><h3>✅ push(E item) – Add an item</h3><pre>stack.push(&quot;A&quot;);  // Stack: [A]<br>stack.push(&quot;B&quot;);  // Stack: [A, B]</pre><h3>✅ pop() – Remove and return top item</h3><pre>String top = stack.pop();  // Removes &quot;B&quot;<br>System.out.println(top);   // Output: B<br>System.out.println(stack); // Output: [A]</pre><blockquote><em>❗ Throws </em><em>EmptyStackException if the stack is empty.</em></blockquote><h3>✅ peek() – Return top item without removing</h3><pre>String top = stack.peek(); // Output: A<br>System.out.println(stack); // Stack unchanged: [A]</pre><blockquote><em>❗ Also throws </em><em>EmptyStackException if stack is empty.</em></blockquote><h3>✅ isEmpty() – Check if stack is empty</h3><pre>System.out.println(stack.isEmpty());  // Output: false</pre><h3>✅ search(Object o) – Position from top (1-based)</h3><pre>stack.push(&quot;X&quot;);<br>stack.push(&quot;Y&quot;);<br>System.out.println(stack.search(&quot;X&quot;));  // Output: 2<br>System.out.println(stack.search(&quot;Z&quot;));  // Output: -1 (not found)</pre><h3>❌ Invalid or Edge Cases</h3><h3>1. Calling pop() or peek() on an empty stack</h3><pre>Stack&lt;String&gt; s = new Stack&lt;&gt;();<br>s.pop(); // ❌ java.util.EmptyStackException</pre><h3>🧪 Null Handling</h3><pre>Stack&lt;String&gt; s = new Stack&lt;&gt;();<br>s.push(null);<br>s.push(null);<br>System.out.println(s);  // Output: [null, null]</pre><p>✅ Nulls are allowed and can be pushed/popped/peeked.</p><h3>📊 Comparison Table — Stack vs Deque vs Vector</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*r7pWtMgcjRlu5pJRfaCxLQ.png" /></figure><h3>💼 Real-Time Use Cases of Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*jZ9TMyb9x0zU71EkhBCOtQ.png" /></figure><h3>🔁 Modern Alternative: Deque as Stack</h3><p>Java <strong>recommends</strong> using Deque (like ArrayDeque) for stack-like behavior:</p><pre>Deque&lt;String&gt; stack = new ArrayDeque&lt;&gt;();<br>stack.push(&quot;A&quot;);<br>stack.pop();</pre><p>✅ Faster, ✅ No legacy sync issues, ❌ Doesn’t allow null</p><h3>📌 Interview Tip</h3><p><strong>Q: Should you use </strong><strong>Stack in modern Java?</strong><br> <strong>A:</strong> No. Stack is a legacy class. Prefer Deque (e.g., ArrayDeque) for better performance and cleaner code in modern applications.</p><h3>🔹 e. CopyOnWriteArrayList</h3><p>CopyOnWriteArrayList is a <strong>thread-safe</strong> variant of ArrayList, introduced in java.util.concurrent package. It&#39;s designed for scenarios where <strong>reads vastly outnumber writes</strong>, ensuring thread-safe iteration <strong>without explicit synchronization or </strong><strong>ConcurrentModificationException</strong>.</p><h4>➤ Overview:</h4><ul><li><strong>Thread-safe</strong> list</li><li>On modification, makes a new copy</li><li>Used in <strong>read-heavy, write-rare</strong> situations</li></ul><h4>➤ Null Handling:</h4><p>✅ Allowed</p><h4>➤ Example:</h4><pre>CopyOnWriteArrayList&lt;String&gt; cowList = new CopyOnWriteArrayList&lt;&gt;();<br>cowList.add(&quot;Java&quot;);<br>for (String s : cowList) {<br>    cowList.add(&quot;New&quot;); // does not affect current iteration<br>    System.out.println(s);<br>}</pre><h4>✅ When to Use:</h4><ul><li>Concurrent environments with many reads</li><li>Read-mostly dashboards or config settings</li></ul><h3>✅ 1. How to Create a CopyOnWriteArrayList</h3><h3>1.1. Create an Empty List</h3><pre>import java.util.concurrent.CopyOnWriteArrayList;<br><br>public class Example {<br>    public static void main(String[] args) {<br>        CopyOnWriteArrayList&lt;String&gt; list = new CopyOnWriteArrayList&lt;&gt;();<br>        list.add(&quot;Shivam&quot;);<br>        list.add(&quot;Shivani&quot;);<br>        System.out.println(list); // Output: [Shivam, Shivani]<br>    }<br>}</pre><h3>1.2. Create from Existing Collection</h3><pre>List&lt;String&gt; names = List.of(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;);<br>CopyOnWriteArrayList&lt;String&gt; list = new CopyOnWriteArrayList&lt;&gt;(names);</pre><h3>⚙️ Characteristics of CopyOnWriteArrayList</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*Q6pzbKXEGlti51INQY6dnQ.png" /></figure><h3>🧪 Common Operations with Examples</h3><h3>✅ Add Elements</h3><pre>CopyOnWriteArrayList&lt;String&gt; list = new CopyOnWriteArrayList&lt;&gt;();<br>list.add(&quot;A&quot;);<br>list.add(&quot;B&quot;);</pre><h3>✅ Remove Elements</h3><pre>list.remove(&quot;B&quot;);  // Removes &quot;B&quot;</pre><h3>✅ Set (Update) Elements</h3><pre>list.set(0, &quot;Shivam&quot;);  // Replace &quot;A&quot; with &quot;Shivam&quot;</pre><h3>✅ Read Elements</h3><pre>System.out.println(list.get(0));  // Output: Shivam</pre><h3>✅ Iterate (Fail-safe Iterator)</h3><pre>for (String s : list) {<br>    System.out.println(s);<br>    list.add(&quot;New&quot;);  // No ConcurrentModificationException!<br>}</pre><blockquote><em>Internally, the iterator uses a </em><strong><em>snapshot</em></strong><em> of the array at the time of creation.</em></blockquote><h3>❗ Important Notes</h3><ul><li>✅ No need to explicitly synchronize</li><li>❗ Modifying during iteration is safe, but modifications won’t be reflected in the current iteration.</li><li>❗ Each write creates a <strong>new copy of the internal array</strong> → performance hit on write-heavy use cases</li></ul><h3>❗ Modifying during iteration is safe, but changes won’t reflect in current iteration</h3><h3>📌 Explanation:</h3><p>When you iterate over a CopyOnWriteArrayList, it uses a <strong>snapshot</strong> of the list taken at the time the iterator was created. If the list is modified <strong>after the iterator is created</strong>, those modifications <strong>won’t be visible</strong> in that loop iteration.</p><p>This behavior makes iteration <strong>thread-safe</strong> and <strong>free of </strong><strong>ConcurrentModificationException</strong>, but at the cost of <strong>not reflecting updates during the loop</strong>.</p><h3>✅ Code Example:</h3><pre>import java.util.concurrent.CopyOnWriteArrayList;<br><br>public class SnapshotExample {<br>    public static void main(String[] args) {<br>        CopyOnWriteArrayList&lt;String&gt; userList = new CopyOnWriteArrayList&lt;&gt;();<br>        userList.add(&quot;Shiv&quot;);<br>        userList.add(&quot;Parvati&quot;);<br>        userList.add(&quot;Ganesh&quot;);<br><br>        for (String user : userList) {<br>            System.out.println(&quot;Sending email to: &quot; + user);<br><br>            // Add a new user during iteration<br>            userList.add(&quot;NewUser&quot;);<br>        }<br><br>        System.out.println(&quot;Final list: &quot; + userList);<br>    }<br>}</pre><h3>🧾 Output:</h3><pre>Sending email to: Shiv<br>Sending email to: Parvati<br>Sending email to: Ganesh<br>Final list: [Shiv, Parvati, Ganesh , NewUser, NewUser, NewUser]</pre><h3>🔍 What Happened?</h3><ul><li>You added “NewUser” during iteration.</li><li>But the loop <strong>did not process</strong> “NewUser” even once.</li><li>Why? Because the iterator was working on a <strong>snapshot</strong> of the original list ([Shivam, Shivani, Niki]) taken <strong>before</strong> the loop began.</li></ul><h3>💡 Real-World Example: Email Notification System</h3><p>Imagine a <strong>notification system</strong> sending alerts to registered users:</p><pre>CopyOnWriteArrayList&lt;String&gt; emailList = new CopyOnWriteArrayList&lt;&gt;();<br>emailList.add(&quot;alice@example.com&quot;);<br>emailList.add(&quot;bob@example.com&quot;);</pre><pre>// A new user signs up during email sending<br>for (String email : emailList) {<br>    sendEmail(email);<br>    emailList.add(&quot;newUser@example.com&quot;);<br>}</pre><p>Here:</p><ul><li>All original users receive emails.</li><li>New user (newUser@example.com) <strong>won’t</strong> receive email <strong>in this run</strong>.</li><li>But the new user is added safely, <strong>without breaking the iteration</strong>.</li></ul><h3>✅ Key Takeaways</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*fiUM0ugQxdzxh8G94rq27Q.png" /></figure><h3>❌ Invalid Cases &amp; Limitations</h3><h3>1. High Write Volume</h3><pre>// Inefficient if you&#39;re modifying a lot<br>for (int i = 0; i &lt; 1000000; i++) {<br>    list.add(&quot;Item&quot;);  // ❌ Slow due to copying on every write<br>}</pre><blockquote><em>Use </em><em>ArrayList or </em><em>Vector in single-threaded or write-intensive cases.</em></blockquote><h3>📊 Comparison with Other Lists</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*D-r4z2OWcKnOhfK818YuTg.png" /></figure><h3>💼 Real-Time Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*XXM-Cbr8n0G83m3TplLopA.png" /></figure><h3>📌 Interview Tip</h3><blockquote><strong><em>Q:</em></strong><em> Why does </em><em>CopyOnWriteArrayList not throw </em><em>ConcurrentModificationException?</em></blockquote><blockquote><strong><em>A:</em></strong><em> Because it works on a </em><strong><em>snapshot copy</em></strong><em> of the array during iteration. The current state of the list is frozen for the iterator, even if the list is modified later.</em></blockquote><h3>✅ Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*FZL3o94ZzZ5g6PbHO4maVQ.png" /></figure><h3>📗 2. Set Interface</h3><ul><li>No duplicates allowed</li><li>At most <strong>one </strong><strong>null</strong> allowed (depends on implementation)</li><li>No index-based access</li></ul><h3>🔰 Key Features of Set</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*DHFwyei6k3qXuIMhqdaxNQ.png" /></figure><h3>🔧 Ways to Create a Set</h3><h3>🔹 a. HashSet</h3><p>HashSet is a part of the Java Collection Framework and implements the Set interface. It is backed by a <strong>HashMap</strong>, and its primary feature is storing <strong>unique elements</strong> with <strong>no guaranteed order</strong>.</p><h3>🔰 Key Features of HashSet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*-8KqVTjtivuOlltSloet4g.png" /></figure><h4>➤ Overview:</h4><ul><li>Backed by a HashMap</li><li>No ordering guarantee</li></ul><h4>➤ Null Handling:</h4><p>✅ Allows 1 null</p><h4>➤ Example:</h4><pre>Set&lt;String&gt; set = new HashSet&lt;&gt;();<br>set.add(&quot;Java&quot;);<br>set.add(&quot;Java&quot;);<br>set.add(null);<br>System.out.println(set); // [Java, null]</pre><h4>✅ When to Use:</h4><ul><li>Need uniqueness</li><li>Don’t care about order</li></ul><h3>🔧 Ways to Create a HashSet</h3><h3>✅ 1. Default Constructor</h3><pre>Set&lt;String&gt; names = new HashSet&lt;&gt;();<br>names.add(&quot;Shivam&quot;);<br>names.add(&quot;Shivani&quot;);</pre><h3>✅ 2. With Initial Capacity</h3><pre>Set&lt;Integer&gt; ids = new HashSet&lt;&gt;(100); // Capacity = 100</pre><h3>✅ 3. With Capacity and Load Factor</h3><pre>Set&lt;String&gt; emails = new HashSet&lt;&gt;(100, 0.75f);</pre><h3>✅ 4. Copy From Another Collection</h3><pre>List&lt;String&gt; list = Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);<br>Set&lt;String&gt; set = new HashSet&lt;&gt;(list);</pre><h3>🧪 Valid and Invalid Cases</h3><h3>✅ Valid</h3><pre>Set&lt;String&gt; set = new HashSet&lt;&gt;();<br>set.add(&quot;apple&quot;);<br>set.add(null); // ✅ Allowed<br>System.out.println(set.contains(&quot;apple&quot;)); // true</pre><h3>❌ Invalid</h3><pre>Set&lt;String&gt; set = new HashSet&lt;&gt;();<br>set.get(0); // ❌ Compile-time error: get() not available in Set</pre><h3>⚠️ Null Behavior</h3><ul><li>Only <strong>one </strong><strong>null element</strong> allowed</li><li>Subsequent null adds are ignored</li></ul><pre>Set&lt;String&gt; set = new HashSet&lt;&gt;();<br>set.add(null);<br>set.add(null);<br>System.out.println(set); // Output: [null]</pre><h3>⚖️ Comparison with Other Sets</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*L_D56zpb8nEUst3ybPdCMA.png" /></figure><h3>💡 Real-World Example: Unique Username Storage</h3><pre>Set&lt;String&gt; usernames = new HashSet&lt;&gt;();<br><br>usernames.add(&quot;shivam123&quot;);<br>usernames.add(&quot;shivam123&quot;); // Duplicate ignored<br>usernames.add(&quot;shivani&quot;);<br><br>System.out.println(usernames); // [shivam123, shivani]</pre><p>✅ Use case: Prevent duplicates in login registration systems.</p><h3>📊 Advantages &amp; Disadvantages</h3><h3>✅ Advantages</h3><ul><li>Fast performance: O(1) for add, remove, and contains</li><li>Prevents duplicates automatically</li><li>Lightweight and flexible</li></ul><h3>❌ Disadvantages</h3><ul><li>No ordering of elements</li><li>Not thread-safe</li><li>Not suitable if sorted/insertion order is required</li></ul><h3>🧾 Output Example</h3><pre>Set&lt;String&gt; colors = new HashSet&lt;&gt;();<br>colors.add(&quot;Red&quot;);<br>colors.add(&quot;Green&quot;);<br>colors.add(&quot;Red&quot;);<br>System.out.println(colors);</pre><p>🟢 Output:</p><pre>[Red, Green] // No duplicates, order not guaranteed</pre><h3>🧠 Interview Tip</h3><ul><li>HashSet is best when <strong>duplicate-free, fast lookups</strong> are needed and <strong>element order is not important</strong>.</li><li>Internally, HashSet uses HashMap where values are stored as map keys and a constant dummy object as the value.</li></ul><h3>🔄 Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*niFEgEApoJzIk3nw48waOw.png" /></figure><h3>🔹 b. LinkedHashSet</h3><p>LinkedHashSet is a subclass of HashSet and part of the Java Collection Framework. It <strong>preserves insertion order</strong> while ensuring <strong>uniqueness</strong> of elements.</p><h4>➤ Overview:</h4><ul><li>Maintains insertion order</li></ul><h4>➤ Null Handling:</h4><p>✅ One null allowed</p><h3>🔰 Key Features of LinkedHashSet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*AxLQodqttxwVUlhKZiaWjQ.png" /></figure><h3>🔧 Ways to Create LinkedHashSet</h3><h3>✅ 1. Default Constructor</h3><pre>Set&lt;String&gt; names = new LinkedHashSet&lt;&gt;();<br>names.add(&quot;Shivam&quot;);<br>names.add(&quot;Shivani&quot;);</pre><h3>✅ 2. With Initial Capacity</h3><pre>Set&lt;String&gt; set = new LinkedHashSet&lt;&gt;(100);</pre><h3>✅ 3. With Capacity and Load Factor</h3><pre>Set&lt;String&gt; set = new LinkedHashSet&lt;&gt;(100, 0.75f);</pre><h3>✅ 4. From Another Collection</h3><pre>List&lt;String&gt; list = Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;a&quot;);<br>Set&lt;String&gt; set = new LinkedHashSet&lt;&gt;(list); // Removes duplicate &quot;a&quot;</pre><h3>🔄 Behavior Compared to HashSet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*37UVTJBo1riOMAeHCd5P2A.png" /></figure><h3>✅ Valid and ❌ Invalid Cases</h3><h3>✅ Valid</h3><pre>Set&lt;Integer&gt; set = new LinkedHashSet&lt;&gt;();<br>set.add(10);<br>set.add(20);<br>set.add(10); // Duplicate ignored<br>System.out.println(set); // [10, 20]</pre><h3>❌ Invalid</h3><pre>Set&lt;String&gt; set = new LinkedHashSet&lt;&gt;();<br>set.get(0); // ❌ Compilation error – no indexing in Set</pre><h3>🧪 Null Handling</h3><ul><li>You can insert <strong>one </strong><strong>null element</strong></li></ul><pre>Set&lt;String&gt; set = new LinkedHashSet&lt;&gt;();<br>set.add(null);<br>set.add(null); // Ignored<br>System.out.println(set); // [null]</pre><h3>🚀 Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*2RVp1bzMVjPhP_UEiiv2HA.png" /></figure><h3>🧠 Real-World Example: Preserving Order</h3><pre>Set&lt;String&gt; history = new LinkedHashSet&lt;&gt;();<br>history.add(&quot;Login&quot;);<br>history.add(&quot;ViewProfile&quot;);<br>history.add(&quot;Logout&quot;);<br>history.add(&quot;Login&quot;); // Duplicate ignored<br>System.out.println(history);</pre><p>🟢 Output:</p><pre>[Login, ViewProfile, Logout]</pre><p>✅ <strong>Use Case</strong>: Track actions in the order they happened <strong>without duplicates</strong>.</p><h3>📉 Advantages &amp; Disadvantages</h3><h3>✅ Advantages</h3><ul><li>Maintains <strong>insertion order</strong></li><li>Ensures <strong>uniqueness</strong></li><li>Faster than TreeSet</li></ul><h3>❌ Disadvantages</h3><ul><li>Slightly slower than HashSet (due to ordering)</li><li>No sorting (unlike TreeSet)</li><li>Not thread-safe</li></ul><h3>📊 Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*CmAevzIG_v2y0gA2B97RCw.png" /></figure><h3>🔎 Internal Working</h3><ul><li>Internally uses LinkedHashMap&lt;K, Object&gt;</li><li>The value is a dummy constant object</li><li>Maintains a doubly-linked list to preserve order</li></ul><h3>💬 Interview Tip</h3><ul><li>Use LinkedHashSet when you want to eliminate duplicates <strong>while preserving the order</strong> of insertion.</li><li>Ideal when order is important (e.g., browsing history, unique logs, API access order).</li></ul><h3>✅ Output Example</h3><pre>Set&lt;String&gt; tasks = new LinkedHashSet&lt;&gt;();<br>tasks.add(&quot;Build&quot;);<br>tasks.add(&quot;Test&quot;);<br>tasks.add(&quot;Deploy&quot;);<br>tasks.add(&quot;Build&quot;);<br>System.out.println(tasks); // [Build, Test, Deploy]</pre><h3>🔹 c. TreeSet</h3><p>TreeSet is a part of the Java Collection Framework that implements the Set interface and stores elements in <strong>sorted (natural or custom)</strong> order using a <strong>Red-Black Tree</strong> internally.</p><h4>➤ Overview:</h4><ul><li>Sorted Set (natural or custom comparator)</li><li>Uses Red-Black Tree</li></ul><h4>➤ Null Handling:</h4><p>❌ NullPointerException if you add null</p><h4>➤ Example:</h4><pre>TreeSet&lt;Integer&gt; ts = new TreeSet&lt;&gt;();<br>ts.add(null); // ❌ NullPointerException</pre><h4>✅ When to Use:</h4><ul><li>Need ordered, unique elements</li></ul><h3>🔰 Key Features of TreeSet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*sqt4cO9vEZuUikZjKtQH9Q.png" /></figure><h3>🔧 Ways to Create a TreeSet</h3><h3>✅ 1. Default Constructor (Natural Ordering)</h3><pre>Set&lt;Integer&gt; numbers = new TreeSet&lt;&gt;();<br>numbers.add(5);<br>numbers.add(1);<br>numbers.add(3);<br>System.out.println(numbers); // [1, 3, 5]</pre><h3>✅ 2. Constructor with Comparator (Custom Ordering)</h3><pre>Set&lt;String&gt; names = new TreeSet&lt;&gt;(Comparator.reverseOrder());<br>names.add(&quot;Shivam&quot;);<br>names.add(&quot;Amit&quot;);<br>System.out.println(names); // [Shivam, Amit]</pre><h3>✅ 3. From Another Collection</h3><pre>List&lt;String&gt; list = Arrays.asList(&quot;Banana&quot;, &quot;Apple&quot;, &quot;Banana&quot;);<br>Set&lt;String&gt; fruits = new TreeSet&lt;&gt;(list); // Removes duplicates and sorts<br>System.out.println(fruits); // [Apple, Banana]</pre><h3>📌 Sorting Behavior</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*X2p2cyXzHdiib8v9IRhdyg.png" /></figure><h3>✅ Valid and ❌ Invalid Cases</h3><h3>✅ Valid</h3><pre>Set&lt;String&gt; set = new TreeSet&lt;&gt;();<br>set.add(&quot;Apple&quot;);<br>set.add(&quot;Banana&quot;);<br>System.out.println(set); // [Apple, Banana]</pre><h3>❌ Invalid — Mixing null with other values</h3><pre>Set&lt;String&gt; set = new TreeSet&lt;&gt;();<br>set.add(null); // ❌ NullPointerException (if more elements are added after)</pre><h3>✅ Valid — Only null (in isolation)</h3><pre>Set&lt;String&gt; set = new TreeSet&lt;&gt;();<br>set.add(null); // Only if no other element added → runtime error will still happen</pre><h3>✅ Valid — Custom comparator handles null</h3><pre>Set&lt;String&gt; set = new TreeSet&lt;&gt;(Comparator.nullsFirst(Comparator.naturalOrder()));<br>set.add(null);<br>set.add(&quot;Zebra&quot;);<br>System.out.println(set); // [null, Zebra]</pre><h3>🚀 Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*9yIjbJ3z9Ym7bBX2eUg_nA.png" /></figure><h3>🧠 Real-World Example — Sorted Leaderboard</h3><pre>Set&lt;Integer&gt; scores = new TreeSet&lt;&gt;(Comparator.reverseOrder());<br>scores.add(100);<br>scores.add(85);<br>scores.add(90);<br>System.out.println(scores); // [100, 90, 85]</pre><p>✅ Used in: <strong>Leaderboards</strong>, <strong>Range Queries</strong>, <strong>Auto-sorting systems</strong></p><h3>📉 Advantages &amp; Disadvantages</h3><h3>✅ Advantages</h3><ul><li>Maintains <strong>sorted order</strong></li><li>Removes duplicates</li><li>Offers <strong>range views</strong> via headSet, tailSet, subSet</li></ul><h3>❌ Disadvantages</h3><ul><li>Slower than HashSet or LinkedHashSet</li><li>Doesn’t allow null unless explicitly handled</li><li>Requires objects to be <strong>comparable or provide a comparator</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*mxAKnF6Rz83c9tKL_a1cNg.png" /></figure><h3>🧩 Additional TreeSet Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*EcOduOzoZVzP3R02jDXMuQ.png" /></figure><h3>📊 Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*x2s64iGaOrMDorD6zxE58Q.png" /></figure><h3>🔎 Internal Working</h3><ul><li>Uses a <strong>self-balancing binary search tree</strong> (Red-Black Tree)</li><li>Maintains sorting at all times during insertion/deletion</li></ul><h3>💬 Interview Tip</h3><blockquote><em>“Use </em><em>TreeSet when you need a collection with </em><strong><em>no duplicates and always sorted elements</em></strong><em>, but can tolerate slightly slower performance.&quot;</em></blockquote><h3>✅ Output Example</h3><pre>Set&lt;String&gt; names = new TreeSet&lt;&gt;();<br>names.add(&quot;Zebra&quot;);<br>names.add(&quot;Apple&quot;);<br>names.add(&quot;Mango&quot;);<br>System.out.println(names); // [Apple, Mango, Zebra]</pre><h3>📙 3. Queue Interface</h3><h3>📌 Overview</h3><p>The Queue interface in Java is part of the java.util package and represents a <strong>First-In-First-Out (FIFO)</strong> collection. It&#39;s ideal for scenarios where <strong>elements are processed in the order they were added</strong>—like task scheduling, job queues, etc.</p><ul><li>FIFO principle</li><li>Includes PriorityQueue, ArrayDeque, etc.</li></ul><h3>🔍 Characteristics of Queue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*8mfMFm0gTySSN4FgGfxk0A.png" /></figure><h3>🔧 Common Implementations of Queue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*jcriajj8E-K3g0L5wT3TjA.png" /></figure><h3>✅ Methods in Queue Interface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*OBgSAwivt-6S206hNzw3sQ.png" /></figure><h3>🔧 Ways to Create Queue</h3><h3>✅ 1. Using LinkedList</h3><pre>Queue&lt;String&gt; queue = new LinkedList&lt;&gt;();<br>queue.offer(&quot;A&quot;);<br>queue.offer(&quot;B&quot;);<br>System.out.println(queue); // [A, B]</pre><h3>✅ 2. Using PriorityQueue</h3><pre>Queue&lt;Integer&gt; priorityQueue = new PriorityQueue&lt;&gt;();<br>priorityQueue.offer(30);<br>priorityQueue.offer(10);<br>priorityQueue.offer(20);<br>System.out.println(priorityQueue); // [10, 30, 20] – internal min-heap ordering</pre><h3>✅ 3. Using ArrayDeque (Faster alternative to LinkedList)</h3><pre>Queue&lt;String&gt; dequeQueue = new ArrayDeque&lt;&gt;();<br>dequeQueue.add(&quot;X&quot;);<br>dequeQueue.add(&quot;Y&quot;);<br>System.out.println(dequeQueue); // [X, Y]</pre><h3>🧠 Real-World Examples</h3><h3>✅ 1. Print Job Scheduling</h3><pre>Queue&lt;String&gt; printQueue = new LinkedList&lt;&gt;();<br>printQueue.offer(&quot;Job1&quot;);<br>printQueue.offer(&quot;Job2&quot;);<br>System.out.println(printQueue.poll()); // Job1<br>System.out.println(printQueue.poll()); // Job2</pre><h3>✅ 2. Task Queue in a Server</h3><pre>Queue&lt;String&gt; taskQueue = new ConcurrentLinkedQueue&lt;&gt;();<br>taskQueue.offer(&quot;ProcessUserLogin&quot;);<br>taskQueue.offer(&quot;FetchData&quot;);</pre><h3>✅ Valid and ❌ Invalid Cases</h3><h3>✅ Valid — Using offer() and poll()</h3><pre>Queue&lt;Integer&gt; q = new LinkedList&lt;&gt;();<br>q.offer(10);<br>q.offer(20);<br>System.out.println(q.poll()); // 10</pre><h3>❌ Invalid — Using add() on full capacity queue (like ArrayBlockingQueue)</h3><pre>Queue&lt;Integer&gt; q = new ArrayBlockingQueue&lt;&gt;(2);<br>q.add(1);<br>q.add(2);<br>q.add(3); // ❌ Throws IllegalStateException</pre><h3>⚙️ Queue vs Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*Yme72Y5w6H9lB0YkVLjaNQ.png" /></figure><h3>🆚 Queue vs Deque</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*_6dpnzuLZCdJjBqWX53tmw.png" /></figure><h3>📉 Performance (Depends on Implementation)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*gTOJz9R0BujKdahDDopXfA.png" /></figure><h3>🚫 Null Element Handling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*Hk4Js_ZIg54wbg28sZ0sLw.png" /></figure><h3>📦 Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*QwOr1Wely1kY1IEyMtyDhQ.png" /></figure><h3>📌 Interview Tip</h3><blockquote><em>“Use </em><em>Queue when tasks need to be processed in order—especially useful in asynchronous systems, printers, thread pools, and messaging systems.”</em></blockquote><p>Let me know if you’d like to go into:</p><ul><li>PriorityQueue</li><li>Deque and ArrayDeque</li><li>Thread-safe queues (ConcurrentLinkedQueue, BlockingQueue)</li><li>Queue use in multithreading and producer-consumer pattern</li></ul><h3>🔹 a. 🥇 PriorityQueue</h3><h3>📌 Overview</h3><p>A PriorityQueue in Java is a <strong>special kind of queue</strong> where <strong>elements are ordered based on priority</strong> rather than insertion order. It uses a <strong>min-heap</strong> as the default implementation and is part of the java.util package.</p><h4>➤ Overview:</h4><ul><li>Orders elements by natural/comparator order</li></ul><h4>➤ Null Handling:</h4><p>❌ Not allowed</p><h4>➤ Example:</h4><pre>Queue&lt;Integer&gt; pq = new PriorityQueue&lt;&gt;();<br>pq.add(5);<br>pq.add(1);<br>System.out.println(pq.poll()); // 1</pre><h3>🔍 Characteristics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*0RtNQZlK5TMF4lA0F0GBBQ.png" /></figure><h3>🛠️ Constructors (Ways to Create PriorityQueue)</h3><h3>✅ 1. Default Constructor (Natural Ordering)</h3><pre>PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;&gt;();<br>pq.add(30);<br>pq.add(10);<br>pq.add(20);<br>System.out.println(pq); // Output: [10, 30, 20] internally ordered as min-heap</pre><h3>✅ 2. With Initial Capacity</h3><pre>PriorityQueue&lt;String&gt; pq = new PriorityQueue&lt;&gt;(20);</pre><h3>✅ 3. With Comparator (Custom Priority)</h3><pre>PriorityQueue&lt;Integer&gt; maxPQ = new PriorityQueue&lt;&gt;(Comparator.reverseOrder());<br>maxPQ.add(10);<br>maxPQ.add(20);<br>maxPQ.add(5);<br>System.out.println(maxPQ.poll()); // 20 (max comes first)</pre><h3>✅ 4. From Collection</h3><pre>List&lt;Integer&gt; list = Arrays.asList(9, 3, 5, 1);<br>PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;&gt;(list);</pre><h3>✅ Methods (Inherited from Queue Interface)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*gcRoClPlFCKGgTre27LOHg.png" /></figure><h3>🧠 Real-World Examples</h3><h3>1. Job Scheduling with Priority</h3><pre>class Job {<br>    String name;<br>    int priority;<br><br>        Job(String name, int priority) {<br>        this.name = name;<br>        this.priority = priority;<br>    }</pre><pre>    public String toString() {<br>        return name + &quot; (Priority: &quot; + priority + &quot;)&quot;;<br>    }<br>}</pre><pre>PriorityQueue&lt;Job&gt; jobQueue = new PriorityQueue&lt;&gt;(Comparator.comparingInt(j -&gt; j.priority));<br>jobQueue.add(new Job(&quot;Job1&quot;, 3));<br>jobQueue.add(new Job(&quot;Job2&quot;, 1));<br>jobQueue.add(new Job(&quot;Job3&quot;, 2));</pre><pre>System.out.println(jobQueue.poll()); // Job2 (Priority: 1)</pre><h3>2. Emergency Room Triage</h3><ul><li>Patients are added to the queue.</li><li>More critical patients (lower priority value) are treated first.</li></ul><h3>✅ Valid &amp; ❌ Invalid Scenarios</h3><h3>✅ Valid — With Custom Comparator</h3><pre>PriorityQueue&lt;String&gt; pq = new PriorityQueue&lt;&gt;(Comparator.reverseOrder());<br>pq.offer(&quot;Apple&quot;);<br>pq.offer(&quot;Mango&quot;);<br>System.out.println(pq.poll()); // Mango (reverse alphabetical)</pre><h3>❌ Invalid — Inserting Null Element</h3><pre>PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;&gt;();<br>pq.add(null); // ❌ Throws NullPointerException</pre><h3>❌ Invalid — Heterogeneous Data (Different Types)</h3><pre>PriorityQueue pq = new PriorityQueue();<br>pq.add(&quot;A&quot;);<br>pq.add(1); // ❌ Throws ClassCastException</pre><h3>🔁 Iteration Order (Important to Note)</h3><p>PriorityQueue does not guarantee any <strong>fixed iteration order</strong>.</p><pre>PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;&gt;();<br>pq.add(10); pq.add(5); pq.add(15);<br>System.out.println(pq); // Output may be: [5, 10, 15]</pre><p>Use .poll() repeatedly if you want sorted order:</p><pre>while (!pq.isEmpty()) {<br>    System.out.print(pq.poll() + &quot; &quot;);<br>}<br>// Output: 5 10 15</pre><h3>🧾 Internal Working</h3><ul><li>Internally uses a <strong>binary heap</strong> (array-based min-heap).</li><li>On every insertion/removal, the heap is restructured to maintain priority.</li></ul><h3>⛓️ PriorityQueue vs LinkedList (as Queue)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*FOQrDjDhWXE4xjAziMiwIg.png" /></figure><h3>📉 Time Complexity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*ThvYkOI3mcBcSB81pHgjGQ.png" /></figure><h3>🔐 Thread-Safety</h3><ul><li><strong>Not thread-safe</strong>.</li><li>Use PriorityBlockingQueue for thread-safe priority queues in concurrent scenarios.</li></ul><h3>📦 Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*_WvLgV6qODAw_tgxP59Ywg.png" /></figure><h3>📌 Interview Tip</h3><blockquote><em>“</em><em>PriorityQueue is ideal for </em><strong><em>task prioritization</em></strong><em>, </em><strong><em>job scheduling</em></strong><em>, or </em><strong><em>shortest path algorithms</em></strong><em>. It gives you quick access to the smallest (or highest priority) element.”</em></blockquote><h3>🔹 b. ArrayDeque</h3><h4>➤ Overview:</h4><ul><li>Double-ended queue</li><li>Faster than Stack &amp; LinkedList</li><li>Interface introduced in Java 1.6 (java.util.Deque)</li></ul><h4>➤ Null Handling:</h4><p>❌ Not allowed</p><h4>➤ Example:</h4><pre>Deque&lt;String&gt; dq = new ArrayDeque&lt;&gt;();<br>dq.addFirst(&quot;First&quot;);<br>dq.addLast(&quot;Last&quot;);<br>System.out.println(dq.removeLast()); // Last</pre><h4>✅ When to Use:</h4><ul><li>Use instead of Stack/Queue</li><li>Best for performance</li></ul><h3>🔍 Characteristics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*fzG42FxAqUu8vDuxksnfJQ.png" /></figure><h3>✅ Ways to Create Deque or ArrayDeque</h3><h3>✅ 1. Create Deque using ArrayDeque</h3><pre>Deque&lt;String&gt; deque = new ArrayDeque&lt;&gt;();<br>deque.add(&quot;A&quot;);<br>deque.addFirst(&quot;B&quot;);<br>deque.addLast(&quot;C&quot;);<br>System.out.println(deque); // Output: [B, A, C]</pre><h3>✅ 2. Create ArrayDeque directly</h3><pre>ArrayDeque&lt;Integer&gt; adq = new ArrayDeque&lt;&gt;();<br>adq.offerFirst(10);<br>adq.offerLast(20);<br>System.out.println(adq); // Output: [10, 20]</pre><h3>✅ 3. With Initial Capacity</h3><pre>Deque&lt;String&gt; deque = new ArrayDeque&lt;&gt;(50);</pre><h3>🧠 Real-World Analogy</h3><ul><li>Think of a <strong>browser history stack</strong>:</li><li>You can go forward or backward (add/remove from both ends).</li><li>Or a <strong>double-ended checkout queue</strong>:</li><li>Customers can enter/exit from both front and rear.</li></ul><h3>⚙️ Common Methods of Deque</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*TYqD0I31f3iNiYKVKz9SKA.png" /></figure><h3>✅ Valid &amp; ❌ Invalid Use Cases</h3><h3>✅ Valid — Working as Stack</h3><pre>Deque&lt;Integer&gt; stack = new ArrayDeque&lt;&gt;();<br>stack.push(1);  // add to front<br>stack.push(2);<br>System.out.println(stack.pop()); // 2 (LIFO)</pre><h3>✅ Valid — Working as Queue</h3><pre>Deque&lt;String&gt; queue = new ArrayDeque&lt;&gt;();<br>queue.offerLast(&quot;Apple&quot;);   // Enqueue at rear<br>queue.offerLast(&quot;Banana&quot;);<br>System.out.println(queue.pollFirst()); // Apple (FIFO)</pre><h3>❌ Invalid — Inserting Null</h3><pre>Deque&lt;String&gt; deque = new ArrayDeque&lt;&gt;();<br>deque.add(null); // ❌ Throws NullPointerException</pre><h3>⚙️ Internal Working of ArrayDeque</h3><ul><li>Internally uses a <strong>circular array</strong> to allow fast insertions/removals at both ends.</li><li>Automatically <strong>doubles in size</strong> when capacity is exceeded.</li></ul><h3>📉 Time Complexity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*lYPhKJsIDd_stFQwga-pcQ.png" /></figure><h3>✅ Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*oSjidPMsuTNoclx2R_NVPQ.png" /></figure><h3>🔐 Thread Safety</h3><ul><li>ArrayDeque is <strong>not thread-safe</strong>.</li><li>Use ConcurrentLinkedDeque for thread-safe double-ended queue.</li></ul><h3>📦 Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*3-j7S5008tIkqcNVNCmOvg.png" /></figure><h3>⚖️ ArrayDeque vs LinkedList</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*eppMgAGT69BesR5ZOfLsZA.png" /></figure><h3>💡 Interview Insights</h3><ul><li>ArrayDeque is a <strong>preferred replacement for both Stack and Queue</strong>.</li><li>Use Deque for <strong>palindrome check</strong>, <strong>sliding windows</strong>, or <strong>history tracking</strong>.</li><li><strong>Avoid using nulls</strong> with ArrayDeque—always leads to exceptions.</li></ul><h3>🧪 Example: Palindrome Check Using Deque</h3><pre>public static boolean isPalindrome(String str) {<br>    Deque&lt;Character&gt; deque = new ArrayDeque&lt;&gt;();<br>    for (char ch : str.toCharArray())<br>        deque.addLast(ch);<br>    while (deque.size() &gt; 1) {<br>        if (deque.removeFirst() != deque.removeLast())<br>            return false;<br>    }<br>    return true;<br>}<br>System.out.println(isPalindrome(&quot;radar&quot;)); // true<br>System.out.println(isPalindrome(&quot;java&quot;));  // false</pre><h3>🗺️ Java Map Interface</h3><p>The Map interface in Java represents a <strong>collection of key-value pairs</strong>, where each <strong>key is unique</strong> and <strong>maps to a single value</strong>.</p><p>➤ <strong>Overview:</strong></p><ul><li>Key-value pair based collection.</li><li>Every key is <strong>unique</strong>, but values can be duplicated.</li><li>Not a subtype of Collection interface.</li><li>Introduced in <strong>Java 1.2</strong> (java.util.Map).</li><li>Common implementations: HashMap, LinkedHashMap, TreeMap, Hashtable, ConcurrentHashMap.</li></ul><p>➤ <strong>Null Handling:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*mY2VEonfatRINjRA3DXBLg.png" /></figure><p>➤ <strong>Key Methods:</strong></p><ul><li>put(K key, V value) – adds a key-value pair</li><li>get(Object key) – retrieves value by key</li><li>remove(Object key) – removes entry by key</li><li>containsKey(Object key) – checks key presence</li><li>containsValue(Object value) – checks value presence</li><li>keySet() – returns set of all keys</li><li>values() – returns collection of values</li><li>entrySet() – returns set of key-value mappings</li></ul><p>➤ ✅ <strong>When to Use:</strong></p><ul><li>When you need to associate <strong>unique keys to values</strong>.</li><li>When <strong>lookup, insertion, and deletion</strong> by key is required.</li><li>When maintaining <strong>insertion order (</strong><strong>LinkedHashMap)</strong> or <strong>natural ordering (</strong><strong>TreeMap)</strong> is important.</li></ul><h3>🧰 Ways to Create a Map</h3><h3>✅ 1. Using HashMap (No order guaranteed)</h3><pre>Map&lt;String, String&gt; map = new HashMap&lt;&gt;();<br>map.put(&quot;name&quot;, &quot;Shivam&quot;);<br>map.put(&quot;city&quot;, &quot;Delhi&quot;);<br>map.put(&quot;name&quot;, &quot;Patel&quot;); // Overwrites previous value</pre><h3>✅ 2. Using LinkedHashMap (Preserves insertion order)</h3><pre>Map&lt;String, Integer&gt; map = new LinkedHashMap&lt;&gt;();<br>map.put(&quot;Math&quot;, 90);<br>map.put(&quot;Science&quot;, 85);</pre><h3>✅ 3. Using TreeMap (Sorted by keys)</h3><pre>Map&lt;Integer, String&gt; map = new TreeMap&lt;&gt;();<br>map.put(3, &quot;Three&quot;);<br>map.put(1, &quot;One&quot;);<br>map.put(2, &quot;Two&quot;); // Sorted by key</pre><h3>✅ 4. Using Hashtable (Thread-safe, legacy class)</h3><pre>Map&lt;String, String&gt; map = new Hashtable&lt;&gt;();<br>map.put(&quot;user&quot;, &quot;admin&quot;);<br>map.put(&quot;pass&quot;, &quot;1234&quot;);</pre><h3>✅ 5. Using Map.of(...) – Immutable Map (Java 9+)</h3><pre>Map&lt;String, String&gt; map = Map.of(&quot;a&quot;, &quot;apple&quot;, &quot;b&quot;, &quot;banana&quot;);<br>// map.put(&quot;c&quot;, &quot;cherry&quot;); ❌ Throws UnsupportedOperationException</pre><h3>🧠 Internal Working of HashMap (Java 8 and Later)</h3><h3>Step 1: Hashing the Key</h3><p>The key is passed to the <strong>hash function</strong> to generate a unique <strong>hash code</strong>. Example:</p><pre>int hash = key.hashCode();</pre><h3>Step 2: Calculating Bucket Index</h3><pre>int index = (n - 1) &amp; hash;</pre><p>Where n is the capacity of the internal array (bucket array).</p><h3>Step 3: Inserting Key-Value Pair</h3><ul><li>Stored in a <strong>bucket</strong>.</li><li>If collision occurs (i.e., same index), keys are stored in a <strong>LinkedList</strong> (or <strong>TreeNode</strong> after a threshold of 8).</li></ul><h3>🔄 Common Operations</h3><pre>map.put(&quot;key&quot;, &quot;value&quot;);<br>map.get(&quot;key&quot;);<br>map.remove(&quot;key&quot;);<br>map.containsKey(&quot;key&quot;);<br>map.containsValue(&quot;value&quot;);<br>map.keySet();<br>map.values();<br>map.entrySet();</pre><h3>⚠️ Behavior with Nulls</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*lTyWgGZLVzvEtfZrIL8E7A.png" /></figure><h3>❌ Invalid Use Cases</h3><pre>Map&lt;String, String&gt; map = new TreeMap&lt;&gt;();<br>map.put(null, &quot;value&quot;);   // ❌ NullPointerException<br>Map&lt;String, String&gt; map = new Hashtable&lt;&gt;();<br>map.put(null, &quot;value&quot;);   // ❌ NullPointerException</pre><h3>✅ Real-World Example: Student Marks System</h3><pre>Map&lt;String, Integer&gt; marks = new HashMap&lt;&gt;();<br>marks.put(&quot;Shivam&quot;, 95);<br>marks.put(&quot;Ram&quot;, 92);<br>System.out.println(marks.get(&quot;Shivam&quot;));  // Output: 95</pre><h3>🔍 Map Implementations</h3><h3>✅ HashMap</h3><ul><li>Unordered</li><li>Allows one null key</li><li>Not thread-safe</li><li>Backed by array + LinkedList/Tree</li></ul><h3>✅ LinkedHashMap</h3><ul><li>Maintains insertion order</li><li>Slightly slower than HashMap</li><li>Useful for caches (e.g., LRU)</li></ul><h3>✅ TreeMap</h3><ul><li>Sorted based on natural order or custom comparator</li><li>Red-Black Tree implementation</li><li>❌ Null keys not allowed</li><li>Time Complexity: O(log n)</li></ul><h3>✅ Hashtable</h3><ul><li>Legacy class</li><li>Thread-safe (synchronized)</li><li>❌ No null key or value</li><li>Slower than HashMap</li></ul><h3>✅ IdentityHashMap</h3><ul><li>Uses reference equality (==) for keys instead of .equals()</li><li>Allows null keys and values</li><li>Used in frameworks for optimization</li></ul><h3>✅ WeakHashMap</h3><ul><li>Keys are held weakly</li><li>Automatically removed if no strong reference</li><li>Useful in caching (memory-sensitive)</li></ul><h3>✅ EnumMap</h3><ul><li>Keys must be enum</li><li>Extremely efficient (array-backed)</li><li>No null keys allowed</li><li>Natural enum order maintained</li></ul><h3>🔐 Concurrent and Sorted Maps</h3><h3>✅ ConcurrentHashMap</h3><ul><li>Thread-safe alternative to HashMap</li><li>Java 7: Segment locking (16 segments)</li><li>Java 8+: CAS (Compare-And-Swap), no segment</li><li>❌ Null keys/values not allowed</li></ul><h3>✅ ConcurrentSkipListMap</h3><ul><li>Thread-safe version of TreeMap</li><li>Internally uses Skip List</li><li>Sorted Map + concurrency</li></ul><h3>✅ SortedMap</h3><ul><li>Interface extending Map</li><li>Entries sorted by natural ordering or custom comparator</li></ul><h3>✅ NavigableMap</h3><ul><li>Extends SortedMap</li><li>Provides methods like:</li><li>lowerKey(), higherKey(), floorKey(), ceilingKey()</li><li>descendingMap()</li></ul><h3>🧊 Immutable Map (Java 9+)</h3><pre>Map&lt;String, Integer&gt; immutableMap = Map.of(<br>    &quot;A&quot;, 1,<br>    &quot;B&quot;, 2,<br>    &quot;C&quot;, 3<br>);<br>// immutableMap.put(&quot;D&quot;, 4); // Throws UnsupportedOperationException</pre><h3>✅ Advantages and ❌ Disadvantages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*PE8C7joSn975y9im6HKiVQ.png" /></figure><h3>📊 Summary Table of Map Implementations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*730eZ_DEqYJo5sVBzaymhw.png" /></figure><h3>🧪 Interview Tip</h3><blockquote><strong><em>Q:</em></strong><em> When should you use </em><em>LinkedHashMap over </em><em>HashMap?</em></blockquote><blockquote><strong><em>A:</em></strong><em> When insertion order matters. </em><em>LinkedHashMap maintains the order in which entries are added, while </em><em>HashMap does not.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2b31947f2f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering Object-Oriented Programming (OOP) in Java — Concepts, Special cases, Real-World…]]></title>
            <link>https://medium.com/@shivapatel1102001/mastering-object-oriented-programming-oop-in-java-concepts-special-cases-real-world-b8bf9b7f660c?source=rss-cfe90cde530b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8bf9b7f660c</guid>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[Shivampatel]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 09:30:59 GMT</pubDate>
            <atom:updated>2025-07-28T05:01:22.393Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧠 Mastering Object-Oriented Programming (OOP) in Java — Concepts, Special cases, Real-World Examples, Code, Keywords and Other concepts</h3><p>This medium covers below topics :</p><blockquote><em>1. </em>Introduction: What is OOP?</blockquote><blockquote><em>2. </em>Object in Java</blockquote><blockquote><em>3. </em><strong>🧱</strong> Constructors in Java</blockquote><blockquote>4. 🧬 Inheritance in Java</blockquote><blockquote><em>5. </em><strong>🌀 </strong>Polymorphism in Java</blockquote><blockquote><em>6. </em>🚀 What is Method Overloading?</blockquote><blockquote><em>7. </em>🔍 Special Cases of Method Overloading</blockquote><blockquote><em>8. </em>🚀 What is Method Overriding?</blockquote><blockquote><em>9. </em>🔍 Special Cases of Method Overriding</blockquote><blockquote><em>10. </em>🧠<strong>Abstraction in Java</strong></blockquote><blockquote>11. 🔶 Abstract Classes in Java</blockquote><blockquote><em>12. </em>🔷 Interfaces in Java</blockquote><blockquote><em>13. </em>🧠 Encapsulation in Java</blockquote><blockquote>14. Detailed Explanation of Java Keywords and Concepts</blockquote><blockquote>15. 🔄 this Keyword in Java</blockquote><blockquote>16. 🔄 Uses of this keyword:</blockquote><blockquote>17. 🧬 super Keyword in Java</blockquote><blockquote>18. 🔼 Uses of super keyword:<br><br>19. Question related to super and this keyword</blockquote><blockquote>20. 🔐 final Keyword<br><br>21. Uses of final Keyword:</blockquote><blockquote>22. ⚙️ static Keyword</blockquote><blockquote>23. 💡 Rules for static methods:</blockquote><blockquote>24. 🌐 Native Methods</blockquote><blockquote>25. ❓ Interview Questions &amp; Answers</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*ScDvkHexAY7pyA2nYXiWsQ.png" /></figure><h3>🔷 Introduction: What is OOP?</h3><p>OOP stands for <strong>Object-Oriented Programming System</strong>. It is a programming paradigm that uses “<strong>objects</strong>” to model real-world entities and solve problems more efficiently.</p><p>OOP is based on the idea of <strong>encapsulating data and behavior</strong> together inside objects.</p><h3>🧱 Java Programming Paradigms</h3><p>A <strong>programming paradigm</strong> is an approach or style to solve problems using programming languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*-OSmlNnmYvgf7GDvGckD0g.png" /></figure><h3>🔑 OOP Pillars</h3><p>There are <strong>4 main pillars of OOP</strong>:</p><ol><li><strong>Encapsulation</strong></li><li><strong>Abstraction</strong></li><li><strong>Inheritance</strong></li><li><strong>Polymorphism</strong></li></ol><h3>🏗️ 1. Class in Java</h3><p>A <strong>class</strong> is a blueprint or template from which objects are created. <strong>It does not occupy memory. [it is collection of object]</strong></p><ul><li>It is not a real-world entity.</li></ul><p>It can contain:</p><ul><li><strong>Fields (variables)</strong></li><li><strong>Methods</strong></li><li><strong>Constructors</strong></li><li><strong>Blocks</strong></li><li><strong>Nested Classes</strong></li></ul><h3>🧍 2. Object in Java</h3><h3>📌 2.1 What are Objects?</h3><p>An <strong>object</strong> is an instance of a class. It is a real-world entity (e.g., car, dog, person).</p><p>Every object has:</p><ul><li><strong>Identity (Name)</strong></li><li><strong>State (Attributes like color, age)</strong></li><li><strong>Behavior (Methods like drive(), eat())</strong></li></ul><p>✅ Syntax:</p><pre>Car myCar = new Car();  // &#39;myCar&#39; is an object of class Car</pre><p>📌 2.2 Ways to Create an Object in Java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*pGgGYIE-latknTLiZr96Uw.png" /></figure><p>📌 2.3 Real-World Program using Class, Method, and Object</p><pre>class Student {<br>    int id;<br>    String name;<br><br>    void display() {<br>        System.out.println(&quot;ID: &quot; + id + &quot;, Name: &quot; + name);<br>    }<br>}<br><br>public class Test {<br>    public static void main(String[] args) {<br>        Student s1 = new Student(); // object creation<br>        s1.id = 101;<br>        s1.name = &quot;Alice&quot;;<br>        s1.display();<br>    }<br>}</pre><p>📌 2.4 How to Initialize an Object</p><h4>✅ 3 Ways to Initialize:</h4><ol><li>By Reference Variable</li></ol><pre>s1.id = 101;<br>s1.name = &quot;Alice&quot;;</pre><p>2. By Method</p><pre>void setData(int i, String n) {<br>    id = i;<br>    name = n;<br>}</pre><p>3. By Constructor</p><pre>Student(int i, String n) {<br>    id = i;<br>    name = n;<br>}</pre><h3><strong>🧱 Constructors in Java</strong></h3><p>A <strong>constructor</strong> is used to <strong>initialize</strong> an object (it is not used create the object). It has the <strong>same name as the class</strong> and has <strong>no return type</strong>.</p><pre>class Student {<br>    int id;<br>    String name;<br><br>    Student(int i, String n) {<br>        id = i;<br>        name = n;<br>    }<br>}</pre><h3>🔥 Important Notes:</h3><ul><li><strong>Constructors do not return values.</strong></li><li><strong>Only modifiers allowed</strong>: public, private, protected, or default (package-private).</li><li><strong>Automatically called</strong> when the object is created.</li></ul><h3>❌ Problem When No Constructor is Used</h3><p>If no constructor is provided, Java provides a <strong>default constructor</strong>. But if any constructor is written, Java <strong>does not create a default constructor</strong>.</p><pre>class Student {<br>    int id;<br>    String name;<br>}</pre><p>In this case, all values will be default: id = 0, name = null.</p><p>🧩 Types of Constructors in Java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*Pv5z9Epok7hEO4g2P8XHYQ.png" /></figure><pre>// No-Arg Constructor<br>Student() {<br>    id = 0;<br>    name = &quot;Default&quot;;<br>}<br><br>// Parameterized Constructor<br>Student(int id, String name) {<br>    this.id = id;<br>    this.name = name;<br>}<br><br>// Copy Constructor<br>Student(Student s) {<br>    this.id = s.id;<br>    this.name = s.name;<br>}</pre><h3><strong>🧬 Inheritance in Java</strong></h3><p><strong>Inheritance</strong> allows one class to acquire properties and behavior of another class.</p><p>✅ 1. IS-A Relationship</p><pre>class Animal {<br>    void eat() { System.out.println(&quot;Eating...&quot;); }<br>}<br><br>class Dog extends Animal {<br>    void bark() { System.out.println(&quot;Barking...&quot;); }<br>}</pre><p>Output:</p><pre>Eating...<br>Barking...</pre><h3>📌 Real World Example:</h3><ul><li>Dog is an Animal</li><li>Car is a Vehicle</li></ul><h3>✅ Benefits:</h3><ul><li><strong>Code Reusability</strong></li><li>Enables <strong>Polymorphism</strong> and <strong>Method Overriding</strong></li></ul><h3>❌ Limitations:</h3><ul><li>Tight coupling</li><li>Java does <strong>not support multiple inheritance</strong> with classes (only via interfaces)</li></ul><p>📊 Types of Inheritance in Java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*MrkF8dFf9eFWBs4PejQADg.png" /></figure><h3>✅ 2. Association (HAS-A)</h3><p>When one class uses another.</p><h4>🔹 Aggregation:</h4><ul><li>Weak association</li><li>“Has-a” relationship</li><li>Child can exist independently</li></ul><pre>class Department {<br>    Teacher teacher;<br>}</pre><h3>🔹 Composition:</h3><ul><li>Strong association</li><li>Child cannot exist without parent</li></ul><pre>class Heart {<br>    private Blood blood; // strong dependency<br>}</pre><h3><strong>🌀 Polymorphism in Java</strong></h3><p><strong>Polymorphism</strong> means “many forms”.</p><ol><li>Compile-time polymorphism [static polymorphism]</li><li>Runtime polymorphism [dynamic polymorphism]</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*zWfE-A7K-t5yH3MRlgTi2g.png" /></figure><p>📊 Overloading vs Overriding (Table)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*cMAUdafTBcoBWdm_O4zSlA.png" /></figure><h3><strong>🚀 What is Method Overloading?</strong></h3><p><strong>Method Overloading</strong> in Java means defining <strong>multiple methods with the same name</strong> but <strong>different parameters</strong> (number, type, or sequence) in the <strong>same class</strong>.</p><h3>✅ Why Overload a Method?</h3><ul><li>Increases <strong>readability</strong></li><li>Helps in <strong>code reusability</strong></li><li>Makes the API intuitive</li></ul><h3>⚠️ Rules of Method Overloading</h3><ul><li>Method name must be the <strong>same</strong></li><li>Parameter list must be <strong>different</strong></li><li>Return type <strong>alone</strong> cannot be used to differentiate methods</li><li>Overloading can happen with:</li><li><strong>Different number</strong> of arguments</li><li><strong>Different data types</strong></li><li><strong>Different order of parameters</strong></li></ul><h3>🔍 Special Cases of Method Overloading</h3><p>Let’s understand <strong>real scenarios</strong> with code and detailed explanations.</p><p>📌 Case 1: Automatic Type Promotion</p><p>If there’s no exact match found, <strong>Java automatically promotes data types</strong> according to this hierarchy:</p><pre>byte → short → int → long → float → double<br>char → int</pre><h4>Example:</h4><pre>class Test {<br>    void show(int a) {<br>        System.out.println(&quot;int method&quot;);<br>    }<br>    void show(String a) {<br>        System.out.println(&quot;string method&quot;);<br>    }<br><br>    public static void main(String[] args) {<br>        Test t = new Test();<br>        t.show(&#39;a&#39;); // char is promoted to int<br>    }<br>}</pre><p>🔍 Output:</p><pre>int method</pre><p>📌 Case 2: Parent vs Child Argument Resolution</p><pre>class Test {<br>    void show(Object a) {<br>        System.out.println(&quot;object method&quot;);<br>    }<br>    void show(String a) {<br>        System.out.println(&quot;string method&quot;);<br>    }<br><br>    public static void main(String[] args) {<br>        Test t = new Test();<br>        t.show(&quot;abc&quot;);<br>        t.show(&#39;a&#39;);<br>    }<br>}</pre><p>🔍 Output:</p><pre>string method<br>object method</pre><h4>💡 Why?</h4><p>When both child and parent types match, <strong>child gets higher priority</strong> (String is a subclass of Object).</p><p>📌 Case 3: Same Level Classes (String vs StringBuffer)</p><pre>class Test {<br>    void show(StringBuffer a) {<br>        System.out.println(&quot;stringbuffer method&quot;);<br>    }<br>    void show(String a) {<br>        System.out.println(&quot;string method&quot;);<br>    }<br><br>    public static void main(String[] args) {<br>        Test t = new Test();<br>        t.show(&quot;abc&quot;);                          // string method<br>        t.show(new StringBuffer(&quot;xyz&quot;));        // stringbuffer method<br>    }<br>}</pre><p>🔍 Output:</p><pre>string method  <br>stringbuffer method</pre><p>⚠️ Case 3b: Calling with null — Ambiguity Error [<strong>Compilation Error</strong>]</p><pre>t.show(null);  // ❌ Compilation Error</pre><h4>❗ Why?</h4><p>Both String and StringBuffer are <strong>at the same level</strong>, so compiler can&#39;t decide which method to call — <strong>ambiguous method call</strong>.</p><p>📌 Case 4: Changing Argument Order</p><pre>class Test {<br>    void show(int a, float b) {<br>        System.out.println(&quot;int float method&quot;);<br>    }<br><br>    void show(float a, int b) {<br>        System.out.println(&quot;float int method&quot;);<br>    }<br><br>    public static void main(String[] args) {<br>        Test t = new Test();<br>        t.show(10, 20.5f);  // int float<br>        t.show(20.5f, 10);  // float int<br>        t.show(10, 20);     // ❌ Error – ambiguous - Compilation Error<br>    }<br>}</pre><h4>❌ Why the error?</h4><p>In t.show(10, 20) both arguments are int, and compiler can promote either way (to float or keep it int), so it&#39;s <strong>ambiguous</strong>.</p><p>📌 Case 5: Varargs (Variable Arguments)</p><pre>class Test {<br>    void show(int a) {<br>        System.out.println(&quot;int method&quot;);<br>    }<br><br>    void show(int... a) {<br>        System.out.println(&quot;varargs method&quot;);<br>    }<br><br>    public static void main(String[] args) {<br>        Test t = new Test();<br>        t.show();           // varargs method<br>        t.show(10);         // int method (exact match)<br>    }<br>}</pre><h4>💡 Note:</h4><ul><li>If no exact match, <strong>varargs</strong> will be used.</li><li>Varargs always gets the <strong>least priority</strong>.</li></ul><p>❓ FAQs on Method Overloading</p><h3>🔄 Q1. Can we overload methods by only changing return type?</h3><p><strong>❌ No</strong>, it leads to compile-time error.</p><pre>int show(int a) { ... }<br>float show(int a) { ... }  // Not allowed</pre><p>🧠 Q2. Can we overload the main() method?</p><p><strong>✅ Yes</strong>, but JVM always calls:</p><pre>public static void main(String[] args)</pre><p>You can overload it for other purposes:</p><pre>public static void main(String args) { ... }<br>public static void main(int a) { ... }</pre><p>🔁 Q3. What is Method Overloading with Type Promotion?</p><p>When the exact match isn’t found, <strong>Java promotes smaller data types</strong> to fit the closest larger type.</p><pre>void show(long a) { ... }<br><br><br>show(10); // int → long</pre><p>🧾 Summary of Special Method Overloading Cases</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*6w2fioRdaVxRLLFQEc0wqQ.png" /></figure><h3>🧠 Best Practices</h3><ul><li>Avoid ambiguous overloads</li><li>Don’t overload with only return type changes</li><li>Use descriptive method names if overloading creates confusion</li><li>Prefer <strong>method overriding</strong> for polymorphic behavior over overloading</li></ul><p>🔁 Method Overriding in Java — Explained in Detail with Real-World Examples</p><h3>✅ What is Method Overriding?</h3><p>Method overriding in Java is when a subclass provides a specific implementation of a method that is already defined in its superclass. This is a key pillar of <strong>Polymorphism</strong> in Object-Oriented Programming (OOP), allowing <strong>runtime method dispatch</strong>.</p><p>📌 Syntax:</p><pre>class Parent {<br>    void display() {<br>        System.out.println(&quot;Display from Parent&quot;);<br>    }<br>}<br><br>class Child extends Parent {<br>    @Override<br>    void display() {<br>        System.out.println(&quot;Display from Child&quot;);<br>    }<br>}</pre><p>🧠 Real-world Analogy:</p><p>Imagine a generic Printer class with a method print(). A ColorPrinter class overrides print() to provide color printing instead of black and white. Both classes have the same method name, but the behavior is specialized in the subclass.</p><h3>🔍 Special Cases of Method Overriding</h3><h3>📘 Case 1: Can Overriding Method Have a Different Return Type?</h3><p>Yes, but it must follow <strong>Covariant Return Type</strong> rules.</p><blockquote><em>🔸 The return type in the subclass can be a subclass of the return type in the superclass.</em></blockquote><p>✅ Example — Covariant Return Type:</p><pre>class Animal {<br>    Animal getAnimal() {<br>        return new Animal();<br>    }<br>}<br><br>class Dog extends Animal {}<br><br>class DogFactory extends Animal {<br>    @Override<br>    Dog getAnimal() {<br>        return new Dog();  // Covariant return type<br>    }<br>}</pre><p>❌ Invalid Case:</p><pre>class A {<br>    void show() {}<br>}<br><br>class B extends A {<br>    int show() {}  // Error: incompatible return type<br>}</pre><h3>📘 Case 2: Overriding and Access Modifiers</h3><blockquote><em>🔸 Access level in the child class must be </em><strong><em>same or more accessible</em></strong><em> than in the parent class.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*KZahw7V0137xjmLbwe4jRw.png" /></figure><pre>class A {<br>    protected void greet() {}<br>}<br><br>class B extends A {<br>    @Override<br>    public void greet() {}  // Valid: more accessible<br>}</pre><p>❌ Invalid:</p><pre>class A {<br>    public void greet() {}<br>}<br><br>class B extends A {<br>    @Override<br>    protected void greet() {}  // Error: reduced visibility<br>}</pre><h3>📘 Case 3: Overriding and Exception Handling</h3><p>Java follows strict rules when it comes to overriding methods and exceptions:</p><h3>🔹 Rule 1: If Parent Method Does Not Throw Any Exception</h3><blockquote><em>Then the child class </em><strong><em>cannot</em></strong><em> throw </em><strong><em>checked exceptions</em></strong><em>, but </em><strong><em>can</em></strong><em> throw unchecked exceptions.</em></blockquote><h3>✅ Example (Unchecked Allowed):</h3><pre>class A {<br>    void show() {}<br>}<br><br>class B extends A {<br>    @Override<br>    void show() {<br>        throw new ArithmeticException();  // Allowed<br>    }<br>}</pre><p>❌ Example (Checked Exception Not Allowed):</p><pre>class A {<br>    void show() {}<br>}<br><br>class B extends A {<br>    @Override<br>    void show() throws IOException {}  // Error: checked exception not allowed<br>}</pre><h3>🔹 Rule 2: If Parent Method Throws an Exception</h3><blockquote><em>Child method:</em></blockquote><ul><li>Can throw the <strong>same exception</strong></li><li>Or its <strong>subclass</strong></li><li>Or throw <strong>no exception</strong></li></ul><p>But <strong>cannot throw a superclass of the parent’s exception</strong></p><p>✅ Valid Example:</p><pre>class A {<br>    void show() throws IOException {}<br>}<br><br>class B extends A {<br>    @Override<br>    void show() throws FileNotFoundException {}  // Valid: subclass exception<br>}</pre><p>❌ Invalid Example:</p><pre>class A {<br>    void show() throws FileNotFoundException {}<br>}<br><br>class B extends A {<br>    @Override<br>    void show() throws IOException {}  // Error: IOException is a superclass<br>}</pre><p>📊 Summary Table: Possible and Not Possible Cases</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*BcajrJVGTEmt5izbK9osJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBzMwim_u4s4ypmerYMFkg.png" /></figure><h3>📘 Case 4: Overriding and Abstraction</h3><blockquote><em>If a class inherits an </em><strong><em>abstract method</em></strong><em>, it must provide an implementation or be declared abstract itself.</em></blockquote><h3>🔹 Example:</h3><pre>abstract class Animal {<br>    abstract void sound();<br>}<br><br>class Dog extends Animal {<br>    @Override<br>    void sound() {<br>        System.out.println(&quot;Bark&quot;);<br>    }<br>}</pre><h3>📘 Case 5: Invoking Overridden Method from Subclass</h3><p>You can call the overridden method using super.methodName() inside the child class.</p><p>🔹 Example:</p><pre>class Parent {<br>    void greet() {<br>        System.out.println(&quot;Hello from Parent&quot;);<br>    }<br>}<br><br>class Child extends Parent {<br>    @Override<br>    void greet() {<br>        super.greet(); // Call parent method<br>        System.out.println(&quot;Hello from Child&quot;);<br>    }<br>}</pre><h3>📘 Case 6: Can All Methods Be Overridden?</h3><p>No. Some methods <strong>cannot be overridden</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*bv4FIO7maYJeW5MYfKtrtg.png" /></figure><p>🔹 Example: Private Method</p><pre>class A {<br>    private void show() {<br>        System.out.println(&quot;Parent&quot;);<br>    }<br>}<br><br>class B extends A {<br>    void show() {<br>        System.out.println(&quot;Child&quot;);<br>    }<br>}<br>// This is not overriding; it&#39;s a new method</pre><p>here if you want to check, you can check by adding @Override annotation on show() method — this annotation will give compile time error</p><ul><li><strong>if we don’t want the method to be ovveridden, we declare the method as final.</strong></li><li><strong>Method Hidiing :- When we define a static method with the same signature as static method in base class it is called method hiding.</strong></li></ul><h3>📘 Case 7: Overriding with synchronized or strictfp</h3><p>Yes, you can use synchronized or strictfp in overridden methods. They are not part of the method signature and don’t affect overriding rules.</p><p>Presence od the synchronized or strictfp modifiers with the method have no effect on the rules of the overriding i.e. it is possible that a synchronized or strictfp can override a non synchronized or strictfp or vice-versa.</p><p>🔹 Example:</p><pre>class A {<br>    synchronized void compute() {}<br>}<br><br>class B extends A {<br>    @Override<br>    strictfp void compute() {}  // Valid<br>}</pre><pre>class A {<br>    void compute() {}<br>}<br><br>class B extends A {<br>    @Override<br>    synchronized void compute() {}  // Valid<br>}</pre><p>✅ Summary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*W_ALJDtyAc4dEN2EV_cm-Q.png" /></figure><p>🧪 Real-world Scenario: Overriding in Banking App</p><pre>class Account {<br>    double getInterestRate() {<br>        return 5.0;<br>    }<br>}<br><br>class SavingsAccount extends Account {<br>    @Override<br>    double getInterestRate() {<br>        return 2.0;<br>    }<br>}<br><br>class FixedDepositAccount extends Account {<br>    @Override<br>    double getInterestRate() {<br>        return 8.5;<br>    }<br>}</pre><p>🔹 Here, all account types use the same method getInterestRate(), but each returns different behavior based on business logic. This is classic <strong>runtime polymorphism</strong>.</p><h3>🧠<strong> Abstraction in Java — A Deep Dive with Real-World Examples</strong></h3><p>Abstraction is one of the four pillars of Object-Oriented Programming (OOP), alongside <strong>Encapsulation</strong>, <strong>Inheritance</strong>, and <strong>Polymorphism</strong>. It allows developers to focus on <strong>what an object does</strong> rather than <strong>how it does it</strong>.</p><h3><strong>🔍</strong> What is Abstraction?</h3><blockquote><strong><em>Abstraction</em></strong><em> is the process of hiding internal implementation details and showing only the essential features of an object.</em></blockquote><p>Think of abstraction as <strong>using a TV remote</strong>: You can change channels, adjust volume, or power on/off — without knowing the complex circuits inside.</p><h3>✅ Why Use Abstraction?</h3><ul><li>Reduce complexity</li><li>Focus on interaction and contract</li><li>Improve code maintainability and scalability</li><li>Enforce security by hiding sensitive details</li></ul><h3>🛠️ How to Achieve Abstraction in Java?</h3><p>Java supports abstraction using two constructs:</p><ol><li><strong>Abstract Classes</strong></li><li><strong>Interfaces</strong></li></ol><h3>🔶 Abstract Classes in Java</h3><h3>💡 What is an Abstract Class?</h3><p>An abstract class is a class that <strong>cannot be instantiated</strong> and may contain <strong>abstract methods</strong> (methods without body) as well as <strong>concrete methods</strong>.</p><pre>abstract class Vehicle {<br>    abstract void start(); // abstract method<br>    void stop() {<br>        System.out.println(&quot;Vehicle stopped.&quot;);<br>    }<br>}</pre><h3>📌 Key Points:</h3><ol><li>A method without a body is called an <strong>abstract method</strong>.</li><li>A class containing at least one abstract method <strong>must</strong> be declared as abstract.</li><li>An abstract class <strong>can</strong> have concrete (non-abstract) methods.<strong> [Class which contains abstract method made as abstract class but it is not mandatory that abstract class have abstract method.]</strong></li><li>We <strong>cannot</strong> instantiate an abstract class, but we <strong>can create a reference</strong>.</li><li>If a class extends an abstract class, it <strong>must implement</strong> all abstract methods, or be declared abstract itself.</li></ol><h3>🔄 Real-World Example:</h3><pre>abstract class PaymentProcessor {<br>    abstract void processPayment(double amount);<br>}<br><br>class CreditCardPayment extends PaymentProcessor {<br>    void processPayment(double amount) {<br>        System.out.println(&quot;Processing credit card payment of ₹&quot; + amount);<br>    }<br>}</pre><h3><strong>🔷 Interfaces in Java</strong></h3><h3>💡 What is an Interface?</h3><p>An interface is a completely abstract class that defines a <strong>contract</strong> for what a class can do, without specifying how.</p><pre>interface Shape {<br>    void draw();<br>}</pre><h3>📌 Key Points:</h3><ol><li>Interfaces contain <strong>only abstract methods</strong> by default (until Java 7).</li><li>From Java 8 onward:</li></ol><ul><li>Can have default methods (concrete).</li><li>Can have static methods.</li></ul><p>3. From Java 9 onward:</p><ul><li>Can have private methods.</li></ul><p><strong>4. Every field</strong> in an interface is public static final (constants).</p><p>5. Interfaces support <strong>multiple inheritance</strong>, unlike classes.</p><p>6. Interfaces help achieve <strong>loose coupling</strong> and <strong>polymorphism</strong>.</p><h3>🔄 Real-World Example:</h3><pre>interface Flyable {<br>    void fly();<br>}<br><br>class Bird implements Flyable {<br>    public void fly() {<br>        System.out.println(&quot;Bird is flying&quot;);<br>    }<br>}</pre><p>🔁 Abstract Class vs Interface — Key Differences</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*UK-vTbbTter9Rmb97EKLDA.png" /></figure><p>🔄 Similarities between Abstract Classes and Interfaces</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*V-KDoB0K1OGwsvbqrCWUYw.png" /></figure><h3>🧑‍💻 Real World Analogy</h3><h3>Abstract Class Analogy:</h3><p>A <strong>generic bank account</strong> might define common behaviors like deposit() and withdraw() but leave calculateInterest() abstract. Concrete subclasses like SavingsAccount or FixedDepositAccount provide specific implementations.</p><h3>Interface Analogy:</h3><p>An <strong>ATM machine</strong> interacts with many banks via a standard protocol. Each bank implements the interface BankAPI, ensuring consistency without enforcing how each bank processes transactions.</p><h3>✅ Final Thoughts</h3><p>Abstraction is all about <strong>hiding the complexities</strong> and exposing only what’s necessary. Java’s dual abstraction model — via abstract classes and interfaces — offers flexibility and power to design <strong>robust, scalable, and clean object-oriented systems</strong>.</p><h3>🧠 <strong>Encapsulation in Java — A Deep Dive with Real-World Analogy</strong></h3><h3>🔐 What is Encapsulation?</h3><p><strong>Encapsulation</strong> is the process of <strong>binding data (variables)</strong> and <strong>methods (functions)</strong> that operate on the data into a <strong>single unit</strong>, typically a <strong>class</strong>.</p><blockquote><em>💡 Think of it as “data hiding” and “data protection” — only the class itself can control how its data is accessed or modified.</em></blockquote><h3>📦 Real-World Analogy: ATM Machine</h3><ul><li>An <strong>ATM machine</strong> hides the internal details of how it processes transactions.</li><li>As a user, you <strong>interact through a secure interface</strong>: insert card, enter PIN, choose transaction.</li><li>You <strong>cannot see or modify</strong> the backend logic (e.g., balance checking, logging).</li></ul><p>Just like this, in <strong>Java</strong>, an encapsulated class:</p><ul><li>Hides internal data (private fields),</li><li>Allows controlled access through public getters/setters.</li></ul><h3>How to Achieve Encapsulation in Java?</h3><h3>✅ Steps:</h3><ol><li><strong>Make all data members (</strong><strong>variables) private.</strong></li><li><strong>Provide public getter and setter methods</strong> to read and modify those values.</li></ol><p>👨‍💻 Example: BankAccount</p><pre>class BankAccount {<br>    private double balance; // 🔒 Hidden data (private)<br><br>    public BankAccount(double balance) {<br>        this.balance = balance;<br>    }<br><br>    // Getter (controlled access)<br>    public double getBalance() {<br>        return balance;<br>    }<br><br>    // Setter (controlled modification)<br>    public void setBalance(double balance) {<br>        if (balance &gt;= 0) {<br>            this.balance = balance;<br>        } else {<br>            System.out.println(&quot;❌ Balance cannot be negative!&quot;);<br>        }<br>    }<br>}</pre><p>🧪 Main Class:</p><pre>public class EncapsulationExample {<br>    public static void main(String[] args) {<br>        BankAccount account = new BankAccount(1000);<br><br>        // ❌ Direct access not allowed: account.balance<br><br>        // ✅ Use getter<br>        System.out.println(&quot;Current Balance: &quot; + account.getBalance());<br><br>        // ✅ Use setter<br>        account.setBalance(2000);<br>        System.out.println(&quot;Updated Balance: &quot; + account.getBalance());<br><br>        // ❌ Invalid attempt<br>        account.setBalance(-500); // Shows error message<br>    }<br>}</pre><p>❓ Why Allow Setters if We’re Trying to “Protect” the Data?</p><blockquote><em>If I’m exposing a </em><em>setBalance() method, what&#39;s the point of marking </em><em>balance as </em><em>private?</em></blockquote><p>Wouldn’t it be the same as making balance public?<br> <strong>NO — and here&#39;s why.</strong></p><h3>✅ Setter Method = Controlled Access</h3><p>The key difference is <strong>control and validation</strong>.</p><p>With a setter, <strong>you choose what is allowed</strong> to be set.<br> With a public field, <strong>any value can be assigned</strong> directly.</p><h3>🔓 ❌ Public Field (Not Encapsulated):</h3><pre>public class BankAccount {<br>    public double balance;<br>}<br><br>BankAccount acc = new BankAccount();<br>acc.balance = -500; // ❌ Invalid state, no protection</pre><p>➡️ Anyone can assign <strong>invalid</strong>, <strong>inconsistent</strong>, or even <strong>malicious</strong> data to your object.</p><h3>🔐 ✅ Private Field with Setter (Encapsulated):</h3><pre>public class BankAccount {<br>    private double balance;<br><br>    public void setBalance(double balance) {<br>        if (balance &gt;= 0) {               // ✅ Validation logic<br>            this.balance = balance;<br>        } else {<br>            System.out.println(&quot;❌ Balance cannot be negative.&quot;);<br>        }<br>    }<br>}</pre><p>➡️ You can <strong>prevent negative balances</strong> or <strong>apply business rules</strong>.</p><h3>🔐 Benefits of Using Setters for Encapsulation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*_6fgXQLyhT89jubWV8vG2A.png" /></figure><h3>🔐 Real World Analogy</h3><p>Imagine your <strong>bank balance</strong>:</p><ul><li><strong>Public variable</strong> = Anyone can walk into the bank and change your balance to ₹0 or ₹1 crore.</li><li><strong>Private variable + Setter</strong> = Only the bank teller (method) can update it after verifying your identity and validating the transaction.</li></ul><blockquote><strong><em>Encapsulation is like putting your valuables in a locker.</em></strong><em><br> Even though people can request access, the </em><strong><em>locker guard (setter)</em></strong><em> checks if it’s valid before opening it.</em></blockquote><p>🛡️ How is Data Actually Hidden?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*xDo34usxSgdx6VAV8Gc07Q.png" /></figure><p>🎯 Why Use Encapsulation?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*51133mD85MC1CTUwq_w0Rw.png" /></figure><p>🔁 Real-World Example: Employee System</p><pre>class Employee {<br>    private int id;<br>    private String name;<br>    private double salary;<br><br>    public int getId() {<br>        return id;<br>    }<br><br>    public void setId(int id) {<br>        if(id &gt; 0) this.id = id;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        if(name != null &amp;&amp; !name.isEmpty()) this.name = name;<br>    }<br><br>    public double getSalary() {<br>        return salary;<br>    }<br><br>    public void setSalary(double salary) {<br>        if(salary &gt;= 0) this.salary = salary;<br>    }<br>}</pre><h3>✅ Example with Advanced Validation</h3><pre>public class Employee {<br>    private int age;<br><br>    public void setAge(int age) {<br>        if (age &gt;= 18 &amp;&amp; age &lt;= 60) {<br>            this.age = age;<br>        } else {<br>            throw new IllegalArgumentException(&quot;Age must be between 18 and 60.&quot;);<br>        }<br>    }<br><br>    public int getAge() {<br>        return age;<br>    }<br>}</pre><p>✅ Bonus: Setter Can Have Side Effects</p><pre>public class Product {<br>    private double price;<br><br>    public void setPrice(double price) {<br>        if (price &gt;= 0) {<br>            this.price = price;<br>            System.out.println(&quot;Price updated successfully.&quot;);<br>        } else {<br>            throw new IllegalArgumentException(&quot;Price must be non-negative.&quot;);<br>        }<br>    }<br>}</pre><p>🔒 Summary: Why Setters = Security + Control</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*INwGNwJx0Uu8udE3reiVZQ.png" /></figure><h3>✅ Benefits:</h3><ul><li>No one can set a negative salary, or age before and after max limit.</li><li>Class remains consistent and predictable.</li><li>Validation rules are enforced from one place.</li></ul><p>🔄 Comparison Table: Encapsulation vs. No Encapsulation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*yWwABbHfthA3pqeDgwYUlQ.png" /></figure><h3>📘 Summary</h3><ul><li><strong>Encapsulation = Data Hiding + Access Control</strong></li><li>Promotes <strong>clean code</strong>, <strong>security</strong>, and <strong>robustness</strong></li><li>Achieved using <strong>private fields</strong> + <strong>public getters/setters</strong></li><li>Used in <strong>every modern Java application</strong> (Banking, HR, eCommerce)</li></ul><blockquote><em>🔐 Encapsulation is the first step toward </em><strong><em>writing secure, maintainable, and scalable</em></strong><em> object-oriented Java applications. It not only protects your data but also keeps your codebase robust and flexible for future changes. Use it wisely — encapsulated code is trusted code.</em></blockquote><h3>Detailed Explanation of Java Keywords and Concepts</h3><h3>🔄 this Keyword in Java</h3><h3>What is this keyword?</h3><p>this is a reference variable in Java that refers to the <strong>current object</strong> of the class. It is mainly used to eliminate confusion between class attributes (instance variables) and parameters or local variables.</p><h3>🔄 Uses of this keyword:</h3><ol><li><strong>Refer to instance variables</strong> → Resolves ambiguity when local and instance variables have the same name.</li><li><strong>Call instance methods</strong> → Implicitly used inside instance methods to call other instance methods.</li><li><strong>Call current class constructor</strong> → this() invokes another constructor in the same class (constructor chaining).</li><li><strong>Pass current object as argument</strong> → To methods or constructors.</li><li><strong>Return current class instance</strong> → From methods.</li><li><strong>Not used in static context</strong> → Static methods do not have a this reference.</li></ol><p>✅ <strong>Rule:</strong> this() must be the first statement in the constructor.</p><p>🛠 <strong>Constructor Chaining Benefits:</strong></p><ul><li>Reduces code duplication.</li><li>Improves code reusability.</li><li>Ensures proper object initialization.</li></ul><p>✅ <strong>1. Refer to instance variables (resolve naming conflict)</strong></p><pre>public class Student {<br>    private String name;<br><br>    public Student(String name) {<br>        this.name = name; // &#39;this.name&#39; refers to the instance variable, &#39;name&#39; refers to constructor parameter<br>    }<br><br>    public void printName() {<br>        System.out.println(&quot;Name is: &quot; + this.name);<br>    }<br>}</pre><p><strong>Why this is useful:</strong> Avoids ambiguity between instance variable and constructor parameter.</p><p>✅ <strong>2. Call instance methods</strong></p><pre>public class Calculator {<br>    public void calculate() {<br>        System.out.println(&quot;Calculating...&quot;);<br>        this.showResult(); // &#39;this&#39; is optional here but clarifies we are calling an instance method<br>    }<br><br>    public void showResult() {<br>        System.out.println(&quot;Result shown!&quot;);<br>    }<br><br>    public static void main(String[] args) {<br>        Calculator c = new Calculator();<br>        c.calculate();<br>    }<br>}</pre><p><strong>Why this is useful:</strong> You can call one instance method from another using this to improve readability.</p><p>✅ 3. <strong>Call current class constructor (Constructor Chaining)</strong></p><pre>public class Person {<br>    private String name;<br>    private int age;<br><br>    public Person() {<br>        this(&quot;Unknown&quot;, 0); // Calls another constructor<br>    }<br><br>    public Person(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br><br>    public void showInfo() {<br>        System.out.println(&quot;Name: &quot; + name + &quot;, Age: &quot; + age);<br>    }<br><br>    public static void main(String[] args) {<br>        Person p = new Person();<br>        p.showInfo();  // Output: Name: Unknown, Age: 0<br>    }<br>}</pre><h3><strong>Rule:</strong> this() must be the first statement in a constructor. [otherwise it will give compiler error]</h3><p><strong>Why this is useful:</strong> Reduces code duplication in multiple constructors.</p><p>✅ 4. <strong>Pass current object as an argument</strong></p><pre>public class Employee {<br>    String name;<br><br>    Employee(String name) {<br>        this.name = name;<br>    }<br><br>    void display() {<br>        System.out.println(&quot;Employee name: &quot; + name);<br>    }<br><br>    void process(Employee e) {<br>        System.out.println(&quot;Processing employee: &quot; + e.name);<br>    }<br><br>    void startProcessing() {<br>        process(this); // Pass current object<br>    }<br><br>    public static void main(String[] args) {<br>        Employee emp = new Employee(&quot;Shivam&quot;);<br>        emp.startProcessing();<br>    }<br>}</pre><p><strong>Why this is useful:</strong> Allows passing the current object to another method or class.</p><p>✅ 5. <strong>Return current class instance</strong></p><pre>public class BuilderExample {<br>    private int x;<br><br>    public BuilderExample setX(int x) {<br>        this.x = x;<br>        return this; // return current object for method chaining<br>    }<br><br>    public void print() {<br>        System.out.println(&quot;x = &quot; + x);<br>    }<br><br>    public static void main(String[] args) {<br>        BuilderExample obj = new BuilderExample();<br>        obj.setX(50).print(); // Method chaining using &#39;this&#39;<br>    }<br>}</pre><p><strong>Why this is useful:</strong> Enables method chaining (used in builder pattern, fluent interfaces).</p><p>❌ 6. <strong>Not used in static context</strong></p><pre>public class Example {<br>    static int count = 0;<br><br>    static void printCount() {<br>        // System.out.println(this.count); ❌ Not allowed<br>        // Error: Cannot use &#39;this&#39; in a static context<br>        System.out.println(&quot;Count: &quot; + count);<br>    }<br>}</pre><p><strong>Why:</strong> Static methods belong to the class, not the object, so there’s no this reference.</p><h3>🧬 super Keyword in Java</h3><h3>What is super keyword?</h3><p>super is a reference variable used to refer to the <strong>parent class</strong> object. It is primarily used in <strong>inheritance</strong>.</p><h3>🔼 Uses of super keyword:</h3><ol><li><strong>Access parent class variables</strong> → Especially when subclass has the same variable name.</li><li><strong>Invoke parent class methods</strong> → When overridden in subclass.</li><li><strong>Invoke parent class constructor</strong> → super() calls the parent constructor from the child.</li></ol><p>📌 <strong>Must be first statement</strong> inside a subclass constructor when used.</p><ol><li><strong>To call parent class constructor</strong></li></ol><pre>class Parent {<br>    Parent() {<br>        System.out.println(&quot;Parent Constructor&quot;);<br>    }<br>}</pre><pre>class Child extends Parent {<br>    Child() {<br>        super(); // Calls Parent constructor<br>        System.out.println(&quot;Child Constructor&quot;);<br>    }<br>}</pre><h3>Rule: super() must be the first statement in a constructor. [otherwise it will give compiler error]</h3><p><strong>2. To access parent class methods/fields</strong></p><pre>class Parent {<br>    void display() {<br>        System.out.println(&quot;Parent Method&quot;);<br>    }<br>}</pre><pre>class Child extends Parent {<br>    void display() {<br>        super.display(); // Calls parent method<br>    }<br>}</pre><blockquote><em>🔐</em> Access Modifiers vs Non-Access Modifiers</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*dazAk8mlGIFLt3XS3AjiLg.png" /></figure><h3>✅ 1. Can we use this and super keyword in constructor simultaneously?</h3><h3>❌ No, you cannot use both this() and super() in the same constructor directly.</h3><ul><li>Both this() and super() must be the <strong>first statement</strong> in the constructor.</li><li>Since only <strong>one</strong> statement can be first, using both is <strong>not allowed</strong>.</li></ul><h3>🔴 Example that causes compilation error:</h3><pre>class Parent {<br>    Parent() {<br>        System.out.println(&quot;Parent Constructor&quot;);<br>    }<br>}</pre><pre>class Child extends Parent {<br>    Child() {<br>        // ❌ Compilation Error<br>        // this();   // Calls another constructor<br>        // super();  // Calls parent constructor<br>    }<br>}</pre><h3>✅ Correct way: Call super() inside the called constructor</h3><p>You can <strong>indirectly</strong> use both by calling super() inside a constructor that is called via this().</p><pre>class Parent {<br>    Parent() {<br>        System.out.println(&quot;Parent Constructor&quot;);<br>    }<br>}</pre><pre>class Child extends Parent {<br>    Child() {<br>        this(&quot;Hello&quot;);  // ✅ this() is used first<br>    }</pre><pre>    Child(String msg) {<br>        super();        // ✅ now we can use super() here<br>        System.out.println(&quot;Child Constructor: &quot; + msg);<br>    }<br>}</pre><h3>✅ 2. Can we use more than one this() in constructor chaining?</h3><h3>❌ No, you cannot use this() more than once in the same constructor.</h3><ul><li>Just like super(), this() must be the <strong>first statement</strong>.</li><li>So, only one this() call is allowed per constructor.</li></ul><h3>🔴 Invalid Example:</h3><pre>public class Example {<br>    Example() {<br>        // ❌ Invalid - can&#39;t call this() more than once<br>        // this(10);<br>        // this(&quot;Hello&quot;);<br>    }</pre><pre>    Example(int x) {<br>        System.out.println(&quot;Constructor with int: &quot; + x);<br>    }</pre><pre>    Example(String msg) {<br>        System.out.println(&quot;Constructor with String: &quot; + msg);<br>    }<br>}</pre><h3>✅ Valid way: Use constructor chaining through multiple levels:</h3><pre>public class ChainExample {<br>    ChainExample() {<br>        this(10);  // Only one this() call here<br>        System.out.println(&quot;Default constructor&quot;);<br>    }</pre><pre>    ChainExample(int x) {<br>        this(&quot;Hello&quot;);  // Only one this() call here<br>        System.out.println(&quot;Constructor with int: &quot; + x);<br>    }</pre><pre>    ChainExample(String msg) {<br>        System.out.println(&quot;Constructor with String: &quot; + msg);<br>    }</pre><pre>    public static void main(String[] args) {<br>        new ChainExample();<br>    }<br>}</pre><h3>🧠 Output:</h3><pre>Constructor with String: Hello<br>Constructor with int: 10<br>Default constructor</pre><h3>✅ Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*_aRYuI1mNCrqcc3oouVigg.png" /></figure><h3>🔐 final Keyword</h3><p>The final keyword is used to declare constants, prevent method overriding, and inheritance.</p><p>Used to declare constants and restrict modification.</p><ul><li><strong>Final variable</strong> → Cannot be changed after initialization.</li><li><strong>Final method</strong> → Cannot be overridden.</li><li><strong>Final class</strong> → Cannot be extended (no subclass can be created).</li></ul><h3>Uses of final Keyword:</h3><ol><li><strong>Final Variable</strong> — Value cannot be changed.</li></ol><pre>final int x = 10;<br>x = 20; // Compilation Error</pre><p><strong>2. Final Method</strong> — Cannot be overridden by subclasses.</p><pre>class A {<br>    final void show() {<br>        System.out.println(&quot;A show()&quot;);<br>    }<br>}</pre><pre>class B extends A {<br>    void show() { // Error<br>        System.out.println(&quot;B show()&quot;);<br>    }<br>}</pre><p><strong>3. Final Class</strong> — Cannot be extended.</p><pre>final class Animal {<br>    void run() {<br>        System.out.println(&quot;Running&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal { // Error: Cannot inherit<br>}</pre><h3>⚙️ static Keyword</h3><h3>What is static?</h3><p>The static keyword is used for memory management and Loads common configuration. Belongs to the class, not to instances.</p><h3>Can be used with:</h3><ul><li>Variables</li><li>Methods</li><li>Blocks</li><li>Nested classes</li></ul><p>Cannot be used with:</p><ul><li>Local variables (directly)</li><li>Outer classes</li></ul><h3>💡 Rules for static methods:</h3><ol><li>Belongs to the class, not the object.</li><li>Can be accessed directly by class name.</li><li>Can access only static data (not instance data).</li><li>Can call only other static methods.</li><li>Cannot use this or super.</li></ol><p>🧱 <strong>Static block</strong>: Executes automatically when the class is loaded. Used to initialize static variables. Always runs before the main() method.</p><h3>Example of Static Variable and Method:</h3><pre>class Counter {<br>    static int count = 0;<br>  <br>    Counter() {<br>        count++;<br>        System.out.println(count);<br>    }<br><br>    static void show() {<br>        System.out.println(&quot;Static Method&quot;);<br>    }<br>}</pre><h3>Static Block:</h3><p>Executes only once when the class is loaded.</p><pre>class A {<br>    static {<br>        System.out.println(&quot;Static Block Called&quot;);<br>    }<br><br>    public static void main(String args[]) {<br>        System.out.println(&quot;Main Method&quot;);<br>    }<br>}</pre><h3>🌐 Native Methods</h3><p>🧬 Native methods are methods written in another language (like C/C++) but used in Java using the native keyword.</p><pre>public class Example {<br>    public native void sayHello();<br><br>    static {<br>        System.loadLibrary(&quot;MyLib&quot;);<br>    }<br>}</pre><h3>Use Case:</h3><p>Used when we want to call platform-specific code from Java (e.g., using JNI).</p><h3>Can We Say It’s Secure If Setters Are Present?</h3><p>Setter methods provide <strong>controlled access</strong> to private fields. Security and encapsulation depend on:</p><ul><li>Whether validation is done in the setter.</li><li>Whether the field can be mutated externally.</li></ul><h3>Example:</h3><pre>public class Account {<br>    private int balance;</pre><pre>    public void setBalance(int balance) {<br>        if (balance &gt; 0)<br>            this.balance = balance;<br>        else<br>            throw new IllegalArgumentException(&quot;Invalid Balance&quot;);<br>    }<br>}</pre><p><strong>Conclusion</strong>: Setters are not insecure <strong>if implemented properly with validation</strong>.</p><h3>❓ Interview Questions &amp; Answers</h3><h3>Q1: What is the purpose of the this keyword?</h3><p><strong>A:</strong> It refers to the current object and is used to resolve naming conflicts, call constructors, return object reference, or pass the object as an argument.</p><h3>Q2: How is super different from this?</h3><p><strong>A:</strong> this refers to the current class object, while super refers to the <strong>immediate parent</strong> class object.</p><h3>Q3: Can we use this and super in static methods?</h3><p><strong>A:</strong> ❌ No, static methods don’t belong to an object, so this and super are not accessible.</p><h3>Q4: Why use constructor chaining?</h3><p><strong>A:</strong> To avoid code duplication and ensure object initialization in a single place.</p><h3>Q5: What happens if you make a class final?</h3><p><strong>A:</strong> It cannot be extended. No class can inherit from a final class.</p><h3>Q6: Can we override a static method?</h3><p><strong>A:</strong> No. Static methods belong to the class, not to instances, so they can be hidden but not overridden.</p><h3>Q7: What is a native method in Java?</h3><p><strong>A:</strong> A method written in another programming language (like C) and integrated with Java using the native keyword.</p><h3>✅ Closing Statement</h3><blockquote><em>In this comprehensive journey through Java’s object-oriented pillars, core keywords, native method intricacies, and real-world interview questions, we’ve explored the foundational and advanced aspects every developer must know. Whether you’re preparing for interviews or strengthening your core Java knowledge, mastering these concepts will give you the confidence and clarity to write clean, robust, and maintainable code. Keep practicing, keep questioning, and most importantly — keep coding. The depth of Java is vast, but with a strong foundation like this, you’re already ahead.</em></blockquote><blockquote><em>🔥 </em>If you found this guide helpful, don’t forget to share it with fellow developers and bookmark it for quick revision. Happy learning!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8bf9b7f660c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Docker from Scratch — A Complete Beginner to Advanced Guide (With Java Spring Boot Example)]]></title>
            <link>https://medium.com/@shivapatel1102001/docker-from-scratch-a-complete-beginner-to-advanced-guide-with-java-spring-boot-example-2a5152b9d5b2?source=rss-cfe90cde530b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a5152b9d5b2</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[spring-boot-microservice]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <dc:creator><![CDATA[Shivampatel]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 18:23:18 GMT</pubDate>
            <atom:updated>2025-09-03T06:40:54.194Z</atom:updated>
            <content:encoded><![CDATA[<h3>🐳 Docker from Scratch — A Complete Beginner to Advanced Guide (With Java Spring Boot Example)</h3><h3>📘 What is Docker?</h3><p>Docker is a platform that enables developers to build, share, and run applications within containers. A <strong>container</strong> packages an application along with all its dependencies — code, runtime, system tools, libraries, and settings — ensuring consistency across all environments.</p><h3>🎯 Real-World Microservices Deployment with Spring Boot and Docker</h3><p>Let’s deploy a real-world Spring Boot Microservices project using Docker and Docker Compose.</p><h3>🧩 Microservices Overview:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*zqPAS4lEbFrsrSLMKYlX5Q.png" /></figure><h3>📑 Index</h3><ol><li>Install Docker (Windows)</li><li>Build all Spring Boot JARs</li><li>Create .dockerignore</li><li>Build all services</li><li>Write Dockerfiles</li><li><strong>Build images manually</strong> (per service)</li><li><strong>Run images manually</strong> (quick test)</li><li>Compose file for full system</li><li>docker‑compose up &amp; verification</li><li>Common CLI commands &amp; cleanup</li></ol><h3>🧱 Step-by-Step Deployment</h3><h3>🔹 Step 1: Install Docker</h3><ol><li>Download Docker Desktop: <a href="https://www.docker.com/products/docker-desktop">https://www.docker.com/products/docker-desktop</a></li><li>Install and start Docker.</li><li>Verify:</li></ol><pre>docker --version<br>docker info</pre><h3>📁 Step 2: Create .dockerignore File (Optional but Recommended)</h3><p>In the project root, create a file named .dockerignore (In each service) :</p><pre>target/*.original<br>*.iml<br>.idea<br>.git</pre><p>This ensures Docker doesn’t copy unnecessary files.</p><pre>school-management-system/<br>├── docker-compose.yml<br>├── .env                     # centralise secrets<br>├── .dockerignore            # root-level ignore<br>├── ServiceRegistry/<br>│   ├── Dockerfile<br>│   └── src/…<br>├── APIGateway/<br>│   ├── Dockerfile<br>│   └── src/…<br>├── UserService/<br>│   ├── Dockerfile<br>│   └── src/…<br>└── …                        # SchoolService &amp; StudentAcademicService</pre><h3>🔹 Step 3: Add .dockerignore to each service folder</h3><pre># .dockerignore<br>.target/<br>.idea/<br>*.iml<br>*.log<br>.git/</pre><h3>🔹 Step 4: Build All Services</h3><p>🧱 Commands to Build All Services</p><p>🔹 <strong>Step 4.1 — Build Service Registry</strong></p><pre>cd ../ServiceRegistry<br>./mvnw clean package -DskipTests</pre><p>🔹 <strong>Step 4.2 — Build API Gateway</strong></p><pre>cd ../APIGateway<br>./mvnw clean package -DskipTests</pre><p>🔹 <strong>Step 4.3 — Build UserService</strong></p><pre>cd ../UserService<br>./mvnw clean package -DskipTests</pre><p>🔹 <strong>Step 4.4 — Build SchoolService</strong></p><pre>cd ../SchoolService<br>./mvnw clean package -DskipTests</pre><p>🔹 <strong>Step 4.5 — Build StudentAcademicService</strong></p><pre>cd ../StudentAcademicService<br>./mvnw clean package -DskipTests</pre><p>ℹ️ Tip: If you’re using Maven instead of ./mvnw, replace it with:</p><pre>mvn clean package -DskipTests</pre><p>Run for each service:</p><p>📁 After These Commands</p><p>Each service will generate its .jar file inside its target/ folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*vd7kkSPAWL6oZBqIX_nj1A.png" /></figure><h3>🔹 Step 5: Dockerfiles for Each Service</h3><p>📁 Place the Dockerfile in the root of each service directory.</p><p>→ it is better to write EXPOSE port number same as that of the port number mention in application.json or application.yml file.</p><h4>🟢 1. Service Registry Dockerfile</h4><pre>FROM openjdk:17-jdk-slim<br>WORKDIR /app<br>COPY target/ServiceRegistry-0.0.1-SNAPSHOT.jar registry.jar<br>EXPOSE 809<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;registry.jar&quot;]</pre><h4>🟢 2. API Gateway Dockerfile</h4><pre>FROM openjdk:17-jdk-slim<br>WORKDIR /app<br>COPY target/APIGateWay-0.0.1-SNAPSHOT.jar gateway.jar<br>EXPOSE 8080<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;gateway.jar&quot;]</pre><h4>🟢 3. User Service Dockerfile</h4><pre>FROM openjdk:17-jdk-slim<br>WORKDIR /app<br>COPY target/UserService-0.0.1-SNAPSHOT.jar user.jar<br>EXPOSE 8081<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;user.jar&quot;]</pre><h4>🟢 4. School Service Dockerfile</h4><pre>FROM openjdk:17-jdk-slim<br>WORKDIR /app<br>COPY target/SchoolService-0.0.1-SNAPSHOT.jar school.jar<br>EXPOSE 8082<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;school.jar&quot;]</pre><h4>🟢 5. Student Academic Service Dockerfile</h4><pre>FROM openjdk:17-jdk-slim<br>WORKDIR /app<br>COPY target/StudentAcademicsService-0.0.1-SNAPSHOT.jar academic.jar<br>EXPOSE 8083<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;academic.jar&quot;]</pre><h3>🔹 Step 6: Build Docker Images Manually (optional but explicit)</h3><pre># Service Registry<br>docker build -t service-registry:v1 ./ServiceRegistry<br># API Gateway<br>docker build -t api-gateway:v1 ./APIGateWay<br># User Service<br>docker build -t user-service:v1 ./UserService<br># School Service<br>docker build -t school-service:v1 ./SchoolService<br># Student Academic Service<br>docker build -t student-academic-service:v1 ./StudentAcademicService</pre><p>Check:</p><pre>docker images | grep service</pre><h3>🔹 Step 5: Build docker-images</h3><p>Navigate to the directory containing the Dockerfile and build the Docker image:</p><pre>docker build -f Dockerfile -t sms_service_registry .</pre><pre>docker build -f Dockerfile -t sms_api_gateway .</pre><pre>docker build -f Dockerfile -t sms_user_service .</pre><pre>docker build -f Dockerfile -t sms_school_service .</pre><pre>docker build -f Dockerfile -t sms_student_academic_service .</pre><h3>🔹 Step 6: Run Images Manually (sanity check)</h3><p>You can also run image from docker desktop manually without using command.</p><p>To run images manually use following command</p><pre># Eureka<br>docker run -d --name sms_service_registry_container -p 8090:8090 sms_service_registry<br><br># if you have versioning the image<br>docker run -d --name sms_service_registry_container -p 8090:8090 sms_service_registry:v1<br><br># Stop &amp; remove when done<br>docker stop registry &amp;&amp; docker rm registry</pre><p>→ Similarly, you can run all the other service images</p><h3>🔹 Step 7: Create docker-compose.yml</h3><p>Create this in the root folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*g839AEzvb0hhjt4vm6_K7w.png" /></figure><pre>version: &#39;3.8&#39;<br><br>services:<br>  mongo:<br>    image: mongo<br>    ports:<br>      - &quot;27017:27017&quot;<br><br>  mysql:<br>    image: mysql:8.0<br>    environment:<br>      MYSQL_ROOT_PASSWORD: root<br>      MYSQL_DATABASE: schooldb<br>    ports:<br>      - &quot;3306:3306&quot;<br><br>  postgres:<br>    image: postgres:14<br>    environment:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: postgres<br>      POSTGRES_DB: smsstudentdb<br>    ports:<br>      - &quot;5432:5432&quot;<br><br>  service-registry:<br>    build: ./ServiceRegistry<br>    ports:<br>      - &quot;8090:8090&quot;<br><br>  api-gateway:<br>    build: ./APIGateWay<br>    depends_on:<br>      - service-registry<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      EUREKA_CLIENT_SERVICEURL_DEFAULTZONE: http://service-registry:8090/eureka<br><br>  user-service:<br>    build: ./UserService<br>    depends_on:<br>      - mongo<br>      - service-registry<br>    ports:<br>      - &quot;8081:8081&quot;<br>    environment:<br>      SPRING_DATA_MONGODB_URI: mongodb://mongo:27017/user_db<br>      EUREKA_CLIENT_SERVICEURL_DEFAULTZONE: http://service-registry:8090/eureka<br><br>  school-service:<br>    build: ./SchoolService<br>    depends_on:<br>      - mysql<br>      - service-registry<br>    ports:<br>      - &quot;8082:8082&quot;<br>    environment:<br>      SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/schooldb<br>      SPRING_DATASOURCE_USERNAME: root<br>      SPRING_DATASOURCE_PASSWORD: root<br>      EUREKA_CLIENT_SERVICEURL_DEFAULTZONE: http://service-registry:8090/eureka<br><br>  student-academic-service:<br>    build: ./StudentAcademicsService<br>    depends_on:<br>      - postgres<br>      - service-registry<br>    ports:<br>      - &quot;8083:8083&quot;<br>    environment:<br>      SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/smsstudentdb<br>      SPRING_DATASOURCE_USERNAME: postgres<br>      SPRING_DATASOURCE_PASSWORD: postgres<br>      EUREKA_CLIENT_SERVICEURL_DEFAULTZONE: http://service-registry:8090/eureka</pre><h3>🔹 Step 8: Run the System</h3><p>In the root directory (where docker-compose.yml is):</p><pre>docker-compose up --build </pre><p>This will:</p><ul><li>Build each service image</li><li>Run Mongo, MySQL, PostgreSQL</li><li>Register services with Eureka</li><li>Expose ports for testing</li></ul><p>✅ Visit: http://localhost:8080 (Gateway), http://localhost:8090 (Eureka UI)</p><h3>🔹 Step 9: Shut Down</h3><pre>docker-compose down</pre><h3>🔹 Handy CLI Reference</h3><pre># Images / Containers<br>docker images            # list images<br>docker ps -a             # list containers<br><br># Cleanup<br>docker system prune -a   # remove stopped containers + dangling images<br><br># Docker Compose helpers<br>docker-compose ps<br>docker-compose logs -f api-gateway<br>docker-compose restart school-service</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a5152b9d5b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Docker From Scratch — A Complete Beginner to Advanced Guide (Java + Database Examples)]]></title>
            <link>https://medium.com/@shivapatel1102001/docker-from-scratch-a-complete-beginner-to-advanced-guide-java-database-examples-16d6e531b0f2?source=rss-cfe90cde530b------2</link>
            <guid isPermaLink="false">https://medium.com/p/16d6e531b0f2</guid>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Shivampatel]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 18:22:31 GMT</pubDate>
            <atom:updated>2025-09-08T16:37:04.266Z</atom:updated>
            <content:encoded><![CDATA[<h3>🐳 Docker From Scratch — A Complete Beginner to Advanced Guide (Java + Database Examples)</h3><h3>📘 What is Docker?</h3><p>Docker is a platform used by developers to build, ship, and run applications inside lightweight, portable containers. It ensures that software runs uniformly across different environments — development, testing, production, or on another developer’s machine.</p><h3>🧠 Real-World Problem</h3><p>You developed a Spring Boot project in 2023 using Java 17 and MySQL 8. In 2025, your colleague tries to run it but their system uses Java 21 and MySQL 8.1. Version mismatch causes problems.</p><h3>✅ Docker Solution:</h3><p>Create a Docker container that contains:</p><ul><li>Java 17 runtime</li><li>MySQL 8</li><li>Your application code and configurations</li></ul><p>This way, your application will run exactly the same <strong>anywhere</strong>.</p><h3>🔹 Install Docker in Windows</h3><ol><li>Download Docker Desktop: <a href="https://www.docker.com/products/docker-desktop">https://www.docker.com/products/docker-desktop</a></li><li>Run the installer and follow the setup.</li><li>Open <strong>Docker Desktop</strong> → wait for “Engine Running” message.</li><li>Check Docker is installed:</li></ol><pre>docker --version<br>docker info</pre><h3>🧱 Docker Concepts Explained in Detail</h3><h3>📦 What is a Docker Image?</h3><ul><li>A <strong>Docker image</strong> is a <strong>read-only template</strong> that contains your app, runtime, libraries, and dependencies.</li><li>Example: openjdk:17-jdk-slim is an image with Java 17 JDK installed.</li></ul><p>➡️ Java Example:</p><pre>FROM openjdk:17-jdk-slim<br>WORKDIR /app<br>COPY target/*.jar app.jar<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>➡️ Command to build an image:</p><pre>docker build -t myapp:latest .</pre><h3>🧃 What is a Docker Container?</h3><ul><li>A <strong>running instance</strong> of an image.</li><li>It is isolated and can run regardless of the host machine’s environment.</li></ul><p>➡️ Run a container:</p><pre>docker run --name myapp-container -p 8080:8080 myapp:latest</pre><p>➡️ Enter into a container:</p><pre>docker exec -it myapp-container bash</pre><p>➡️ Stop a container:</p><pre>docker stop myapp-container</pre><p>➡️ Restart a container:</p><pre>docker restart myapp-container</pre><p>➡️ Remove a container:</p><pre>docker rm myapp-container</pre><p>➡️ Remove an image:</p><pre>docker rmi myapp:latest</pre><p>➡️ Force remove:</p><pre>docker rm -f myapp-container<br>docker rmi -f myapp:latest</pre><p>➡️ Clean up everything: (deleing all images and containers)</p><pre>docker system prune -a</pre><h3>🔄 Difference Between Image and Container</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*KgLNmz-6kWUcIUP4Mv-aEA.png" /></figure><h3>📥 Pulling &amp; Running Existing Images</h3><p>➡️ Pull an image from Docker Hub:</p><pre>docker pull openjdk:17-jdk-slim<br>docker pull mysql:8.0<br>docker pull postgres:14</pre><p>➡️ Run Node or Java container with interactive terminal:</p><pre>docker run -it node /bin/bash<br>docker run -it openjdk:17-jdk-slim /bin/bash</pre><h3>📄 Dockerfile Explained (Spring Boot Example)</h3><p>Create a Dockerfile in your Spring Boot project root:</p><pre>FROM openjdk:17-jdk-slim<br>WORKDIR /app<br>COPY target/*.jar app.jar<br>EXPOSE 8080<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>➡️ Build the image:</p><pre>./mvnw clean package -DskipTests<br>docker build -t springboot-app:latest .</pre><p>➡️ Run the container:</p><pre>docker run --name springboot-container -p 8080:8080 springboot-app:latest</pre><h3>🚫 .dockerignore</h3><p>Avoid copying unnecessary files into Docker image.</p><p>Create .dockerignore in project root:</p><pre>target/<br>.git/<br>*.iml<br>.idea/<br>*.log</pre><h3>🔢 Docker Image Versioning</h3><p>➡️ Tagging versions:</p><pre>docker build -t myapp:v1 .<br>docker build -t myapp:v2 .</pre><p>➡️ Run with specific version:</p><pre>docker run --name app-v1 -p 8081:8080 myapp:v1</pre><p>➡️ Delete specific image:</p><pre>docker rmi myapp:v1</pre><h3>💾 Docker Volumes (For Persistent Data)</h3><p>➡️ Run MySQL with volume:</p><pre>docker run -d --name mysql-db \<br> -e MYSQL_ROOT_PASSWORD=root \<br> -e MYSQL_DATABASE=schooldb \<br> -v mysql_data:/var/lib/mysql \<br> -p 3306:3306 mysql:8.0</pre><p>➡️ Volume list:</p><pre>docker volume ls</pre><p>➡️ Remove volume:</p><pre>docker volume rm mysql_data</pre><h3>🧰 Docker Compose (Multi-container Setup)</h3><h3>✅ Why?</h3><p>To run Java app + DB + Redis etc., in a single command.</p><h3>🐳 Why Use Docker Compose for Multiple Services?</h3><p>When we have just <strong>one service</strong> (like a single Spring Boot app), we can build its <strong>Docker image</strong> and run it using:</p><pre>docker build -t my-service:v1 .<br>docker run -d --name my-service -p 8080:8080 my-service:v1</pre><p>👉 But what if we have <strong>many services</strong> (like Service Registry, API Gateway, User Service, School Service, Student Service)?</p><p>If we use only docker run, we would need to:</p><ul><li>Build <strong>each image</strong> separately</li><li>Run <strong>each container</strong> manually</li><li>Expose and map ports one by one</li><li>Manage dependencies (e.g., Registry must start before Gateway, Gateway before User Service, etc.)</li></ul><p>⚠️ This becomes <strong>complex and messy</strong> very quickly.</p><h3>✅ Solution: Docker Compose</h3><p>Instead of running multiple docker run commands, we can use <strong>Docker Compose</strong>.</p><ul><li>We create a file named docker-compose.yml.</li><li>Inside it, we define <strong>all services</strong> (Registry, Gateway, UserService, etc.).</li><li>We configure ports, dependencies, and networking in one place.</li></ul><p>Then, with <strong>one command</strong>, we can start the whole system:</p><pre>docker-compose up --build</pre><p>👉 Docker Compose will:</p><ul><li>Build images for all services</li><li>Create and run containers</li><li>Set up a private network so services can talk to each other</li><li>Start services in the correct order</li></ul><h3>🛠️ Create docker-compose.yml</h3><pre>version: &#39;3.8&#39;<br>services:<br>  mysql:<br>    image: mysql:8.0<br>    environment:<br>      MYSQL_ROOT_PASSWORD: root<br>      MYSQL_DATABASE: schooldb<br>    ports:<br>      - &quot;3306:3306&quot;<br>    volumes:<br>      - db_data:/var/lib/mysql<br><br>  springboot-app:<br>    build: .<br>    ports:<br>      - &quot;8080:8080&quot;<br>    depends_on:<br>      - mysql<br>    environment:<br>      SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/schooldb<br>      SPRING_DATASOURCE_USERNAME: root<br>      SPRING_DATASOURCE_PASSWORD: root<br><br>volumes:<br>  db_data:</pre><p>➡️ Run all services:</p><pre>docker-compose up --build</pre><p>➡️ Stop all:</p><pre>docker-compose down</pre><p>➡️ List services:</p><pre>docker-compose ps</pre><p>➡️ Run specific service:</p><pre>docker-compose run springboot-app</pre><p>➡️ Restart only one service:</p><pre>docker-compose restart mysql</pre><p>➡️ Rebuild only one service:</p><pre>docker-compose build springboot-app</pre><p>➡️ Logs:</p><pre>docker-compose logs</pre><h3>🌍 Docker Hub (Public Image Registry)</h3><ol><li>Login or create account: <a href="https://hub.docker.com/">https://hub.docker.com</a></li><li>Login in terminal:</li></ol><pre>docker login</pre><ol><li>Tag image:</li></ol><pre>docker tag myapp username/myapp:latest</pre><ol><li>Push image:</li></ol><pre>docker push username/myapp</pre><ol><li>Pull image from another system:</li></ol><pre>docker pull username/myapp</pre><h3>🔍 Docker CLI Commands Summary</h3><h3>🚀 Image Commands</h3><pre>docker build -t myapp .      # Build image<br>docker images                # List all images<br>docker rmi image_id          # Delete image<br>docker pull image_name       # Pull from Docker Hub<br>docker tag old new           # Tag an image</pre><h3>📦 Container Commands</h3><pre>docker run -p 8080:8080 myapp         # Run container<br>docker ps                             # List running containers<br>docker ps -a                          # List all containers<br>docker stop container_id              # Stop container<br>docker rm container_id                # Remove container<br>docker exec -it container_id bash     # Access running container shell</pre><h3>🧹 Cleanup</h3><pre>docker system prune -a                # Remove all stopped containers/images</pre><h3>🧊 Volume Commands</h3><pre>docker volume ls                      # List volumes<br>docker volume rm volume_name          # Remove volume</pre><h3>🧩 Compose Commands</h3><pre>docker-compose up --build             # Build and run all services<br>docker-compose down                   # Stop all services<br>docker-compose ps                     # View running services<br>docker-compose restart service        # Restart specific service</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16d6e531b0f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Exception Handling in Java: Complete Guide with Examples]]></title>
            <link>https://medium.com/@shivapatel1102001/exception-handling-in-java-complete-guide-with-examples-d2d1daf0457c?source=rss-cfe90cde530b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2d1daf0457c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[throw]]></category>
            <category><![CDATA[try]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[error]]></category>
            <dc:creator><![CDATA[Shivampatel]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 13:45:47 GMT</pubDate>
            <atom:updated>2025-07-10T13:45:47.994Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔸 What is an Exception?</h3><p>It is an unwanted or unexpected event, which occurs during the exception of the program at run time, that disturbs the normal flow of the program.</p><p>🔸 Java Exception Hierarchy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*YVVb-kDW5Ddyx1A52KOUPw.png" /></figure><p>Object class is the parent class of all the objects.</p><p><strong>Throwable</strong> is parent class of Class Exception and class Error.</p><p><strong>Exception :-</strong></p><ul><li>Cause of the program</li><li>Recoverable</li></ul><p><strong>Exception are of two types :-</strong></p><ul><li><strong>Compile time exception</strong> (Checked Exception)</li><li><strong>Run time exception </strong>(Unchecked Exception)</li></ul><p><strong>Error :-</strong></p><ul><li>Cause because of lack of the system resources.</li><li>Cannot be recover</li><li>Error is of only one type :- Run time error.</li></ul><p><strong>❌ Compile time exception occurs at compile time and run time exception occurs at run time.</strong></p><p><strong>✅All exceptions occurs at runtime</strong></p><p>Whenever there is exception, the method in which exception occurs will create an object and that object stores three things</p><p><strong>Exception Name, Description and Stack Trace</strong></p><h3>🔸 Exception Handling Keywords</h3><h3>1. try</h3><p>Wraps the code that might throw an exception.</p><h3>2. catch</h3><p>Handles the exception.</p><h3>3. finally</h3><p>Code that executes regardless of exception (e.g., closing resources).</p><h3>4. throw</h3><p>Used to explicitly throw an exception.</p><h3>5. throws</h3><p>Declares exceptions a method might throw.</p><h3>🔸 Facts about try catch finally</h3><p>→ We cannot write try block without catch or finally</p><p>Means :-</p><p><strong>✅ </strong>try catch</p><p><strong>✅ </strong>try catch finally</p><p><strong>✅ </strong>try finally</p><p>❌try</p><p>In Java, when you write multiple catch blocks, they are evaluated <strong>top to bottom</strong>, and the <strong>first matching catch block</strong> is executed. Therefore, writing a <strong>parent exception before a child exception</strong> causes a <strong>compile-time error</strong> because the child catch block becomes <strong>unreachable</strong>.</p><h3>❗ Scenario: Parent Exception Before Child Exception</h3><pre>public class Demo {<br>    public static void main(String[] args) {<br>        try {<br>            String str = null;<br>            str.length();  // Throws NullPointerException<br>        } catch (Exception e) { // 🔴 Parent catch block<br>            System.out.println(&quot;Caught Exception&quot;);<br>        } catch (NullPointerException e) { // 🔴 Child catch block<br>            System.out.println(&quot;Caught NullPointerException&quot;);<br>        }<br>    }<br>}</pre><h3>🔴 Compilation Error:</h3><pre>error: exception NullPointerException has already been caught</pre><h3>🔸 Facts about finally block</h3><p>→ It is always execute even if the try block contains control transfer statements (i.e. jump statement) like return, break, or continue</p><p>Possible ways that stops the finally block from the execution</p><ol><li>Using <strong>System.exist() </strong>method.</li><li>Causing a fatal error that cause process to abort</li></ol><h3>🔸 Basic Example</h3><pre>public class Example {<br>    public static void main(String[] args) {<br>        try {<br>            int result = 10 / 0; // will throw ArithmeticException<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Error: &quot; + e.getMessage());<br>        } finally {<br>            System.out.println(&quot;Finally block executed.&quot;);<br>        }<br>    }<br>}</pre><h3>🔸 Multiple Catch Blocks</h3><pre>try {<br>    int[] arr = new int[5];<br>    arr[10] = 50;<br>} catch (ArithmeticException e) {<br>    System.out.println(&quot;Arithmetic Error&quot;);<br>} catch (ArrayIndexOutOfBoundsException e) {<br>    System.out.println(&quot;Array Index Error&quot;);<br>} catch (Exception e) {<br>    System.out.println(&quot;Generic Error&quot;);<br>}</pre><p><strong>Note:</strong> Always place the more specific exception before the general Exception.</p><h3>🔸 Nested Try Blocks</h3><pre>try {<br>    System.out.println(&quot;Outer try block&quot;);<br>    try {<br>        int a = 10 / 0;<br>    } catch (ArithmeticException e) {<br>        System.out.println(&quot;Inner catch: &quot; + e);<br>    }<br>} catch (Exception e) {<br>    System.out.println(&quot;Outer catch: &quot; + e);<br>}</pre><h3>🔸 Custom Exceptions</h3><p>You can create your own exception by extending Exception or RuntimeException.</p><pre>class AgeValidationException extends Exception {<br>    public AgeValidationException(String message) {<br>        super(message);<br>    }<br>}<br>public class CustomExceptionTest {<br>    static void validate(int age) throws AgeValidationException {<br>        if (age &lt; 18) {<br>            throw new AgeValidationException(&quot;Age must be 18 or older.&quot;);<br>        }<br>    }<br>public static void main(String[] args) {<br>        try {<br>            validate(15);<br>        } catch (AgeValidationException e) {<br>            System.out.println(&quot;Caught Exception: &quot; + e.getMessage());<br>        }<br>    }<br>}<br></pre><p><strong>Note</strong>: To create a <strong>checked exception</strong>, extend Exception. To create an <strong>unchecked exception</strong>, extend RuntimeException.</p><p>🔸 throw</p><p>throw keyword is used to throw the exception by the programmer to JVM.</p><p>- Also, we cannot write any statement after throw keyword statement — otherwise it will give <strong>compiler error.</strong></p><ul><li>throw keyword is used to create exception object manually but it cannot handle the exception, rather to handle the exception we have to write try catch block.</li></ul><p>🔸 throws</p><p>throws keyword is used to declare the exception. it give information to the caller method that there may occur exception might occur.</p><p><strong>It is better to handle exception using try catch block </strong>for the checked exception instead of using <strong>throws anyexception </strong>with the method because try catch block handles the exception and does not terminates the program but by using <strong>throws anyexception </strong>if exception occurs then it abnormally terminates the program.</p><p><strong>throw</strong> keyword is mainly used for runtime exceptions or checked exception but <strong>throws</strong> keyword is mainly used for compile time exceptions or checked exception</p><p>🔸 Difference: throw vs throws</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*9wqbWcMLW6nPI4Cot1F0pg.png" /></figure><p><strong>→ it will give compiler error if we write any code after the throw statement.</strong></p><p>→ If we don’t handle any exception in main class and if exception occurs then JVM internally call the default exception handler and throw the exception and abnormally terminates the program. [Same case with the caller method, it first pass the exception to main method and then to the default exception handler.]</p><h3>✅ Does the order of exceptions after throws matter?</h3><p><strong>No</strong>, the order in which you declare exceptions after the throws keyword <strong>doesn&#39;t affect compilation or runtime</strong>.</p><h3>✔ Both of these are valid:</h3><pre>void printHello() throws IOException, NullPointerException, Exception { }</pre><pre>void printHello() throws NullPointerException, IOException, Exception { }</pre><p>👉 But while it’s <strong>legal</strong>, there’s something important to understand…</p><h3>❌ Declaring Parent Exception After Child Exception is Redundant</h3><h3>Example:</h3><pre>void printHello() throws IOException, Exception { }</pre><p>Since IOException is a subclass of Exception, listing both is <strong>redundant</strong>.</p><ul><li>The compiler won’t complain.</li><li>But it’s bad practice and may confuse others reading the code.</li><li>You should only declare the <strong>most general necessary exception</strong>.</li></ul><h3>❌ Declaring only parent is enough</h3><pre>// This is enough<br>void myMethod() throws Exception { <br>    throw new IOException(); // Allowed, since IOException is a subclass<br>}</pre><h3>⚠ Will this cause a compile-time or runtime error?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*bL--vZRESbQMzWYkWyeWfQ.png" /></figure><h3>✅ Best Practice</h3><blockquote><em>Always declare the </em><strong><em>most specific exception(s)</em></strong><em> that the method might throw. Avoid redundancy.</em></blockquote><h3>✅ Good:</h3><pre>void readFile() throws IOException { }</pre><h3>❌ Bad (redundant):</h3><pre>void readFile() throws IOException, Exception { }  // Don&#39;t do this</pre><p>🔸 Exception Declaration in throws – Parent vs Child</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQofCRWwPDRYp55PSAaTNw.png" /></figure><h3>📌 Tip</h3><blockquote><em>✅ Java doesn’t care about the </em><strong><em>order</em></strong><em> of exceptions after </em><em>throws, but you should care about </em><strong><em>readability and redundancy</em></strong><em>.</em></blockquote><h3>🔸 Common Runtime Exceptions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*yRJnxE7VOKsVsOF-lNINAQ.png" /></figure><h3>🔸 Try-With-Resources (Java 7+)</h3><p>Automatically closes the resource (like streams, readers).</p><pre>try (BufferedReader br = new BufferedReader(new FileReader(&quot;file.txt&quot;))) {<br>    String line;<br>    while ((line = br.readLine()) != null) {<br>        System.out.println(line);<br>    }<br>} catch (IOException e) {<br>    e.printStackTrace();<br>}</pre><h3>🔸 Best Practices</h3><ol><li><strong>Catch Specific Exceptions</strong><br> Avoid catching Exception or Throwable unless necessary.</li><li><strong>Don’t Suppress Exceptions</strong><br> Don’t write empty catch blocks:</li></ol><pre>catch (Exception e) {<br>    // bad practice<br>}<br><br></pre><p><strong>3. Use Finally or Try-with-Resources for Cleanup</strong></p><p><strong>4. Avoid Using Exceptions for Flow Control</strong></p><p><strong>5. Log the Exception Properly</strong></p><h3>🔸 Code Example:</h3><pre>public class Test {<br>    void printHello() throws IOException, NullPointerException {<br>        System.out.println(&quot;hello&quot;);<br>    }<br>}</pre><h3>✅ Is this compilation legal?</h3><p>Yes, <strong>this code will compile without error</strong>.</p><h3>🧠 Why?</h3><p>Because Java allows a method to declare any <strong>checked</strong> or <strong>unchecked</strong> exceptions in the throws clause — <strong>even if the method doesn’t actually throw them</strong>.</p><p>However, there are some nuances:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*agvNC5G2D276ZD7D8xs8VQ.png" /></figure><h3>🤔 But is this good practice?</h3><p>No. Declaring unnecessary exceptions:</p><p>❌ Confuses other developers</p><p>❌ Forces the <strong>caller</strong> of the method to handle or declare those exceptions unnecessarily</p><p>❌ Makes API contracts misleading</p><h3>🔥 Example of Misleading Throws</h3><pre>void doNothing() throws SQLException {<br>    // nothing here<br>}</pre><p>❌ Caller thinks it must prepare to catch SQLException</p><p>❌ But SQLException will never be thrown</p><p>🔸 Checked vs Unchecked Exceptions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*-LgdRwdG2opMJVxqYXfBsg.png" /></figure><h3>🔸 Conclusion</h3><p>Exception handling is not just a language feature — it’s a <strong>design principle</strong>. Handling exceptions properly leads to more robust, maintainable, and reliable code. Always anticipate potential failures and gracefully recover using exception handling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2d1daf0457c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Complete Guide to Spring and Spring Boot Annotations (With Summary Table)]]></title>
            <link>https://medium.com/@shivapatel1102001/complete-guide-to-spring-and-spring-boot-annotations-with-summary-table-fec2f9435b3d?source=rss-cfe90cde530b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fec2f9435b3d</guid>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Shivampatel]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 09:32:58 GMT</pubDate>
            <atom:updated>2025-07-08T09:32:58.445Z</atom:updated>
            <content:encoded><![CDATA[<p>Annotations in Spring and Spring Boot are powerful tools that help developers write clean, declarative, and configuration-less code. Below is a complete list of annotations divided by purpose — Core, Dependency Injection, Configuration, Web, AOP, Testing, etc. — followed by detailed descriptions of each.</p><pre>| Annotation                     | Description                                 | Target(s)                          | Package                                                   | Common |<br>|--------------------------------|---------------------------------------------|------------------------------------|-----------------------------------------------------------|--------|<br>| `@Component`                   | Spring-managed component                    | Class                              | `org.springframework.stereotype`                          | Yes    |<br>| `@Service`                     | Specialization of `@Component` for services | Class                              | `org.springframework.stereotype`                          | Yes    |<br>| `@Repository`                  | Specialization of `@Component` for DAO      | Class                              | `org.springframework.stereotype`                          | Yes    |<br>| `@Controller`                  | Marks a web controller                      | Class                              | `org.springframework.stereotype`                          | Yes    |<br>| `@RestController`              | `@Controller` + `@ResponseBody`             | Class                              | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@Autowired`                   | Inject dependencies automatically           | Field,Constructor,Method,Parameter | `org.springframework.beans.factory.annotation`            | Yes    |<br>| `@Qualifier`                   | Specify bean when multiple exist            | Field,Parameter,Method             | `org.springframework.beans.factory.annotation`            | Yes    |<br>| `@Value`                       | Inject property values                      | Field,Parameter,Method             | `org.springframework.beans.factory.annotation`            | Yes    |<br>| `@Bean`                        | Declares a Spring bean in config class      | Method                             | `org.springframework.context.annotation`                  | Yes    |<br>| `@Configuration`               | Defines Spring config class                 | Class                              | `org.springframework.context.annotation`                  | Yes    |<br>| `@ComponentScan`               | Enables component scanning                  | Class                              | `org.springframework.context.annotation`                  | Yes    |<br>| `@EnableAutoConfiguration`     | Enables Spring Boot auto-config             | Class                              | `org.springframework.boot.autoconfigure`                  | Yes    |<br>| `@SpringBootApplication`       | Combines config, auto-config, scanning      | Class                              | `org.springframework.boot.autoconfigure`                  | Yes    |<br>| `@RequestMapping`              | Maps HTTP requests                          | Class,Method                       | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@GetMapping` / `@PostMapping` | Shortcut mappings                           | Method                             | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@PathVariable`                | Bind URI variable to method param           | Parameter                          | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@RequestParam`                | Bind query param                            | Parameter                          | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@RequestBody`                 | Bind request body                           | Parameter                          | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@ResponseBody`                | Return object as HTTP response              | Method                             | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@ResponseStatus`              | Set HTTP status                             | Class,Method                       | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@ExceptionHandler`            | Handle exceptions                           | Method                             | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@ControllerAdvice`            | Global exception/model handler              | Class                              | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@RestControllerAdvice`        | `@ControllerAdvice` + `@ResponseBody`       | Class                              | `org.springframework.web.bind.annotation`                 | Yes    |<br>| `@Entity`                      | JPA entity                                  | Class                              | `jakarta.persistence` / `javax.persistence`               | Yes    |<br>| `@Id`                          | Primary key                                 | Field,Method                       | `jakarta.persistence` / `javax.persistence`               | Yes    |<br>| `@GeneratedValue`              | Auto-generate ID                            | Field,Method                       | `jakarta.persistence` / `javax.persistence`               | Yes    |<br>| `@Table`                       | DB table name                               | Class                              | `jakarta.persistence`                                     | Yes    |<br>| `@Column`                      | DB column mapping                           | Field,Method                       | `jakarta.persistence`                                     | Yes    |<br>| `@Transactional`               | Transaction management                      | Class,Method                       | `org.springframework.transaction.annotation`              | Yes    |<br>| `@EnableTransactionManagement` | Enables `@Transactional`                    | Class                              | `org.springframework.transaction.annotation`              | Yes    |<br>| `@Profile`                     | Conditional bean load                       | Class,Method                       | `org.springframework.context.annotation`                  | Yes    |<br>| `@Scope`                       | Define bean scope                           | Class,Method                       | `org.springframework.context.annotation`                  | Yes    |<br>| `@PostConstruct`               | Init after bean creation                    | Method                             | `jakarta.annotation` / `javax.annotation`                 | Yes    |<br>| `@PreDestroy`                  | Cleanup before bean destroy                 | Method                             | `jakarta.annotation` / `javax.annotation`                 | Yes    |<br>| `@EnableScheduling`            | Enables scheduling                          | Class                              | `org.springframework.scheduling.annotation`               | Yes    |<br>| `@Scheduled`                   | Schedules tasks                             | Method                             | `org.springframework.scheduling.annotation`               | Yes    |<br>| `@EnableAsync`                 | Enables async execution                     | Class                              | `org.springframework.scheduling.annotation`               | Yes    |<br>| `@Async`                       | Execute method asynchronously               | Method                             | `org.springframework.scheduling.annotation`               | Yes    |<br>| `@Test`                        | JUnit test                                  | Method                             | `org.junit.jupiter.api` / `org.junit`                     | Yes    |<br>| `@SpringBootTest`              | Boot full Spring context                    | Class                              | `org.springframework.boot.test.context`                   | Yes    |<br>| `@MockBean`                    | Mock and inject bean                        | Field,Method                       | `org.springframework.boot.test.mock.mockito`              | Yes    |<br>| `@DataJpaTest`                 | JPA repository test                         | Class                              | `org.springframework.boot.test.autoconfigure.orm.jpa`     | Yes    |<br>| `@WebMvcTest`                  | Web controller test                         | Class                              | `org.springframework.boot.test.autoconfigure.web.servlet` | Yes    |<br>| `@RestClientTest`              | REST client test                            | Class                              | `org.springframework.boot.test.autoconfigure.web.client`  | Yes    |</pre><h3>🧠 Core Stereotype Annotations</h3><h3>@Component</h3><p>Marks a class as a Spring-managed bean. Can be detected by @ComponentScan.</p><pre>@Component<br>public class MyComponent {<br>}</pre><h3>@Service, @Repository, @Controller</h3><p>Specialized forms of @Component:</p><ul><li>@Service – for service layer</li><li>@Repository – for persistence layer (adds exception translation)</li><li>@Controller – for MVC controller</li></ul><pre>@Service<br>public class UserService {}</pre><pre>@Repository<br>public class UserRepository {}</pre><pre>@Controller<br>public class HomeController {}</pre><h3>@RestController</h3><p>Shortcut for @Controller + @ResponseBody. Used in REST APIs.</p><pre>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class ApiController {<br>    @GetMapping(&quot;/hello&quot;)<br>    public String sayHello() {<br>        return &quot;Hello World&quot;;<br>    }<br>}</pre><h3>🛠️ Dependency Injection Annotations</h3><h3>@Autowired</h3><p>Injects dependencies automatically.</p><pre>@Autowired<br>private UserService userService;</pre><h3>@Qualifier</h3><p>Used with @Autowired when multiple beans of same type exist.</p><pre>@Autowired<br>@Qualifier(&quot;emailService&quot;)<br>private NotificationService service;</pre><h3>🏷️ @Qualifier Annotation in Spring</h3><h3>📌 What is @Qualifier?</h3><p>@Qualifier is a Spring annotation used to <strong>resolve the ambiguity</strong> when multiple beans of the same type exist. It tells Spring <strong>which exact bean</strong> to inject when there are <strong>multiple candidate beans</strong> available for autowiring.</p><h3>🔍 Why is @Qualifier Needed?</h3><p>In Spring, when we use @Autowired, Spring tries to inject the required dependency by type. But if there are <strong>multiple beans of the same type</strong>, Spring doesn&#39;t know <strong>which one to inject</strong>, and you&#39;ll get an exception like:</p><pre>NoUniqueBeanDefinitionException: expected single matching bean but found 2</pre><p>@Qualifier solves this by specifying <strong>the name of the bean</strong> to inject.</p><h3>✅ Syntax</h3><pre>@Autowired<br>@Qualifier(&quot;beanName&quot;)<br>private SomeType someBean;</pre><h3>🎯 Real Example: With Java Spring Boot</h3><h3>💡 Scenario:</h3><p>You have two NotificationService implementations:</p><ul><li>EmailNotificationService</li><li>SMSNotificationService</li></ul><p>You want to use <strong>only one</strong> at a specific place.</p><h3>🔨 Step-by-Step Implementation</h3><h4>1. Create an Interface</h4><pre>public interface NotificationService {<br>    void sendNotification(String message);<br>}</pre><h4>2. Create Two Implementations</h4><pre>@Service(&quot;emailService&quot;)<br>public class EmailNotificationService implements NotificationService {<br>    @Override<br>    public void sendNotification(String message) {<br>        System.out.println(&quot;Email Sent: &quot; + message);<br>    }<br>}</pre><pre>@Service(&quot;smsService&quot;)<br>public class SMSNotificationService implements NotificationService {<br>    @Override<br>    public void sendNotification(String message) {<br>        System.out.println(&quot;SMS Sent: &quot; + message);<br>    }<br>}</pre><blockquote><em>Note: The names </em><em>&quot;emailService&quot; and </em><em>&quot;smsService&quot; are the bean names registered in Spring.</em></blockquote><h4>3. Use @Qualifier in Your Controller or Service</h4><pre>@RestController<br>public class NotificationController {</pre><pre>    private final NotificationService notificationService;</pre><pre>    @Autowired<br>    public NotificationController(@Qualifier(&quot;smsService&quot;) NotificationService notificationService) {<br>        this.notificationService = notificationService;<br>    }</pre><pre>    @GetMapping(&quot;/notify&quot;)<br>    public String notifyUser() {<br>        notificationService.sendNotification(&quot;Your order has been shipped!&quot;);<br>        return &quot;Notification sent&quot;;<br>    }<br>}</pre><blockquote><em>✅ This tells Spring to inject the </em><em>smsService implementation of </em><em>NotificationService.</em></blockquote><h3>🛑 What if @Qualifier is NOT used?</h3><pre>@Autowired<br>private NotificationService notificationService;</pre><p>Spring will throw an error like:</p><pre>NoUniqueBeanDefinitionException: No qualifying bean of type &#39;NotificationService&#39; available: expected single matching bean but found 2: emailService,smsService</pre><h3>📦 Use with @Component, @Service, @Repository</h3><p>You can also use @Qualifier with components declared with @Component, @Service, etc.</p><p>Example:</p><pre>@Component(&quot;fileStorageService&quot;)<br>public class FileStorageService implements StorageService { ... }</pre><pre>@Component(&quot;dbStorageService&quot;)<br>public class DBStorageService implements StorageService { ... }</pre><pre>@Autowired<br>@Qualifier(&quot;fileStorageService&quot;)<br>private StorageService storageService;</pre><h3>🧠 Tip: @Primary vs @Qualifier</h3><p>If you always want one specific bean to be injected <strong>by default</strong>, use @Primary:</p><pre>@Primary<br>@Service<br>public class EmailNotificationService implements NotificationService { ... }</pre><p>Then @Autowired will inject this unless @Qualifier is used.</p><h3>🧪 Testing with @Qualifier</h3><p>In test cases or configuration classes, you can also use:</p><pre>@Bean<br>@Qualifier(&quot;mockEmail&quot;)<br>public NotificationService emailNotificationService() {<br>    return new MockEmailNotificationService();<br>}</pre><h3>@Value</h3><p>Injects values from property files.</p><pre>@Value(&quot;${app.name}&quot;)<br>private String appName;</pre><h3>⚙️ Configuration &amp; Bean Annotations</h3><h3>@Configuration</h3><p>Marks a class that provides bean definitions.</p><pre>@Configuration<br>public class AppConfig {<br>    @Bean<br>    public MyService myService() {<br>        return new MyService();<br>    }<br>}</pre><h3>@Bean</h3><p>Defines a method that returns a Spring-managed bean.</p><h3>@ComponentScan</h3><p>Specifies base packages to scan for components.</p><h3>@SpringBootApplication</h3><p>Combination of @Configuration, @EnableAutoConfiguration, @ComponentScan.</p><h3>@EnableAutoConfiguration</h3><p>Auto-configures Spring Boot app based on dependencies.</p><h3>🌐 Web &amp; REST Annotations</h3><h3>@RequestMapping, @GetMapping, @PostMapping, etc.</h3><p>Map web requests to handler methods.</p><pre>@GetMapping(&quot;/user/{id}&quot;)<br>public User getUser(@PathVariable Long id) {}</pre><h3>@PathVariable, @RequestParam, @RequestBody, @ResponseBody</h3><p>Used to extract data from HTTP request parts.</p><h3>@ResponseStatus</h3><p>Set custom status for response.</p><h3>@ExceptionHandler</h3><p>Handle specific exceptions in a controller.</p><h3>@ControllerAdvice, @RestControllerAdvice</h3><p>Global exception handling for all controllers.</p><h3>📦 Persistence (JPA) Annotations</h3><h3>@Entity, @Id, @GeneratedValue, @Table, @Column, @Transient</h3><p>Used for ORM mapping with Hibernate/JPA.</p><h3>@Transient – Ignore Field for Persistence</h3><h3>🔍 What is @Transient?</h3><p>@Transient is used in <strong>JPA (Java Persistence API)</strong> to mark a field that <strong>should not be persisted in the database</strong>.</p><p>It means:</p><ul><li>This field is part of the class in memory.</li><li>But it is not saved in the table when you persist the object.</li></ul><h3>✅ Syntax</h3><pre>@Transient<br>private String tempCalculationResult;</pre><h3>🔧 Real-World Example</h3><p>Suppose you have a User entity where you want to store full name (derived from first and last name), but you don’t want to store it in the database.</p><pre>@Entity<br>public class User {<br>    @Id<br>    private Long id;<br>    private String firstName;<br>    private String lastName;</pre><pre>    @Transient<br>    private String fullName;</pre><pre>    public String getFullName() {<br>        return firstName + \&quot; \&quot; + lastName;<br>    }<br>}</pre><ul><li>firstName and lastName will be saved in the DB.</li><li>fullName will <strong>not</strong> be saved, because it&#39;s derived at runtime.</li></ul><h3>⚠️ Note:</h3><ul><li>Don’t confuse with transient keyword in Java (used for serialization).</li><li>@Transient is for JPA; transient is for Java serialization.</li></ul><h3>🔁 Transactional Annotations</h3><h3>@Transactional</h3><p>Enables transaction management.</p><h3>@EnableTransactionManagement</h3><p>Enable usage of @Transactional.</p><h3>1. @Transactional – Manage Transactions Automatically</h3><h3>🔍 What is @Transactional?</h3><p>@Transactional is a Spring annotation used to <strong>wrap a method or class in a database transaction</strong>. It ensures that:</p><ul><li>All the statements within the method run as a <strong>single transaction</strong>.</li><li>If <strong>any exception</strong> occurs, everything is <strong>rolled back</strong> automatically.</li><li>If everything goes well, the transaction is <strong>committed</strong>.</li></ul><h3>✅ Syntax</h3><pre>@Transactional<br>public void methodName() {<br>    // transactional code<br>}</pre><p>Can be applied at:</p><ul><li><strong>Method level</strong> — affects only that method.</li><li><strong>Class level</strong> — affects all public methods in the class.</li></ul><h3>🔧 Real-World Example</h3><h4>Suppose you have a service that:</h4><ol><li>Saves an order</li><li>Deducts payment</li><li>Sends confirmation</li></ol><p>You want all 3 to succeed or <strong>none at all</strong> (atomic transaction).</p><pre>@Service<br>public class OrderService {</pre><pre>    @Autowired<br>    private OrderRepository orderRepository;</pre><pre>    @Autowired<br>    private PaymentService paymentService;</pre><pre>    @Transactional<br>    public void placeOrder(Order order) {<br>        orderRepository.save(order);                  // Step 1<br>        paymentService.deduct(order.getAmount());     // Step 2<br>        sendConfirmationEmail(order);                 // Step 3<br>    }<br>}</pre><p>If step 2 or 3 fails, Spring <strong>automatically rolls back</strong> the order saved in step 1.</p><h3>🧠 Important Details</h3><p>Attributes</p><p>rollbackFor :-Specify which exceptions should trigger rollback (e.g., rollbackFor = Exception.class)</p><p>readOnly :-Optimize performance for read-only operations</p><p>propagation :-Defines how transactions interact (e.g., REQUIRED, REQUIRES_NEW, etc.)</p><h3>🧪 Testing Annotations</h3><h3>@SpringBootTest, @WebMvcTest, @DataJpaTest, @MockBean, @Test</h3><p>Used to write various types of tests in Spring Boot.</p><h3>🕒 Scheduling &amp; Async</h3><h3>@EnableScheduling, @Scheduled</h3><p>For scheduling background tasks.</p><h3>@EnableAsync, @Async</h3><p>For asynchronous method execution.</p><h3>👥 Profile &amp; Lifecycle</h3><h3>@Profile</h3><p>Load beans conditionally by profile name.</p><pre>@Profile(&quot;dev&quot;)<br>@Bean<br>public DataSource devDataSource() {}</pre><h3>2. @Profile – Load Beans Based on Environment</h3><h3>🔍 What is @Profile?</h3><p>@Profile is used to define <strong>which Spring environment profile a bean should be loaded in</strong>.</p><p>For example, you may want different configurations for:</p><ul><li>Development</li><li>Testing</li><li>Production</li></ul><h3>✅ Syntax</h3><pre>@Profile(&quot;dev&quot;)<br>@Component<br>public class DevDataSourceConfig implements DataSourceConfig {<br>    ...<br>}</pre><pre>@Profile(&quot;prod&quot;)<br>@Component<br>public class ProdDataSourceConfig implements DataSourceConfig {<br>    ...<br>}</pre><p>Then, activate the desired profile in:</p><pre># application.properties<br>spring.profiles.active=dev</pre><h3>🔧 Real-World Use Case</h3><p>Different database URLs for dev and prod:</p><pre>@Configuration<br>@Profile(&quot;dev&quot;)<br>public class DevDatabaseConfig {<br>    @Bean<br>    public DataSource dataSource() {<br>        return new HikariDataSource(&quot;jdbc:h2:mem:devdb&quot;);<br>    }<br>}</pre><pre>@Configuration<br>@Profile(&quot;prod&quot;)<br>public class ProdDatabaseConfig {<br>    @Bean<br>    public DataSource dataSource() {<br>        return new HikariDataSource(&quot;jdbc:mysql://prod-db:3306/myapp&quot;);<br>    }<br>}</pre><h3>💡 Use @Profile with:</h3><p>@Component, @Configuration, @Service, @Bean, etc.</p><h3>@Scope</h3><p>Defines scope like singleton, prototype.</p><h3>@PostConstruct, @PreDestroy</h3><p>Lifecycle hooks for beans.</p><h3>✨ Final Thoughts</h3><p>This guide gives you a <strong>complete walkthrough of all annotations in Spring and Spring Boot</strong> — both commonly and rarely used. Understanding and applying them effectively will help you build robust, maintainable, and production-ready applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fec2f9435b3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>