<?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 Sharayu Sanjay Yeole on Medium]]></title>
        <description><![CDATA[Stories by Sharayu Sanjay Yeole on Medium]]></description>
        <link>https://medium.com/@sharayuyeole38?source=rss-b6b4c0ac3e87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mnWgT1-5Ii4c7EeW</url>
            <title>Stories by Sharayu Sanjay Yeole on Medium</title>
            <link>https://medium.com/@sharayuyeole38?source=rss-b6b4c0ac3e87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:33:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sharayuyeole38/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[Springboot- REST API- Basic Project]]></title>
            <link>https://medium.com/@sharayuyeole38/springboot-rest-api-basic-project-f0af5b0f9c21?source=rss-b6b4c0ac3e87------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0af5b0f9c21</guid>
            <dc:creator><![CDATA[Sharayu Sanjay Yeole]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 21:24:08 GMT</pubDate>
            <atom:updated>2025-07-21T21:24:08.600Z</atom:updated>
            <content:encoded><![CDATA[<p>Go to Website : start.spring.io</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXBLlygZ6TIO8eBMyK_Z2A.png" /></figure><p>Click on “Generate”</p><p>Zip file will get download, extract it</p><p>Open intellij IDEA</p><p>File menu -&gt; Open -&gt; select extracted folder -&gt; Project will get open in Intellij IDEA</p><p>Open MySQL Workbench</p><p>create database in your connection</p><p>MySQL Query for Database creation : create database StudentManagement Application</p><p>Go inside application.properties</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSsIVY-bkEdcIYwgT1fwRg.png" /></figure><p>Type this code to connect with database</p><p>Create Student class inside model package as per belwo image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*mj9vIllgKhXwIlFDP-gpBQ.png" /></figure><p>Type code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*a6QNoiznlg2bWgFDrF_CaQ.png" /></figure><p>We are using annotation @ Entity on class Student, It means Student table will created in your database after succussfully running the application</p><p>@ Id annotation making variable id as Primary key in this databse</p><p>@ column(name=”colunm name”) : for each data variables (id, name, Lastname, email) seperate column will get created in your table Student, if you want to give different names, you can give them using @ Column annotation</p><p><strong>Generate Getter and Setter methods for all variables</strong></p><p><strong>Generate toString method for all of them</strong></p><p>Create interface StudentRepo inside package StudentRepo as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*SNeuL2fvXzzAOZ7-YutvWg.png" /></figure><p>Type code as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v9OuDG87MZcZScF6u2dJvg.png" /></figure><p><strong>In JpaRepository&lt;model_class_name, Data_type_of_primarykey&gt;</strong></p><p>Create class StudentController in package Controller</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*t3iHDWK1_n3cYps5UoQABg.png" /></figure><p>Type code as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*mLC1MjlzQehRo5v6oO-GSg.png" /></figure><p><strong>Purpose of @ RestController</strong></p><p>It combines two annotations : @ Controller + @ ResponseBody</p><p>@ Controller : tells Spring this class handles HTTP requests.</p><p>@ ResponseBody: tells spring to convert returned java object directly into JSON/XML (based on client request) instead of rendering a view (like Thymeleaf or JSP)</p><p><strong>By using RestController</strong></p><ol><li>This class will handle HTTP requests related to Students</li><li>All methods like getAllStudent(), getSingleStudent(), etc will return data(like JSON) directly in the HTTP response body.</li><li>You dont need to annotate each method with @ ResponseBody seperately</li></ol><p><strong>Without RestController</strong></p><ol><li>Spring would look for a view (HTML page) to render.</li><li>You will need to add @ ResponseBody to each method to return JSON manually.</li></ol><p><strong>Purpose of @ Autowired</strong></p><p>It automatically wires (injects) the required dependencies by type from the spring container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*aJ1BHypnJjJ8hmxN57Jc4w.png" /></figure><p>This tells spring : “Find a bean of type StudentRepo and inject it here.”</p><p>So, Spring will look for a class that implements studentRepo (a Spring Data JPA interface), create its object, and inject it automatically into the repo variable.</p><p><strong>Without @ Autowired, you’d have to manually create objects like:</strong></p><p>StudentRepo repo = new StudentRepoImpl();</p><ul><li>Spring scans for components (@Component, @Service, @Repository, etc.) and keeps them in the <strong>Spring Application Context</strong>.</li><li>When it sees @Autowired, it searches for a <strong>matching bean by type</strong> and <strong>injects</strong> it.</li></ul><p><strong>The StudentRepo interface is a spring Data JPA repository.</strong> It doesn’t have any method implementation because spring automatically provides the implementation at runtime.</p><p>The @ Autowired StudentRepo repo; tells spring that inject the auto-generated implementation of StudentRepo here, so we can use its built-in database methods like <strong>save(), findAll(), FindById()</strong>, etc</p><p>Getting List of all student</p><p>type this on your browser — localhost:8080/Student</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*urkp1efU8D0CmlB9dv2TGw.png" /></figure><p>Get Student by ID</p><p>Type this on your browser — localhost:8080/Student/1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*uNWwnm5L_3hjoahQ-l1YEQ.png" /></figure><p>create student(use Postman)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*w1H7qSfiOQT6tRtjwcsvTg.png" /></figure><p>Delete Student(use Postman)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*8pyCDVHoJPv7hYKFlp6Hsg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0af5b0f9c21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You must read these Multithreading question before java interview]]></title>
            <link>https://medium.com/@sharayuyeole38/you-must-read-these-multithreading-question-before-java-interview-b707da6205b7?source=rss-b6b4c0ac3e87------2</link>
            <guid isPermaLink="false">https://medium.com/p/b707da6205b7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Sharayu Sanjay Yeole]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 19:04:24 GMT</pubDate>
            <atom:updated>2025-03-13T19:04:24.538Z</atom:updated>
            <content:encoded><![CDATA[<h3>Core Multithreading</h3><ol><li><strong>What is multithreading? How is it different from multiprocessing?</strong></li></ol><ul><li><strong>Multithreading</strong> is a process of executing multiple threads concurrently to maximize CPU utilization.</li><li><strong>Multiprocessing</strong> involves running multiple processes, each with its own memory space.</li><li>Difference: Threads share memory, while processes have isolated memory.</li></ul><p><strong>2. What is a thread? How is it different from a process?</strong></p><ul><li>A <strong>thread</strong> is the smallest unit of execution within a process.</li><li>A <strong>process</strong> can have multiple threads sharing its resources (heap, method area).</li><li>Threads are faster to create and switch between, while processes are heavier and need more resources.</li></ul><p><strong>3. How do you create a thread in Java?</strong></p><p><strong>Method 1: Extending the Thread class</strong></p><pre>// Thread creation by extending Thread class<br>class FileDownloader extends Thread {<br>    private String fileName;<br><br>    public FileDownloader(String fileName) {<br>        this.fileName = fileName;<br>    }<br><br>    public void run() {<br>        System.out.println(&quot;Downloading: &quot; + fileName);<br>        // Simulate time taken to download<br>        try {<br>            Thread.sleep(3000); // 3 seconds<br>        } catch (InterruptedException e) {<br>            System.out.println(&quot;Download interrupted for &quot; + fileName);<br>        }<br>        System.out.println(&quot;Download completed: &quot; + fileName);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        FileDownloader file1 = new FileDownloader(&quot;file1.pdf&quot;);<br>        FileDownloader file2 = new FileDownloader(&quot;file2.pdf&quot;);<br><br>        file1.start(); // starts thread for file1<br>        file2.start(); // starts thread for file2<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>start() method starts a new thread that calls the run() method.</li><li>Both file downloads happen <strong>concurrently</strong>.</li></ul><p>Method 2: Implementing the Runnable interface</p><pre>// Thread creation by implementing Runnable<br>class FileDownloader implements Runnable {<br>    private String fileName;<br><br>    public FileDownloader(String fileName) {<br>        this.fileName = fileName;<br>    }<br><br>    public void run() {<br>        System.out.println(&quot;Downloading: &quot; + fileName);<br>        try {<br>            Thread.sleep(3000); // simulate download time<br>        } catch (InterruptedException e) {<br>            System.out.println(&quot;Download interrupted for &quot; + fileName);<br>        }<br>        System.out.println(&quot;Download completed: &quot; + fileName);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Thread file1 = new Thread(new FileDownloader(&quot;file1.pdf&quot;));<br>        Thread file2 = new Thread(new FileDownloader(&quot;file2.pdf&quot;));<br><br>        file1.start();<br>        file2.start();<br>    }<br>}</pre><p><strong>4. Why prefer Runnable over Thread?</strong></p><ul><li>More flexible: Java supports <strong>single inheritance</strong> — so extending Thread means you can’t extend other classes.</li><li>Runnable lets you use thread pooling (important for large-scale apps).</li></ul><p>5. <strong>Which one should you use?</strong></p><ul><li><strong>Use Runnable</strong> if you want <strong>better design</strong> and <strong>scalability</strong> (ideal for most apps).</li><li><strong>Extend Thread</strong> only if you want to <strong>override thread methods</strong> like start(), interrupt(), etc.</li></ul><p><strong>6. Difference between extending threads and Runnable interface?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*Ku-DYFYy35C4Dr0CaSa6ig.png" /></figure><p><strong>7. What is the life cycle of a thread? Can you explain each state?</strong></p><p>A thread in Java goes through <strong>5 states</strong>:</p><ol><li><strong>New</strong>:</li></ol><ul><li>A thread is created but not yet started.</li><li><strong>Real life:</strong> A food delivery driver is <strong>hired</strong> but hasn’t received any orders yet.</li></ul><pre>Thread t = new Thread(() -&gt; System.out.println(&quot;Delivering order&quot;));</pre><p><strong>2. Runnable</strong>:</p><ul><li>The thread is ready to run but waiting for CPU time.</li><li><strong>Real life:</strong> The driver is <strong>waiting at the restaurant</strong> for the food to be ready.</li></ul><pre>t.start(); // moves to Runnable state</pre><p><strong>3. Running</strong>:</p><ul><li>The thread is executing its task.</li><li><strong>Real life:</strong> The driver is <strong>delivering the order</strong>.</li></ul><pre>public void run() {<br>    System.out.println(&quot;Order is being delivered...&quot;);<br>}</pre><p><strong>4. Blocked/Waiting</strong>:</p><ul><li>The thread is paused waiting for a resource or a signal.</li><li><strong>Real life:</strong> The driver is <strong>stuck in traffic</strong> waiting for the road to clear.</li></ul><pre>synchronized(obj) {<br>    obj.wait(); // Thread moves to waiting state<br>}</pre><p><strong>5. Terminated (Dead)</strong>:</p><ul><li>The thread finishes its task or is stopped.</li><li><strong>Real life:</strong> The driver <strong>delivers the order</strong> and goes home.</li></ul><pre>System.out.println(&quot;Order delivered, thread exits.&quot;);</pre><p><strong>Thread Life Cycle Example:</strong></p><pre>class DeliveryDriver extends Thread {<br>    public void run() {<br>        System.out.println(getName() + &quot; is picking up the order (RUNNABLE)&quot;);<br>        try {<br>            Thread.sleep(2000); // Simulate time to deliver<br>        } catch (InterruptedException e) {<br>            System.out.println(getName() + &quot; was interrupted.&quot;);<br>        }<br>        System.out.println(getName() + &quot; has delivered the order (TERMINATED)&quot;);<br>    }<br>}<br><br>public class DeliveryApp {<br>    public static void main(String[] args) {<br>        DeliveryDriver driver1 = new DeliveryDriver();<br>        DeliveryDriver driver2 = new DeliveryDriver();<br><br>        System.out.println(driver1.getName() + &quot; is created (NEW)&quot;);<br>        System.out.println(driver2.getName() + &quot; is created (NEW)&quot;);<br><br>        driver1.start();<br>        driver2.start();<br>    }<br>}</pre><p><strong>Output</strong></p><pre>Thread-0 is created (NEW)<br>Thread-1 is created (NEW)<br>Thread-0 is picking up the order (RUNNABLE)<br>Thread-1 is picking up the order (RUNNABLE)<br>Thread-0 has delivered the order (TERMINATED)<br>Thread-1 has delivered the order (TERMINATED)</pre><h3><strong>Thread Control and Management</strong></h3><ol><li><strong>What are Daemon Threads? How do you create one?</strong></li></ol><ul><li><strong>Daemon threads</strong> are <strong>background threads</strong> that run continuously to perform supporting tasks, like <strong>garbage collection</strong> or <strong>monitoring</strong>.</li><li>They automatically terminate when <strong>all user threads finish</strong>.</li></ul><p><strong>Real-life example: Auto-save feature in a text editor</strong></p><p>Imagine working in a text editor. While you’re typing (user thread), the auto-save feature (daemon thread) runs silently in the background. When you close the editor, the auto-save stops.</p><pre>public class AutoSave extends Thread {<br>    public void run() {<br>        while (true) {<br>            System.out.println(&quot;Auto-saving document...&quot;);<br>            try {<br>                Thread.sleep(3000); // auto-save every 3 seconds<br>            } catch (InterruptedException e) {<br>                System.out.println(&quot;Auto-save interrupted&quot;);<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        AutoSave autoSave = new AutoSave();<br>        autoSave.setDaemon(true); // set thread as daemon<br>        autoSave.start();<br><br>        try {<br>            Thread.sleep(5000); // simulate user working for 5 seconds<br>        } catch (InterruptedException e) {<br>            System.out.println(&quot;Main thread interrupted&quot;);<br>        }<br>        System.out.println(&quot;User exits the editor, daemon thread stops.&quot;);<br>    }<br>}</pre><pre>Auto-saving document...<br>Auto-saving document...<br>User exits the editor, daemon thread stops.</pre><p>2<strong>. How do you stop a thread in Java? Why is the </strong><strong>stop() method deprecated?</strong></p><p><strong>Stopping a thread:</strong></p><ul><li>The stop() method is <strong>deprecated</strong> because it:</li><li><strong>Forcibly terminates</strong> a thread without proper cleanup.</li><li>Can cause <strong>data corruption</strong> if a thread is stopped while updating shared resources.</li></ul><p><strong>Better alternatives:</strong></p><ul><li>Use <strong>flags</strong> or <strong>interrupts</strong> to stop threads safely.</li></ul><p><strong>Real-life example: Download cancellation button</strong></p><p>Imagine downloading a file, and you press “Cancel”. The download thread should stop gracefully, saving any partial data.</p><p>Code example:</p><pre>public class FileDownload extends Thread {<br>    private volatile boolean exit = false;<br><br>    public void run() {<br>        while (!exit) {<br>            System.out.println(&quot;Downloading file...&quot;);<br>            try {<br>                Thread.sleep(1000);<br>            } catch (InterruptedException e) {<br>                System.out.println(&quot;Download interrupted.&quot;);<br>            }<br>        }<br>        System.out.println(&quot;Download stopped.&quot;);<br>    }<br><br>    public void stopDownloading() {<br>        exit = true; // signal to stop the thread<br>    }<br><br>    public static void main(String[] args) throws InterruptedException {<br>        FileDownload download = new FileDownload();<br>        download.start();<br>        Thread.sleep(3000); // let download run for 3 seconds<br>        download.stopDownloading();<br>    }<br>}</pre><p><strong>3. What is thread priority? How does it affect thread scheduling?</strong></p><p>Definition:</p><ul><li>Thread priority determines the <strong>importance of a thread</strong> — but <strong>doesn’t guarantee</strong> execution order.</li><li>Priorities range from:</li><li><strong>MIN_PRIORITY (1)</strong></li><li><strong>NORM_PRIORITY (5)</strong></li><li><strong>MAX_PRIORITY (10)</strong></li></ul><h4>Real-life example: Emergency calls vs. regular calls</h4><p>In a call center:</p><ul><li>Emergency<strong> </strong>calls <strong>= </strong>High<strong>-</strong>priority<strong> </strong>threads</li><li>Regular<strong> </strong>calls <strong>= </strong>Low<strong>-</strong>priority thread</li></ul><p><strong>Code example</strong></p><pre>public class CallCenter extends Thread {<br>    public CallCenter(String name) {<br>        super(name);<br>    }<br><br>    public void run() {<br>        System.out.println(getName() + &quot; is being processed.&quot;);<br>    }<br><br>    public static void main(String[] args) {<br>        CallCenter regularCall = new CallCenter(&quot;Regular Call&quot;);<br>        CallCenter emergencyCall = new CallCenter(&quot;Emergency Call&quot;);<br><br>        regularCall.setPriority(Thread.MIN_PRIORITY);<br>        emergencyCall.setPriority(Thread.MAX_PRIORITY);<br><br>        regularCall.start();<br>        emergencyCall.start();<br>    }<br>}</pre><p><strong>4. What is the </strong><strong>join() method in threads? How does it work?</strong></p><p><strong>Definition</strong>: The join() method makes the current thread <strong>wait</strong> until another thread <strong>finishes execution</strong>.</p><p><strong>Real-life example: Ordering food before watching a movie : </strong>Imagine you’re waiting for your pizza (thread) to be delivered before you start watching a movie (main thread). You won’t start the movie until the pizza thread completes.</p><p><strong>Code example:</strong></p><pre>public class PizzaDelivery extends Thread {<br>    public void run() {<br>        System.out.println(&quot;Pizza delivery started...&quot;);<br>        try {<br>            Thread.sleep(3000); // simulate delivery time<br>        } catch (InterruptedException e) {<br>            System.out.println(&quot;Delivery interrupted.&quot;);<br>        }<br>        System.out.println(&quot;Pizza delivered!&quot;);<br>    }<br><br>    public static void main(String[] args) throws InterruptedException {<br>        PizzaDelivery pizza = new PizzaDelivery();<br>        pizza.start();<br><br>        System.out.println(&quot;Waiting for pizza...&quot;);<br>        pizza.join(); // wait for pizza to be delivered<br>        System.out.println(&quot;Pizza received. Let&#39;s watch the movie!&quot;);<br>    }<br>}</pre><p><strong>output</strong></p><pre>Pizza delivery started...<br>Waiting for pizza...<br>Pizza delivered!<br>Pizza received. Let&#39;s watch the movie!</pre><p><strong>5. What happens if you call </strong><strong>start() twice on the same thread?</strong></p><h4>Explanation:</h4><ul><li>Calling start() twice on the same thread causes a <strong>runtime exception</strong>:<br> <strong>IllegalThreadStateException</strong>.</li><li>A thread can be started <strong>only once</strong>. After it finishes execution (TERMINATED state), it <strong>cannot be restarted</strong>.</li></ul><p><strong>Real-life example: Restarting a burned-out light bulb</strong></p><p>Once a light bulb burns out (thread ends), flipping the switch again won’t light it back up.</p><p><strong>Code example:</strong></p><pre>public class TestThread extends Thread {<br>    public void run() {<br>        System.out.println(&quot;Thread is running...&quot;);<br>    }<br><br>    public static void main(String[] args) {<br>        TestThread t = new TestThread();<br>        t.start(); // valid start<br>        t.start(); // throws IllegalThreadStateException<br>    }<br>}</pre><p><strong>Output</strong></p><pre>Thread is running...<br>Exception in thread &quot;main&quot; java.lang.IllegalThreadStateException</pre><h3><strong>Concurrency and Synchronization:</strong></h3><h4><strong>1. What is Synchronization in Java? Why is it needed?</strong></h4><h4>Definition:</h4><ul><li><strong>Synchronization</strong> in Java is a way to control the <strong>access of multiple threads to shared resources</strong>.</li><li>It ensures that <strong>only one thread</strong> can access a critical section (like a method or block of code) at a time.</li></ul><h4>Why needed?</h4><ul><li>Without synchronization, <strong>race conditions</strong> can occur, leading to <strong>inconsistent data</strong>.</li><li>Used when multiple threads modify <strong>shared data or resources</strong> — like updating a bank balance.</li></ul><h4>Real-life example: ATM withdrawal</h4><p>Imagine <strong>two people (threads)</strong> using the <strong>same ATM (shared resource)</strong> to withdraw money at the same time.<br>Without synchronization, both might withdraw $100 from an account with only $100, causing a negative balance.</p><p><strong>Code example</strong></p><pre>class BankAccount {<br>    private int balance = 100;<br><br>    public synchronized void withdraw(String name, int amount) {<br>        if (balance &gt;= amount) {<br>            System.out.println(name + &quot; is withdrawing &quot; + amount);<br>            balance -= amount;<br>            System.out.println(name + &quot; completed withdrawal. Remaining balance: &quot; + balance);<br>        } else {<br>            System.out.println(name + &quot; cannot withdraw. Insufficient funds.&quot;);<br>        }<br>    }<br>}<br><br>public class ATM {<br>    public static void main(String[] args) {<br>        BankAccount account = new BankAccount();<br><br>        Thread person1 = new Thread(() -&gt; account.withdraw(&quot;Person1&quot;, 100));<br>        Thread person2 = new Thread(() -&gt; account.withdraw(&quot;Person2&quot;, 100));<br><br>        person1.start();<br>        person2.start();<br>    }<br>}</pre><pre>Person1 is withdrawing 100<br>Person1 completed withdrawal. Remaining balance: 0<br>Person2 cannot withdraw. Insufficient funds.<br><br></pre><p><strong>2. What is the concept of a Monitor in Java?</strong></p><h4>Definition:</h4><ul><li>A <strong>monitor</strong> is a <strong>mechanism used by Java to achieve synchronization</strong>.</li><li>Every object in Java has an <strong>implicit lock</strong> (or <strong>monitor lock</strong>).</li><li>When a thread enters a <strong>synchronized block/method</strong>, it <strong>acquires the lock</strong>.</li><li>Other threads <strong>wait</strong> until the lock is <strong>released</strong>.</li></ul><p><strong>Real-life example: Bathroom queue</strong></p><p>Think of a <strong>single-occupancy bathroom</strong> (shared resource).</p><ul><li><strong>Lock acquired</strong>: Someone enters and locks the door.</li><li><strong>Waiting threads</strong>: Others wait outside.</li><li><strong>Lock released</strong>: Person exits, next one enters.</li></ul><p><strong>Code:</strong></p><pre>class Bathroom {<br>    public synchronized void useBathroom(String name) {<br>        System.out.println(name + &quot; entered the bathroom.&quot;);<br>        try {<br>            Thread.sleep(2000); // using bathroom<br>        } catch (InterruptedException e) {<br>            System.out.println(&quot;Interrupted&quot;);<br>        }<br>        System.out.println(name + &quot; left the bathroom.&quot;);<br>    }<br>}</pre><p><strong>3. Synchronized Method vs Synchronized Block</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*L30eih_nbsoAEDYG9iqpJQ.png" /></figure><h4>Real-life example: Movie ticket booking</h4><ul><li><strong>Synchronized method</strong>: Book entire tickets section — slower, less flexible.</li><li><strong>Synchronized block</strong>: Only lock the <strong>seat selection</strong> — faster, more precise.</li></ul><p><strong>Code example:</strong></p><pre>class MovieTheater {<br>    private int availableSeats = 3;<br><br>    // Synchronized Method<br>    public synchronized void bookSeat(String name) {<br>        if (availableSeats &gt; 0) {<br>            System.out.println(name + &quot; booked a seat.&quot;);<br>            availableSeats--;<br>        } else {<br>            System.out.println(&quot;No seats available.&quot;);<br>        }<br>    }<br><br>    // Synchronized Block<br>    public void bookWithBlock(String name) {<br>        synchronized (this) { // only lock this section<br>            if (availableSeats &gt; 0) {<br>                System.out.println(name + &quot; booked a seat.&quot;);<br>                availableSeats--;<br>            } else {<br>                System.out.println(&quot;No seats available.&quot;);<br>            }<br>        }<br>    }<br>}</pre><p><strong>4. What is a Deadlock? How can you prevent it?</strong></p><ul><li><strong>Deadlock</strong> happens when <strong>two or more threads are waiting for each other’s locks</strong>, causing a <strong>permanent block</strong>.</li></ul><p><strong>Real-life example: Two people swapping pens</strong></p><ul><li>Person A has pen 1, waiting for pen 2.</li><li>Person B has pen 2, waiting for pen 1.<br> Both wait forever.</li></ul><p><strong>Code example:</strong></p><pre>class Resource {<br>    void methodA(Resource resource) {<br>        synchronized (this) {<br>            System.out.println(Thread.currentThread().getName() + &quot; locked methodA.&quot;);<br>            synchronized (resource) {<br>                System.out.println(Thread.currentThread().getName() + &quot; trying to lock methodB.&quot;);<br>            }<br>        }<br>    }<br><br>    void methodB(Resource resource) {<br>        synchronized (this) {<br>            System.out.println(Thread.currentThread().getName() + &quot; locked methodB.&quot;);<br>            synchronized (resource) {<br>                System.out.println(Thread.currentThread().getName() + &quot; trying to lock methodA.&quot;);<br>            }<br>        }<br>    }<br>}</pre><p><strong>Deadlock Prevention</strong>:</p><ul><li>Use <strong>timeout locks</strong> (tryLock() in ReentrantLock).</li><li><strong>Lock ordering</strong> — always lock resources in a defined order.</li><li>Use <strong>deadlock detection algorithms</strong>.</li></ul><p><strong>5. What is a Race Condition? How do you handle it?</strong></p><p>A <strong>race condition</strong> occurs when <strong>two or more threads access shared data simultaneously</strong> and the <strong>result depends on the order of execution</strong>.</p><p><strong>Real-life example: Online voting system</strong></p><ul><li><strong>Thread 1</strong>: Reads votes count (100), adds 1 → 101.</li><li><strong>Thread 2</strong>: Reads votes count (100), adds 1 → 101.<br> The correct count should be <strong>102</strong>, but <strong>both write 101</strong>.</li></ul><pre>class VotingMachine {<br>    private int votes = 0;<br><br>    public void vote() {<br>        votes++;<br>    }<br><br>    public int getVotes() {<br>        return votes;<br>    }<br>}<br><br>public class RaceCondition {<br>    public static void main(String[] args) throws InterruptedException {<br>        VotingMachine machine = new VotingMachine();<br><br>        Thread t1 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 1000; i++) machine.vote();<br>        });<br><br>        Thread t2 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 1000; i++) machine.vote();<br>        });<br><br>        t1.start();<br>        t2.start();<br><br>        t1.join();<br>        t2.join();<br><br>        System.out.println(&quot;Total votes: &quot; + machine.getVotes());<br>    }<br>}<br></pre><p><strong>6. What is Reentrant Locking in Java?</strong></p><p><strong>Reentrant locks</strong> allow the same thread to <strong>acquire a lock multiple times</strong> without blocking itself.</p><p><strong>Real-life example: Recursive function</strong></p><p>A person (thread) unlocks a <strong>nested drawer</strong> (lock 1) and a <strong>sub-drawer inside</strong> (lock 2) — they can access both without being locked out.</p><p><strong>Code example:</strong></p><pre>import java.util.concurrent.locks.ReentrantLock;<br><br>public class ReentrantLockExample {<br>    private final ReentrantLock lock = new ReentrantLock();<br><br>    public void outerMethod() {<br>        lock.lock();<br>        System.out.println(&quot;Outer method&quot;);<br>        innerMethod();<br>        lock.unlock();<br>    }<br><br>    public void innerMethod() {<br>        lock.lock();<br>        System.out.println(&quot;Inner method&quot;);<br>        lock.unlock();<br>    }<br><br>    public static void main(String[] args) {<br>        ReentrantLockExample example = new ReentrantLockExample();<br>        example.outerMethod();<br>    }<br>}</pre><h3><strong>Executors and Thread Pools</strong></h3><ol><li><strong>What is the Executor framework in Java? Why use it instead of manually creating threads?</strong></li></ol><ul><li>The <strong>Executor framework</strong> (introduced in Java 5) is part of the java.util.concurrent package.</li><li>It <strong>decouples thread management</strong> from task execution — providing a <strong>high-level API</strong> for managing and controlling thread pools.</li></ul><p><strong>Why use it?</strong></p><ul><li><strong>Manual thread creation</strong> (new Thread()) is error-prone and inefficient for complex apps.</li><li><strong>Executor framework</strong> solves key issues:</li><li><strong>Thread reuse</strong> — avoids costly thread creation/destruction.</li><li><strong>Task queuing</strong> — lets you queue tasks if threads are busy.</li><li><strong>Scalable pools</strong> — allows dynamic thread scaling (like CachedThreadPool).</li><li><strong>Graceful shutdown</strong> — provides proper thread lifecycle management.</li></ul><p><strong>Real-life example: Restaurant kitchen</strong></p><ul><li><strong>Without Executor</strong>: Every order (task) gets its own chef (thread) — chaotic and inefficient.</li><li><strong>With Executor</strong>: There’s a <strong>fixed number of chefs (thread pool)</strong> who handle incoming orders <strong>one by one</strong> — smooth and organized.</li></ul><p><strong>Code example (without Executor)</strong></p><pre>public class WithoutExecutor {<br>    public static void main(String[] args) {<br>        Runnable task = () -&gt; System.out.println(&quot;Task executed by &quot; + Thread.currentThread().getName());<br>        <br>        // Creating threads manually<br>        new Thread(task).start();<br>        new Thread(task).start();<br>    }<br>}</pre><p><strong>Using Executor:</strong></p><pre>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br><br>public class WithExecutor {<br>    public static void main(String[] args) {<br>        ExecutorService executor = Executors.newFixedThreadPool(2);<br>        <br>        Runnable task = () -&gt; System.out.println(&quot;Task executed by &quot; + Thread.currentThread().getName());<br>        <br>        executor.submit(task);<br>        executor.submit(task);<br>        <br>        executor.shutdown(); // Properly close the executor<br>    }<br>}</pre><p><strong>2. Difference between Executor, ExecutorService, and ThreadPoolExecutor</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*qEY2cU0qFzIhM6fbY6M72A.png" /></figure><p><strong>Real-life example: Delivery service</strong></p><ul><li><strong>Executor</strong>: Basic courier — sends parcels (tasks) immediately.</li><li><strong>ExecutorService</strong>: Post office — manages couriers (threads), queues parcels (tasks), and closes at the end of the day.</li><li><strong>ThreadPoolExecutor</strong>: Custom delivery company — decides <strong>number of couriers</strong>, max workload, and how to handle overflow.</li></ul><p><strong>3. How does CachedThreadPool work? When would you use it?</strong></p><p><strong>Definition:</strong></p><ul><li><strong>CachedThreadPool</strong> (Executors.newCachedThreadPool()) creates a <strong>dynamic pool</strong>:</li><li>Creates <strong>new threads as needed</strong>.</li><li><strong>Reuses</strong> old threads if available (like a recycling bin).</li><li><strong>Removes idle threads</strong> after 60 seconds.</li></ul><p><strong>When to use:</strong></p><ul><li>For <strong>short-lived tasks</strong> or apps with <strong>unpredictable workloads</strong>.</li><li>Example: A <strong>web server</strong> handling <strong>spike traffic</strong>.</li></ul><p><strong>Real-life example: Food delivery drivers</strong></p><ul><li>If <strong>5 orders come</strong> → 5 drivers are <strong>hired instantly</strong>.</li><li>If <strong>1 order comes</strong> later → a <strong>previous driver (thread)</strong> is <strong>reused</strong>.</li><li>If <strong>no orders for 1 hour</strong> → drivers go <strong>home (destroyed threads)</strong>.</li></ul><p><strong>Code</strong></p><pre>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br><br>public class CachedThreadPoolExample {<br>    public static void main(String[] args) {<br>        ExecutorService executor = Executors.newCachedThreadPool();<br><br>        for (int i = 1; i &lt;= 5; i++) {<br>            final int taskId = i;<br>            executor.execute(() -&gt; System.out.println(&quot;Task &quot; + taskId + &quot; executed by &quot; + Thread.currentThread().getName()));<br>        }<br>        <br>        executor.shutdown();<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Task 1 executed by pool-1-thread-1<br>Task 2 executed by pool-1-thread-2<br>Task 3 executed by pool-1-thread-3<br>Task 4 executed by pool-1-thread-4<br>Task 5 executed by pool-1-thread-5</pre><p><strong>4. What is FixedThreadPool? How does it differ from SingleThreadExecutor?</strong></p><p><strong>FixedThreadPool:</strong></p><ul><li>Creates a <strong>fixed number of threads</strong>.</li><li><strong>Extra tasks</strong> wait in a <strong>queue</strong> until a thread is <strong>free</strong>.</li><li>Use for <strong>CPU-bound tasks</strong> or <strong>constant workloads</strong>.</li></ul><pre>ExecutorService fixedPool = Executors.newFixedThreadPool(3);</pre><p><strong>SingleThreadExecutor:</strong></p><ul><li>Uses <strong>1 thread only</strong> — executes tasks <strong>sequentially</strong> (one by one).</li><li>All tasks are <strong>queued</strong>.</li><li>Ensures <strong>thread-safety</strong> (useful for <strong>logging or file I/O</strong>).</li></ul><p><strong>Real-life example: Bank counters</strong></p><ul><li><strong>FixedThreadPool (3)</strong>: <strong>3 counters</strong> at a bank.</li><li><strong>Customers (tasks)</strong> wait if all counters are <strong>busy</strong>.</li><li><strong>SingleThreadExecutor</strong>: <strong>1 counter</strong> — all customers form a <strong>single queue</strong>.</li></ul><p><strong>5. Difference between submit() and execute() methods in ExecutorService</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*henX80m92ltWv9NQgvF_VQ.png" /></figure><p><strong>Real-life example: Pizza orders</strong></p><ul><li><strong>execute()</strong>: <strong>Throw the order to the chef</strong> — doesn’t care about the result.</li><li><strong>submit()</strong>: <strong>Track the order</strong> — gives you a <strong>receipt (Future)</strong> to check progress or errors.</li></ul><p><strong>Code example:</strong></p><pre>import java.util.concurrent.*;<br><br>public class SubmitVsExecute {<br>    public static void main(String[] args) {<br>        ExecutorService executor = Executors.newFixedThreadPool(2);<br><br>        // Using execute() — fire and forget<br>        executor.execute(() -&gt; System.out.println(&quot;Executed by: &quot; + Thread.currentThread().getName()));<br><br>        // Using submit() — returns a Future<br>        Future&lt;String&gt; future = executor.submit(() -&gt; {<br>            return &quot;Task result from: &quot; + Thread.currentThread().getName();<br>        });<br><br>        try {<br>            System.out.println(future.get()); // waits for task completion<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>        }<br><br>        executor.shutdown();<br>    }<br>}</pre><pre>Executed by: pool-1-thread-1  <br>Task result from: pool-1-thread-2</pre><h4>1. Difference between Runnable and Callable</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*RieperGhD5xlx4FRBFyqVw.png" /></figure><h4>Real-life example: Pizza order</h4><ul><li><strong>Runnable</strong>: Tells the chef to <strong>bake the pizza</strong> — doesn’t care about the <strong>pizza’s result</strong>.</li><li><strong>Callable</strong>: Asks the chef to <strong>bake the pizza and tell me when it’s done</strong> (returning the <strong>pizza object</strong>).</li></ul><p><strong>Code example</strong></p><pre>import java.util.concurrent.*;<br><br>public class RunnableVsCallable {<br>    public static void main(String[] args) throws Exception {<br>        // Runnable task — doesn&#39;t return a value<br>        Runnable runnableTask = () -&gt; System.out.println(&quot;Running a task...&quot;);<br><br>        // Callable task — returns a value<br>        Callable&lt;String&gt; callableTask = () -&gt; &quot;Task completed!&quot;;<br><br>        // Execute with ExecutorService<br>        ExecutorService executor = Executors.newFixedThreadPool(2);<br><br>        executor.submit(runnableTask); // just runs<br>        Future&lt;String&gt; future = executor.submit(callableTask); // returns result<br><br>        System.out.println(&quot;Callable result: &quot; + future.get()); // waits for result<br><br>        executor.shutdown();<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Running a task...<br>Callable result: Task completed!</pre><h4>2. How do you get a result back from a thread in Java?</h4><ul><li>Use <strong>Callable</strong> to return a result.</li><li>To <strong>retrieve the result</strong>, use <strong>Future</strong>.</li></ul><h4>3. What is a Future in Java?</h4><ul><li>A <strong>Future</strong> is an interface that represents the <strong>result of an asynchronous computation</strong>.</li><li>It lets you:</li><li><strong>Check if the task is done</strong> (isDone())</li><li><strong>Cancel the task</strong> (cancel())</li><li><strong>Retrieve the result</strong> (get() — blocking call)</li></ul><h4>Real-life example: Food delivery app</h4><ul><li>You <strong>place an order</strong> (submit task).</li><li>You <strong>track the order status</strong> (is it done or not? — isDone()).</li><li>You can <strong>cancel the order</strong> (cancel()).</li><li>You <strong>wait for food</strong> (get() — blocking call).</li></ul><p><strong>code</strong></p><pre>import java.util.concurrent.*;<br><br>public class FutureExample {<br>    public static void main(String[] args) throws Exception {<br>        ExecutorService executor = Executors.newSingleThreadExecutor();<br><br>        Callable&lt;String&gt; task = () -&gt; {<br>            Thread.sleep(2000); // Simulate time-consuming task<br>            return &quot;Pizza is ready!&quot;;<br>        };<br><br>        Future&lt;String&gt; future = executor.submit(task);<br><br>        System.out.println(&quot;Order placed...&quot;);<br><br>        // Check if task is done<br>        while (!future.isDone()) {<br>            System.out.println(&quot;Waiting for pizza...&quot;);<br>            Thread.sleep(500);<br>        }<br><br>        // Get result (blocking)<br>        System.out.println(&quot;Result: &quot; + future.get());<br><br>        executor.shutdown();<br>    }<br>}</pre><p><strong>Output</strong></p><pre>Order placed...<br>Waiting for pizza...<br>Waiting for pizza...<br>Result: Pizza is ready!</pre><p><strong>4. Difference between </strong><strong>isDone() and </strong><strong>get() in Future</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*rdqgjin0sSXJJBvKwWTTYg.png" /></figure><h4>Real-life example: Movie ticket booking</h4><ul><li><strong>isDone()</strong>: Check if <strong>tickets are confirmed</strong> (doesn’t block you from doing other things).</li><li><strong>get()</strong>: <strong>Wait at the counter</strong> till <strong>tickets are printed</strong>.</li></ul><h4>5. CompletableFuture and its benefits</h4><p>Introduced in <strong>Java 8</strong>, <strong>CompletableFuture</strong> is an enhanced version of <strong>Future</strong> that allows:</p><ul><li><strong>Chaining tasks</strong> (thenApply(), thenAccept())</li><li><strong>Combining multiple tasks</strong> (thenCombine(), allOf())</li><li><strong>Handling errors</strong> (exceptionally())</li><li><strong>Non-blocking async calls</strong> (supplyAsync())</li></ul><h4>Real-life example: Ordering food and drinks together</h4><ul><li><strong>Future</strong>: Orders <strong>food</strong> — waits till it’s <strong>done</strong>.</li><li><strong>CompletableFuture</strong>: Orders <strong>food and drinks simultaneously</strong> — combines both <strong>results asynchronously</strong>.</li></ul><p><strong>Code:</strong></p><pre>import java.util.concurrent.*;<br><br>public class CompletableFutureExample {<br>    public static void main(String[] args) throws Exception {<br>        // Run async task<br>        CompletableFuture&lt;String&gt; pizza = CompletableFuture.supplyAsync(() -&gt; {<br>            sleep(2000);<br>            return &quot;Pizza is ready!&quot;;<br>        });<br><br>        CompletableFuture&lt;String&gt; drink = CompletableFuture.supplyAsync(() -&gt; {<br>            sleep(1000);<br>            return &quot;Drink is ready!&quot;;<br>        });<br><br>        // Combine both tasks<br>        CompletableFuture&lt;String&gt; combined = pizza.thenCombine(drink, (p, d) -&gt; p + &quot; and &quot; + d);<br><br>        // Non-blocking way to handle result<br>        combined.thenAccept(System.out::println);<br><br>        sleep(3000); // to allow async tasks to complete<br>    }<br><br>    private static void sleep(int ms) {<br>        try { Thread.sleep(ms); } catch (InterruptedException e) { e.printStackTrace(); }<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Pizza is ready! and Drink is ready!</pre><p><strong>Benefits of CompletableFuture:</strong></p><ul><li><strong>Non-blocking</strong> — Runs async tasks <strong>without blocking the main thread</strong>.</li><li><strong>Chaining</strong> — Combine multiple tasks <strong>sequentially</strong> or <strong>in parallel</strong>.</li><li><strong>Error handling</strong> — Handle errors <strong>gracefully</strong> using exceptionally().</li><li><strong>Combining tasks</strong> — Merge results of multiple async operations.</li></ul><h3><strong>Advanced Topics (Semaphore, CountDownLatch, etc.)</strong></h3><h4>1. What is a Semaphore in Java? How does it work?</h4><p>A <strong>Semaphore</strong> is a thread synchronization construct that:</p><ul><li>Controls <strong>access to a resource</strong> by multiple threads.</li><li>Maintains a set number of <strong>permits</strong> — only threads with a permit can proceed.</li></ul><h4>Real-life example: Parking lot</h4><ul><li>A parking lot with <strong>5 spots</strong> allows a max of <strong>5 cars</strong> at a time.</li><li>If <strong>all spots are full</strong>, cars <strong>wait</strong>.</li><li>When a car <strong>leaves</strong>, a <strong>spot (permit) is released</strong>.</li></ul><p>Code</p><pre>import java.util.concurrent.*;<br><br>public class SemaphoreExample {<br>    public static void main(String[] args) {<br>        Semaphore parkingLot = new Semaphore(3); // 3 parking spots<br><br>        for (int i = 1; i &lt;= 6; i++) {<br>            final int car = i;<br>            new Thread(() -&gt; {<br>                try {<br>                    System.out.println(&quot;Car &quot; + car + &quot; trying to park...&quot;);<br>                    parkingLot.acquire(); // get a permit<br>                    System.out.println(&quot;Car &quot; + car + &quot; parked.&quot;);<br>                    Thread.sleep(2000); // simulate time parked<br>                    System.out.println(&quot;Car &quot; + car + &quot; leaving...&quot;);<br>                    parkingLot.release(); // release the permit<br>                } catch (InterruptedException e) {<br>                    e.printStackTrace();<br>                }<br>            }).start();<br>        }<br>    }<br>}</pre><p>Output</p><pre>Car 1 trying to park...<br>Car 1 parked.<br>Car 2 trying to park...<br>Car 2 parked.<br>Car 3 trying to park...<br>Car 3 parked.<br>Car 4 trying to park...<br>Car 5 trying to park...<br>Car 6 trying to park...<br>Car 1 leaving...<br>Car 4 parked.</pre><p><strong>2. Binary vs Counting Semaphore</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*EXhD7hO4GZP0BM6ySWN0Ng.png" /></figure><h4>3. What is CountDownLatch in Java?</h4><ul><li><strong>CountDownLatch</strong> is used to <strong>block a thread until other threads complete</strong> a given task.</li><li>You initialize it with a count (number of events to wait for).</li><li>Threads call <strong>countDown()</strong> when a task is done, and <strong>await()</strong> makes the main thread wait until the count reaches <strong>zero</strong>.</li></ul><h4>Real-life example: Race start</h4><ul><li>A race doesn’t start until <strong>all runners are ready</strong>.</li><li>The <strong>starter gun (main thread)</strong> waits for <strong>all runners</strong> to call <strong>ready (countDown)</strong> before <strong>firing the gun (proceeding)</strong>.</li></ul><p>Code</p><pre>import java.util.concurrent.*;<br><br>public class CountDownLatchExample {<br>    public static void main(String[] args) throws InterruptedException {<br>        CountDownLatch latch = new CountDownLatch(3); // 3 runners<br><br>        for (int i = 1; i &lt;= 3; i++) {<br>            final int runner = i;<br>            new Thread(() -&gt; {<br>                System.out.println(&quot;Runner &quot; + runner + &quot; ready...&quot;);<br>                latch.countDown(); // reduce count<br>            }).start();<br>        }<br><br>        latch.await(); // wait until count reaches 0<br>        System.out.println(&quot;All runners ready. Race starts!&quot;);<br>    }<br>}</pre><p>Output</p><pre>Runner 1 ready...<br>Runner 2 ready...<br>Runner 3 ready...<br>All runners ready. Race starts!</pre><h4>4. CountDownLatch vs Semaphore</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*lTbjbgVS6fYMS6jFu2mtOA.png" /></figure><h4>5. What is CyclicBarrier in Java?</h4><ul><li><strong>CyclicBarrier</strong> makes a set of threads <strong>wait for each other</strong> to reach a common point.</li><li>Unlike <strong>CountDownLatch</strong>, it can be <strong>reset</strong> and <strong>reused</strong>.</li></ul><h4>Real-life example: Group trekking</h4><ul><li>A trekking team has 5 members.</li><li>They must all <strong>wait at a checkpoint</strong> until <strong>everyone arrives</strong> before <strong>proceeding</strong>.</li><li>If <strong>one round is over</strong>, they <strong>reuse the barrier</strong> for the <strong>next checkpoint</strong>.</li></ul><p>Code</p><pre>import java.util.concurrent.*;<br><br>public class CyclicBarrierExample {<br>    public static void main(String[] args) {<br>        CyclicBarrier barrier = new CyclicBarrier(3, () -&gt; <br>            System.out.println(&quot;All arrived. Moving to the next checkpoint.&quot;)<br>        );<br><br>        for (int i = 1; i &lt;= 3; i++) {<br>            final int hiker = i;<br>            new Thread(() -&gt; {<br>                try {<br>                    System.out.println(&quot;Hiker &quot; + hiker + &quot; arrived.&quot;);<br>                    barrier.await(); // wait at the barrier<br>                } catch (Exception e) {<br>                    e.printStackTrace();<br>                }<br>            }).start();<br>        }<br>    }<br>}</pre><h4>6. ReentrantLock vs synchronized</h4><ul><li><strong>ReentrantLock</strong> is a more flexible and powerful alternative to the <strong>synchronized</strong> keyword.</li><li>It allows:</li><li><strong>TryLock</strong> — try acquiring the lock without blocking.</li><li><strong>Interruptible locks</strong> — cancel waiting threads.</li><li><strong>Fairness</strong> — give priority to waiting threads.</li></ul><h4>Real-life example: Library computer booking</h4><ul><li><strong>Synchronized</strong>: A computer can be <strong>booked by 1 person</strong> at a time.</li><li><strong>ReentrantLock</strong>: Allows you to:</li><li><strong>Check if a computer is free</strong> (tryLock()).</li><li><strong>Cancel the booking request</strong> if the queue is long.</li></ul><p><strong>code</strong></p><pre>import java.util.concurrent.locks.*;<br><br>public class ReentrantLockExample {<br>    private final ReentrantLock lock = new ReentrantLock();<br><br>    public void accessResource() {<br>        if (lock.tryLock()) {<br>            try {<br>                System.out.println(Thread.currentThread().getName() + &quot; accessed the resource.&quot;);<br>                Thread.sleep(1000);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            } finally {<br>                lock.unlock();<br>            }<br>        } else {<br>            System.out.println(Thread.currentThread().getName() + &quot; couldn&#39;t get the lock.&quot;);<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        ReentrantLockExample example = new ReentrantLockExample();<br><br>        for (int i = 1; i &lt;= 3; i++) {<br>            new Thread(example::accessResource).start();<br>        }<br>    }<br>}</pre><h4>7. What are ReadWriteLocks?</h4><ul><li><strong>ReadWriteLock</strong> separates <strong>read</strong> and <strong>write</strong> locks.</li><li><strong>Multiple threads can read simultaneously</strong>, but only <strong>one thread can write</strong> at a time.</li></ul><h4>Real-life example: Online Library</h4><ul><li>Many users can <strong>read</strong> the same <strong>book</strong> (read lock).</li><li>But only <strong>one librarian can update</strong> the book record (write lock).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b707da6205b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interview questions for Synchronization and Semaphore]]></title>
            <link>https://medium.com/@sharayuyeole38/interview-questions-for-synchronization-and-semaphore-377245faf8af?source=rss-b6b4c0ac3e87------2</link>
            <guid isPermaLink="false">https://medium.com/p/377245faf8af</guid>
            <dc:creator><![CDATA[Sharayu Sanjay Yeole]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 18:59:37 GMT</pubDate>
            <atom:updated>2025-03-10T18:59:37.564Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Synchronization Interview Questions — Answers</strong></h3><h4>1. What is synchronization in Java, and why is it needed?</h4><p><strong>Synchronization</strong> in Java is a mechanism that controls access to shared resources by multiple threads. It ensures that only one thread can access critical sections of code at a time, preventing <strong>race conditions</strong> and maintaining data consistency.</p><h4>2. Difference between process synchronization and thread synchronization?</h4><ul><li><strong>Process synchronization</strong>: Coordinates processes to avoid conflicts when accessing shared resources (handled by OS).</li><li><strong>Thread synchronization</strong>: Ensures threads within the same process don’t concurrently access shared data, preventing race conditions (handled via synchronized methods, locks, etc.).</li></ul><h4>3. Ways to achieve thread synchronization in Java?</h4><ul><li><strong>Synchronized methods</strong>: Locks entire methods.</li><li><strong>Synchronized blocks</strong>: Locks specific code blocks.</li><li><strong>Static synchronization</strong>: Locks class-level resources.</li><li><strong>ReentrantLock</strong>: Explicit lock from java.util.concurrent.locks.</li><li><strong>Volatile keyword</strong>: Ensures visibility of changes to variables.</li><li><strong>Atomic classes</strong>: AtomicInteger, AtomicBoolean, etc.</li></ul><h4>4. Difference between synchronized methods and synchronized blocks?</h4><ul><li><strong>Synchronized methods</strong> lock the entire method — only one thread can execute it.</li><li><strong>Synchronized blocks</strong> lock only a portion of code — allowing more fine-grained control.<br> Use synchronized blocks when you want to reduce contention by locking only the critical part of a method.</li></ul><h4>5. Can you synchronize a static method in Java?</h4><p>Yes! Static methods can be synchronized using the <strong>class-level lock</strong>.</p><pre>public synchronized static void method() {<br>    // Class-level lock<br>}</pre><p>It locks the class object (Class&lt;?&gt;), ensuring only one thread can execute <strong>any static synchronized method</strong> at a time.</p><h4>6. Limitations of synchronization in Java?</h4><ul><li><strong>Performance overhead</strong>: Can slow down execution due to thread blocking.</li><li><strong>Deadlocks</strong>: Improper locking order can cause threads to block forever.</li><li><strong>Lack of flexibility</strong>: No timeout, interruptibility, or fairness control (unlike ReentrantLock).</li></ul><h4>7. What is a race condition, and how does synchronization prevent it?</h4><p>A <strong>race condition</strong> happens when multiple threads access and modify shared data simultaneously, leading to inconsistent results.<br> <strong>Synchronization</strong> prevents this by ensuring only one thread can access critical sections of code at a time.</p><h4>9. What is a deadlock? How can you prevent it?</h4><p>A <strong>deadlock</strong> occurs when two or more threads are stuck, each waiting for a resource held by the other — leading to an infinite block.<br> <strong>Prevention strategies</strong>:</p><ul><li><strong>Lock ordering</strong>: Always acquire locks in a consistent order.</li><li><strong>TryLock</strong>: Use <strong>tryLock()</strong> to avoid waiting forever.</li><li><strong>Timeout</strong>: Set timeouts when acquiring locks.</li></ul><h4>10. Difference between volatile and synchronized?</h4><ul><li><strong>Volatile</strong>: Ensures <strong>visibility</strong> of variable changes across threads but <strong>doesn’t prevent race conditions</strong>.</li><li><strong>Synchronized</strong>: Ensures <strong>mutual exclusion</strong> (one thread at a time) and <strong>visibility</strong>.</li></ul><h3>🚦 <strong>Semaphore Interview Questions — Answers</strong></h3><h4>1. What is a semaphore?</h4><p>A <strong>semaphore</strong> is a synchronization tool that controls access to a shared resource by allowing a set number of permits. Threads must acquire a permit to proceed and release it after use.</p><h4>2. Difference between binary and counting semaphores?</h4><ul><li><strong>Binary semaphore</strong>: Allows only <strong>1 permit</strong> (like a lock). Used for mutual exclusion.</li><li><strong>Counting semaphore</strong>: Allows <strong>multiple permits</strong> — controls access for a fixed number of threads.</li></ul><h4>3. How are semaphores used for mutual exclusion?</h4><p>A <strong>binary semaphore</strong> (initialized to 1) can act as a lock:</p><pre>Semaphore semaphore = new Semaphore(1); // 1 permit<br>semaphore.acquire();  // Lock<br>// critical section<br>semaphore.release();  // Unlock</pre><p>Only one thread can enter the critical section at a time.</p><h4>4. <strong>Difference between semaphore and lock?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*soMMMgCU1z_w6YO9tg0pwQ.png" /></figure><h4>5. What are acquire() and release() methods in semaphores?</h4><ul><li><strong>acquire()</strong>: Requests a permit — blocks if none are available.</li><li><strong>release()</strong>: Returns a permit, allowing other threads to proceed.</li></ul><h4>6. Semaphore use case: Producer-Consumer problem?</h4><p>A counting semaphore can limit buffer access:</p><ul><li><strong>Empty semaphore</strong> counts available slots.</li><li><strong>Full semaphore</strong> counts filled slots.</li><li><strong>Mutex</strong> ensures mutual exclusion for buffer access.</li></ul><h4>7. What happens if a thread calls release() without acquiring a permit?</h4><p>The permit count increases, which may violate logic, leading to <strong>over-permission</strong> — allowing more threads than intended to enter critical sections.</p><h4>8. Fair vs. non-fair semaphores?</h4><ul><li><strong>Fair semaphore</strong>: Permits are given in order (FIFO).</li><li><strong>Non-fair semaphore</strong>: Threads may acquire permits out of order (default).</li></ul><h4>9. Semaphore vs. Monitor in Java?</h4><ul><li><strong>Semaphore</strong>: Controls <strong>access to resources</strong> via permits.</li><li><strong>Monitor</strong>: Implicitly used by synchronized, focusing on <strong>thread coordination</strong> with wait(), notify().</li></ul><h4>10. Can semaphores prevent deadlocks?</h4><p>Yes! <strong>TryLock</strong> or <strong>timeout-based acquire()</strong> helps avoid infinite waiting by giving threads a way to abandon locks if they can’t proceed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=377245faf8af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set of process and thread interview questions (basic)]]></title>
            <link>https://medium.com/@sharayuyeole38/set-of-process-and-thread-interview-questions-ranging-from-basic-to-advanced-levels-5f6b2ab2829a?source=rss-b6b4c0ac3e87------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f6b2ab2829a</guid>
            <category><![CDATA[process]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Sharayu Sanjay Yeole]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 17:25:29 GMT</pubDate>
            <atom:updated>2025-03-09T17:30:14.546Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>What is a process?</strong><br>A process is an executing instance of a program. It has its own memory space, data, and resources. Each process runs independently and is isolated from other processes.</li><li><strong>What is a thread?</strong><br>A thread is the smallest unit of execution within a process. Threads share the same memory space of the process but execute independently. A process can have multiple threads.</li><li><strong>Difference between a process and a thread:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*n4ptlK8MKOEGaZvalg-faw.png" /></figure><p><strong>4. How do processes communicate with each other?</strong><br>Processes use Inter-process Communication (IPC) mechanisms like:<br>• Pipes<br>• Message queues<br>• Shared memory<br>• Sockets</p><p><strong>5.</strong> 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝘀𝘁𝗮𝘁𝗲𝘀 𝗼𝗳 𝗮 𝘁𝗵𝗿𝗲𝗮𝗱?<br>• 𝗡𝗲𝘄: Created but not started.<br>• 𝗥𝘂𝗻𝗻𝗮𝗯𝗹𝗲: Eligible to run but waiting for CPU.<br>• 𝗕𝗹𝗼𝗰𝗸𝗲𝗱: Waiting to acquire a lock.<br>• 𝗪𝗮𝗶𝘁𝗶𝗻𝗴: Waiting indefinitely for another thread’s signal.<br>• 𝗧𝗶𝗺𝗲𝗱 𝗪𝗮𝗶𝘁𝗶𝗻𝗴: Waiting for a specific time.<br>• 𝗧𝗲𝗿𝗺𝗶𝗻𝗮𝘁𝗲𝗱: Thread has finished execution.</p><p><strong>7.</strong>𝗧𝗵𝗿𝗲𝗮𝗱 𝗰𝗼𝗻𝘁𝗲𝘅𝘁 𝘀𝘄𝗶𝘁𝗰𝗵𝗶𝗻𝗴 𝘃𝘀. 𝗽𝗿𝗼𝗰𝗲𝘀𝘀 𝗰𝗼𝗻𝘁𝗲𝘅𝘁 𝘀𝘄𝗶𝘁𝗰𝗵𝗶𝗻𝗴:<br>• 𝗣𝗿𝗼𝗰𝗲𝘀𝘀 𝗰𝗼𝗻𝘁𝗲𝘅𝘁 𝘀𝘄𝗶𝘁𝗰𝗵𝗶𝗻𝗴: Involves saving and loading process states, including memory maps — slower.<br>• 𝗧𝗵𝗿𝗲𝗮𝗱 𝗰𝗼𝗻𝘁𝗲𝘅𝘁 𝘀𝘄𝗶𝘁𝗰𝗵𝗶𝗻𝗴: Only saves and loads thread registers and program counters — faster.</p><p><strong>8. </strong>𝗪𝗵𝗮𝘁 𝗶𝘀 𝗺𝘂𝗹𝘁𝗶𝘁𝗵𝗿𝗲𝗮𝗱𝗶𝗻𝗴? 𝗛𝗼𝘄 𝗶𝘀 𝗶𝘁 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗳𝗿𝗼𝗺 𝗺𝘂𝗹𝘁𝗶𝘁𝗮𝘀𝗸𝗶𝗻𝗴?<br>• 𝗠𝘂𝗹𝘁𝗶𝘁𝗵𝗿𝗲𝗮𝗱𝗶𝗻𝗴: Running multiple threads in a single process, sharing the same memory.<br>• 𝗠𝘂𝗹𝘁𝗶𝘁𝗮𝘀𝗸𝗶𝗻𝗴: Running multiple processes at the same time.<br>• 𝗞𝗲𝘆 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲: Multithreading works within a process, multitasking works at the process level.</p><p>9. 𝗔𝗱𝘃𝗮𝗻𝘁𝗮𝗴𝗲𝘀 𝗮𝗻𝗱 𝗱𝗶𝘀𝗮𝗱𝘃𝗮𝗻𝘁𝗮𝗴𝗲𝘀 𝗼𝗳 𝗺𝘂𝗹𝘁𝗶𝘁𝗵𝗿𝗲𝗮𝗱𝗶𝗻𝗴:<br>• 𝗔𝗱𝘃𝗮𝗻𝘁𝗮𝗴𝗲𝘀:<br>Better CPU utilization<br>Improved app responsiveness<br>Easy resource sharing (shared memory)<br>• 𝗗𝗶𝘀𝗮𝗱𝘃𝗮𝗻𝘁𝗮𝗴𝗲𝘀:<br>Complexity (synchronization issues)<br>Risk of deadlocks<br>Difficult debugging</p><p><strong>10. Creating threads in Java:</strong><br> <strong>Two ways to create threads:</strong></p><pre>public class MyThread extends Thread {<br>    public void run() {<br>        System.out.println(&quot;Thread running&quot;);<br>    }<br>    public static void main(String[] args) {<br>        MyThread t = new MyThread();<br>        t.start();<br>    }<br>}</pre><pre>public class MyRunnable implements Runnable {<br>    public void run() {<br>        System.out.println(&quot;Thread running&quot;);<br>    }<br>    public static void main(String[] args) {<br>        Thread t = new Thread(new MyRunnable());<br>        t.start();<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*VP-TIB-ALNhAYm7IW4_ZWQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f6b2ab2829a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Programming (OOPs) interview questions — tailored for SDE roles]]></title>
            <link>https://medium.com/@sharayuyeole38/object-oriented-programming-oops-interview-questions-tailored-for-sde-roles-a44bfa169832?source=rss-b6b4c0ac3e87------2</link>
            <guid isPermaLink="false">https://medium.com/p/a44bfa169832</guid>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[oops-interview-questions]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sharayu Sanjay Yeole]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 20:18:25 GMT</pubDate>
            <atom:updated>2025-03-08T20:18:25.115Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Object-Oriented Programming (OOPs) interview questions</strong> — tailored for SDE roles</h3><p>Basic OOPs Concepts</p><ol><li><strong>What are the four pillars of OOP?</strong><br> The four pillars of OOP are:</li></ol><ul><li><strong>Encapsulation</strong>: Restricting direct access to object data and methods.</li><li><strong>Abstraction</strong>: Hiding complex implementation details and showing only the essential features.</li><li><strong>Inheritance</strong>: Allowing one class to inherit properties and methods from another.</li><li><strong>Polymorphism</strong>: Allowing methods to have multiple forms — method overloading (compile-time) and method overriding (runtime).</li></ul><p><strong>2. Explain encapsulation with an example.</strong></p><p>Encapsulation is achieved using <strong>private fields and public methods</strong>:</p><pre>public class Student {<br>    private String name;  // Encapsulated field<br><br>    public String getName() {  // Accessor method<br>        return name;<br>    }<br><br>    public void setName(String name) {  // Mutator method<br>        this.name = name;<br>    }<br>}</pre><p>The private field name cannot be accessed directly, it’s controlled through <strong>getter </strong>and <strong>setter</strong> <strong>methods</strong>.</p><p><strong>3. What is inheritance?</strong><br>Inheritance allows a class (child class) to acquire properties and methods from another class (parent class).</p><pre>class Animal {<br>    void eat() {<br>        System.out.println(&quot;This animal eats food&quot;);<br>    }<br>}<br><br>class Dog extends Animal {<br>    void bark() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>Here, Dog inherits the eat() method from Animal.</p><p><strong>4. What is polymorphism?</strong><br><strong>Polymorphism</strong> in simple words means “one thing, many forms.” In programming, it allows objects of different classes to be treated as objects of a common superclass. It mainly comes in two types:</p><ol><li><strong>Compile-time (Static) Polymorphism</strong>: Achieved using <strong>method overloading</strong> — multiple methods with the same name but different parameters.</li><li><strong>Run-time (Dynamic) Polymorphism</strong>: Achieved using <strong>method overriding</strong> — a child class provides its own implementation of a method defined in the parent class.</li></ol><p>Let’s break down <strong>polymorphism</strong> with a <strong>real-world example</strong>! 🌟</p><h3>Scenario: Payment System</h3><p>Imagine an e-commerce app where users can pay using different methods like <strong>Credit Card</strong>, <strong>Debit Card</strong>, or <strong>UPI</strong>. All these payment methods share a common action — <strong>pay()</strong> — but the way they process the payment is different.</p><p>Let’s map this to polymorphism:</p><pre>// Parent class<br>abstract class Payment {<br>    abstract void pay(double amount);<br>}<br><br>// Child classes<br>class CreditCard extends Payment {<br>    @Override<br>    void pay(double amount) {<br>        System.out.println(&quot;Paid &quot; + amount + &quot; using Credit Card.&quot;);<br>    }<br>}<br><br>class DebitCard extends Payment {<br>    @Override<br>    void pay(double amount) {<br>        System.out.println(&quot;Paid &quot; + amount + &quot; using Debit Card.&quot;);<br>    }<br>}<br><br>class UPI extends Payment {<br>    @Override<br>    void pay(double amount) {<br>        System.out.println(&quot;Paid &quot; + amount + &quot; using UPI.&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        // Polymorphism: Parent class reference points to child class objects<br>        Payment payment;<br><br>        payment = new CreditCard();<br>        payment.pay(500);<br><br>        payment = new DebitCard();<br>        payment.pay(300);<br><br>        payment = new UPI();<br>        payment.pay(200);<br>    }<br>}</pre><p>code for overloading</p><pre>class Calculator {<br>    // Overloaded methods with different parameter lists<br>    int add(int a, int b) {<br>        return a + b;<br>    }<br><br>    double add(double a, double b) {<br>        return a + b;<br>    }<br><br>    int add(int a, int b, int c) {<br>        return a + b + c;<br>    }<br>}<br><br>public class OverloadingExample {<br>    public static void main(String[] args) {<br>        Calculator calc = new Calculator();<br>        System.out.println(&quot;Sum of two integers: &quot; + calc.add(5, 10));<br>        System.out.println(&quot;Sum of two doubles: &quot; + calc.add(5.5, 10.5));<br>        System.out.println(&quot;Sum of three integers: &quot; + calc.add(5, 10, 15));<br>    }<br>}</pre><p><strong>5. What is abstraction?</strong><br> Abstraction hides implementation details and shows only the functionality:</p><ul><li><strong>Abstract classes</strong> (using abstract keyword)</li><li><strong>Interfaces</strong> (with default, static, or abstract methods)<br> Example:</li></ul><pre>abstract class Shape {<br>    abstract void draw();<br>}<br><br>class Circle extends Shape {<br>    void draw() { System.out.println(&quot;Drawing Circle&quot;); }<br>}</pre><p>🏛️ <strong>Classes and Objects</strong></p><p><strong>6. What is a class and an object?</strong></p><ul><li><strong>Class</strong>: A blueprint for creating objects (defines properties and behaviors).</li><li><strong>Object</strong>: An instance of a class.</li></ul><pre>class Car {<br>    String brand;<br>}<br>Car myCar = new Car();  // Object</pre><p><strong>7. Can a class be final?</strong><br> Yes, marking a class as final means it cannot be subclassed:</p><pre>final class Car { }<br>class ElectricCar extends Car { }  // Error!</pre><p><strong>8. What happens if you don’t create a constructor?</strong><br> Java provides a default no-argument constructor. However, if you define any constructor, the default is removed.</p><p><strong>9. Difference between constructor and method?</strong></p><ul><li><strong>Constructor</strong>: Initializes an object; same name as class; no return type.</li><li><strong>Method</strong>: Defines behavior; can have any name and return type.</li></ul><p><strong>10. What is ‘this’ keyword?</strong><br> Refers to the current object instance:</p><pre>public class Car {<br>    String brand;<br>    Car(String brand) {<br>        this.brand = brand;  // Refers to the instance variable<br>    }<br>}</pre><p>📚 <strong>Inheritance</strong></p><p><strong>11. Types of inheritance:</strong></p><ul><li><strong>Single</strong>: A → B</li><li><strong>Multilevel</strong>: A → B → C</li><li><strong>Hierarchical</strong>: A → B, A → C<br> Java doesn’t support <strong>Multiple Inheritance</strong> (A → B, C) due to ambiguity.</li></ul><p><strong>12. Why doesn’t Java support multiple inheritance?</strong><br> It prevents the <strong>Diamond problem</strong> — where a class inherits conflicting methods from two parents.</p><p>13. <strong>What is method overriding?</strong><br> Redefining a parent class method in a child class:</p><pre>class Animal {<br>    void sound() { System.out.println(&quot;Animal sound&quot;); }<br>}<br>class Dog extends Animal {<br>    @Override<br>    void sound() { System.out.println(&quot;Bark&quot;); }<br>}</pre><p><strong>14. What is super keyword?</strong><br> Refers to parent class methods or constructors:</p><pre>class Animal {<br>    void sound() { System.out.println(&quot;Animal sound&quot;); }<br>}<br>class Dog extends Animal {<br>    void display() {<br>        super.sound();  // Calls parent method<br>    }<br>}</pre><p><strong>15. Dynamic method dispatch:</strong><br> Enables runtime polymorphism by calling the overridden method based on object type:</p><pre>Animal a = new Dog();<br>a.sound();  // Calls Dog&#39;s sound method</pre><p>🌟 <strong>Abstraction and Interfaces</strong></p><p><strong>16. What is an abstract class?</strong><br> A class with abstract methods (without implementation):</p><pre>abstract class Shape {<br>    abstract void draw();<br>}</pre><p><strong>17. Abstract class vs Interface:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*ilOhgrX4U51IIq3V3lsEoQ.png" /></figure><p><strong>18. Can interface extend another interface?</strong></p><pre>interface A { void show(); }<br>interface B extends A { void display(); }</pre><p><strong>19. Default and static methods in interfaces:</strong></p><pre>interface Vehicle {<br>    default void print() { System.out.println(&quot;Vehicle&quot;); }<br>    static void stop() { System.out.println(&quot;Stopped&quot;); }<br>}</pre><p><strong>20. Why can’t we instantiate abstract classes?</strong><br> Abstract classes have incomplete methods — making it impossible to create their objects directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a44bfa169832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DSA journey with HashMap practice!]]></title>
            <link>https://medium.com/@sharayuyeole38/dsa-journey-with-hashmap-practice-defd76806c35?source=rss-b6b4c0ac3e87------2</link>
            <guid isPermaLink="false">https://medium.com/p/defd76806c35</guid>
            <dc:creator><![CDATA[Sharayu Sanjay Yeole]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 10:47:43 GMT</pubDate>
            <atom:updated>2024-10-16T10:47:43.471Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>DSA journey with HashMap practice! 🧑‍💻</strong><br>Whether you’re just getting started or looking to level up your problem-solving skills, this post focuses on practicing HashMaps, categorized into Easy, Medium, and Hard levels! 📊 Here’s your roadmap for mastering HashMaps through consistent practice! 👇</p><p>📝 <strong>Level: Easy</strong></p><ol><li>Two Sum</li><li>Contains Duplicate</li><li>Valid Anagram</li><li>Intersection of Two Arrays</li><li>First Unique Character in a String</li><li>Check If Two String Arrays are Equivalent</li><li>Group Anagrams</li><li>Find All Duplicates in an Array</li></ol><p>📝 <strong>Level: Medium</strong></p><ol><li>Subarray Sum Equals K</li><li>Group Anagrams</li><li>Longest Substring Without Repeating Characters</li><li>Find the Longest Subarray with Equal 0s and 1s</li><li>Top K Frequent Elements</li><li>Longest Consecutive Sequence</li><li>Smallest Window in a String Containing All Characters of Another String</li><li>Kth Distinct String in an Array</li></ol><p>📝 <strong>Level: Hard</strong></p><ol><li>Longest Substring with At Most K Distinct Characters</li><li>Subarrays with K Different Integers</li><li>Max Points on a Line</li><li>Concatenated Words</li><li>Evaluate Division</li><li>Word Break II</li><li>Palindrome Pairs</li><li>Employee Importance</li></ol><p><strong>Important for Interview</strong></p><ol><li>Two Sum</li><li>Group Anagrams</li><li>Longest Substring Without Repeating Characters</li><li>Top K Frequent Elements</li><li>First Unique Character in a String</li><li>Check if Two Strings are Anagrams</li><li>Find All Anagrams in a String</li><li>Subarray Sum Equals K</li><li>Longest Consecutive Sequence</li><li>Employee Importance</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=defd76806c35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DSA Topic : Sorting Algorithms(Preparation) ]]></title>
            <link>https://medium.com/@sharayuyeole38/dsa-topic-sorting-algorithms-preparation-56fd4f63f3ee?source=rss-b6b4c0ac3e87------2</link>
            <guid isPermaLink="false">https://medium.com/p/56fd4f63f3ee</guid>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Sharayu Sanjay Yeole]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 10:32:21 GMT</pubDate>
            <atom:updated>2024-10-16T10:32:21.688Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>DSA Topic : Sorting Algorithms(Preparation) 📝</strong></p><p>👉 Sorting algorithms are crucial for optimizing the efficiency of many programs. Here’s a quick overview, along with links to the most important sorting algorithms you should know when preparing for coding interviews or DSA:</p><p><strong>1. Bubble Sort</strong> <a href="https://shorturl.at/apTVU">https://shorturl.at/apTVU</a> <br> -Description: Repeatedly swaps adjacent elements if they are in the wrong order.<br> -Time Complexity: O(n²) (not efficient for large datasets)<br> -Use case: Small datasets or for educational purposes.</p><p><strong>2. Selection Sort</strong> <a href="https://shorturl.at/737Rs">https://shorturl.at/737Rs</a> <br> -Description: Repeatedly selects the smallest element from the unsorted part and swaps it with the first unsorted element.<br> -Time Complexity: O(n²)<br> -Use case: Simple, but not efficient for large datasets.</p><p><strong>3. Insertion Sort</strong> <a href="https://shorturl.at/7v8JJ">https://shorturl.at/7v8JJ</a> <br> -Description: Builds a sorted array one element at a time by inserting elements into their correct position.<br> -Time Complexity: O(n²), but O(n) for nearly sorted arrays.<br> -Use case: Efficient for small or nearly sorted datasets.</p><p><strong>4. Merge Sort</strong> <a href="https://shorturl.at/V48q6">https://shorturl.at/V48q6</a> <br> -Description: Divides the array into two halves, recursively sorts them, and then merges them back together.<br> -Time Complexity: O(n log n)<br> -Use case: Stable sort, efficient for large datasets.</p><p><strong>5. Quick Sort</strong> <a href="https://shorturl.at/NLQpB">https://shorturl.at/NLQpB</a> <br> -Description: Picks a pivot, partitions the array around the pivot, and recursively sorts the partitions.<br> -Time Complexity: O(n log n) on average, O(n²) in the worst case.<br> -Use case: Fastest comparison-based sort for large datasets, but unstable.</p><p><strong>6. Heap Sort</strong> <a href="https://shorturl.at/5SGL4">https://shorturl.at/5SGL4</a> <br> -Description: Converts the array into a binary heap and then extracts the maximum (or minimum) element one by one.<br> -Time Complexity: O(n log n)<br> -Use case: Efficient, but not stable. Great for priority queues.</p><p><strong>7. Counting Sort</strong> <a href="https://shorturl.at/xw5A4">https://shorturl.at/xw5A4</a><br> -Description: Counts the occurrences of each element and uses this information to place elements in their correct position.<br> -Time Complexity: O(n + k) (where k is the range of input values)<br> -Use case: Non-comparison sort, suitable when the range of numbers is not significantly larger than the number of elements.</p><p><strong>8. Radix Sort</strong> <a href="https://shorturl.at/9gy6n">https://shorturl.at/9gy6n</a> <br> -Description: Sorts numbers digit by digit using a stable sort like Counting Sort for each digit.<br> -Time Complexity: O(nk), where k is the number of digits.<br> -Use case: Efficient for numbers or strings, non-comparison sort.</p><p><strong>9. Bucket Sort</strong> <a href="https://shorturl.at/vWbfn">https://shorturl.at/vWbfn</a> <br> -Description: Distributes elements into buckets, sorts them individually, and then concatenates the results.<br> -Time Complexity: O(n + k), where k is the number of buckets.<br> -Use case: Useful for uniformly distributed data over a range.</p><p>💡 <strong>Key Takeaways:</strong><br> -Comparison-based sorts: Bubble, Selection, Insertion, Merge, Quick, and Heap Sort.<br> -Non-comparison sorts: Counting, Radix, and Bucket Sort — highly efficient for specific cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56fd4f63f3ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>