<?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 Parag Kaldate on Medium]]></title>
        <description><![CDATA[Stories by Parag Kaldate on Medium]]></description>
        <link>https://medium.com/@paragkaldate?source=rss-20850bddca0f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*alV7eu5xd_S8jsfiqhvFcg.png</url>
            <title>Stories by Parag Kaldate on Medium</title>
            <link>https://medium.com/@paragkaldate?source=rss-20850bddca0f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:25:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paragkaldate/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[Object-Oriented Design Patterns]]></title>
            <link>https://medium.com/@paragkaldate/object-oriented-design-patterns-7d29f15d86d7?source=rss-20850bddca0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d29f15d86d7</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Parag Kaldate]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 23:15:34 GMT</pubDate>
            <atom:updated>2025-02-10T23:15:34.608Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Object-Oriented Design (OOD) patterns are the blueprints for building scalable and maintainable software. But let’s be honest — learning them can sometimes feel overwhelming. So, let’s take a fun and interactive approach! We’ll start with real-life analogies, dig into technical details with coding snippets, and finally explore practical use cases in Low-Level Design (LLD).</p><p>By the end of this article, you’ll not only understand design patterns but also instinctively recognize when and where to use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0eR-BkjJ5vS2KU2ek3UtdQ.png" /><figcaption>Some important patterns that are covered in this article</figcaption></figure><h3>1. Creational Design Patterns</h3><p>Creational patterns deal with object creation mechanisms, reducing dependencies and improving flexibility.</p><h4>1.1 Singleton Pattern — “The One and Only”</h4><blockquote>Fun Analogy:</blockquote><p>Imagine a government issuing only one passport per citizen. No matter how many times you apply, you always get the same one!</p><blockquote>Technical Deep Dive:</blockquote><p>Singleton ensures that only one instance of a class exists throughout the program.</p><pre>public class Singleton {<br>    private static Singleton instance;<br>    private Singleton() {}<br>    public static Singleton getInstance() {<br>        if (instance == null) {<br>            instance = new Singleton();<br>        }<br>        return instance;<br>    }<br>}</pre><blockquote>Use Cases:</blockquote><ul><li>Database connections</li><li>Logger utility</li><li>Thread pools</li></ul><h4>1.2 Factory Pattern — “The Factory Worker”</h4><blockquote>Fun Analogy:</blockquote><p>A car factory produces different types of cars (SUV, Sedan, Hatchback) but you don’t need to know the internal details of how they’re made.</p><blockquote>Technical Deep Dive:</blockquote><p>Factory pattern provides a way to create objects without specifying the exact class.</p><pre>interface Car {<br>    void assemble();<br>}<br>class Sedan implements Car {<br>    public void assemble() {<br>        System.out.println(&quot;Sedan Assembled&quot;);<br>    }<br>}<br>class SUV implements Car {<br>    public void assemble() {<br>        System.out.println(&quot;SUV Assembled&quot;);<br>    }<br>}<br>class CarFactory {<br>    public static Car getCar(String type) {<br>        if (type.equals(&quot;SUV&quot;)) return new SUV();<br>        else return new Sedan();<br>    }<br>}</pre><blockquote>Use Cases:</blockquote><ul><li>UI component creation (buttons, dropdowns)</li><li>Database connection factories</li><li>Notification services</li></ul><h4>1.3 Abstract Factory Pattern — “Factory of Factories”</h4><blockquote>Fun Analogy:</blockquote><p>Imagine a furniture store that specializes in both <strong>Modern</strong> and <strong>Vintage</strong> styles. Instead of picking individual pieces, you choose a factory that exclusively produces modern or vintage furniture. The store ensures that all items (chairs, tables, sofas) match the selected style.</p><blockquote>Technical Deep Dive:</blockquote><p>The <strong>Abstract Factory Pattern</strong> is a factory that creates other factories. It helps produce families of related objects without specifying their concrete classes.</p><blockquote>Key Concept:</blockquote><ul><li>A <strong>super factory</strong> that creates other factories.</li><li>Each factory creates a group of related products.</li></ul><blockquote>Example: GUI Theme Factory</blockquote><p>Let’s say we are developing a <strong>cross-platform UI library</strong> that supports both <strong>Windows and Mac</strong> themes. Instead of writing separate code for each, we use an <strong>Abstract Factory</strong> to manage theme consistency.</p><pre>// Step 1: Define abstract product families<br>interface Button {<br>    void paint();<br>}<br>interface Checkbox {<br>    void render();<br>}<br>// Step 2: Concrete products for Windows<br>class WindowsButton implements Button {<br>    public void paint() { System.out.println(&quot;Rendering Windows-style Button&quot;); }<br>}<br>class WindowsCheckbox implements Checkbox {<br>    public void render() { System.out.println(&quot;Rendering Windows-style Checkbox&quot;); }<br>}<br>// Step 3: Concrete products for Mac<br>class MacButton implements Button {<br>    public void paint() { System.out.println(&quot;Rendering Mac-style Button&quot;); }<br>}<br>class MacCheckbox implements Checkbox {<br>    public void render() { System.out.println(&quot;Rendering Mac-style Checkbox&quot;); }<br>}<br>// Step 4: Abstract Factory<br>interface GUIFactory {<br>    Button createButton();<br>    Checkbox createCheckbox();<br>}<br>// Step 5: Concrete factories<br>class WindowsFactory implements GUIFactory {<br>    public Button createButton() { return new WindowsButton(); }<br>    public Checkbox createCheckbox() { return new WindowsCheckbox(); }<br>}<br>class MacFactory implements GUIFactory {<br>    public Button createButton() { return new MacButton(); }<br>    public Checkbox createCheckbox() { return new MacCheckbox(); }<br>}<br>// Step 6: Client code<br>class Application {<br>    private Button button;<br>    private Checkbox checkbox;<br>    public Application(GUIFactory factory) {<br>        this.button = factory.createButton();<br>        this.checkbox = factory.createCheckbox();<br>    }<br>    public void renderUI() {<br>        button.paint();<br>        checkbox.render();<br>    }<br>}<br>// Step 7: Demo<br>public class AbstractFactoryDemo {<br>    public static void main(String[] args) {<br>        GUIFactory factory;<br>        // Client chooses the OS type at runtime<br>        String os = &quot;Mac&quot;; // Change to &quot;Windows&quot; to test WindowsFactory<br>        if (os.equalsIgnoreCase(&quot;Windows&quot;)) {<br>            factory = new WindowsFactory();<br>        } else {<br>            factory = new MacFactory();<br>        }<br>        Application app = new Application(factory);<br>        app.renderUI();<br>    }<br>}</pre><blockquote>Use Cases:</blockquote><ul><li><strong>GUI libraries</strong> (Windows/Mac/Linux themes)</li><li><strong>Database connection factories</strong> (SQL vs. NoSQL)</li><li><strong>Cross-platform game engines</strong> (DirectX vs. OpenGL)</li></ul><h4>1.4 Builder Pattern — “The Custom Order”</h4><blockquote>Fun Analogy:</blockquote><p>Think of ordering a pizza — you choose toppings, crust type, and size before it’s baked.</p><blockquote>Technical Deep Dive:</blockquote><p>Builder pattern helps construct complex objects step by step.</p><pre>class Pizza {<br>    private String size;<br>    private boolean cheese;<br>    private boolean pepperoni;<br><br>    private Pizza(PizzaBuilder builder) {<br>        this.size = builder.size;<br>        this.cheese = builder.cheese;<br>        this.pepperoni = builder.pepperoni;<br>    }<br>    static class PizzaBuilder {<br>        private String size;<br>        private boolean cheese;<br>        private boolean pepperoni;<br>        public PizzaBuilder(String size) {<br>            this.size = size;<br>        }<br>        public PizzaBuilder addCheese() { this.cheese = true; return this; }<br>        public PizzaBuilder addPepperoni() { this.pepperoni = true; return this; }<br>        public Pizza build() { return new Pizza(this); }<br>    }<br>}</pre><blockquote>Use Cases:</blockquote><ul><li>Object creation with many optional parameters</li><li>Configurable game character creation</li></ul><h3>2. Structural Design Patterns</h3><p>Structural patterns define how objects are composed to form larger structures.</p><h4>2.1 Adapter Pattern — “The Universal Plug”</h4><blockquote>Fun Analogy:</blockquote><p>Think of a travel adapter that lets your charger work in different countries.</p><blockquote>Technical Deep Dive:</blockquote><p>Adapter pattern allows classes with incompatible interfaces to work together.</p><pre>interface MediaPlayer {<br>    void play(String fileName);<br>}<br>class MP3Player implements MediaPlayer {<br>    public void play(String fileName) {<br>        System.out.println(&quot;Playing MP3: &quot; + fileName);<br>    }<br>}<br>class MediaAdapter implements MediaPlayer {<br>    AdvancedMediaPlayer advancedPlayer;<br>    public MediaAdapter(AdvancedMediaPlayer player) {<br>        this.advancedPlayer = player;<br>    }<br>    public void play(String fileName) {<br>        advancedPlayer.playAdvanced(fileName);<br>    }<br>}</pre><blockquote>Use Cases:</blockquote><ul><li>Converting data formats (XML to JSON)</li><li>Third-party API integration</li></ul><h4>2.2 Decorator Pattern — “The Customizable Coffee”</h4><blockquote>Fun Analogy:</blockquote><p>Imagine ordering a <strong>basic coffee</strong> at a café. If you want <strong>milk, sugar, or caramel</strong>, you don’t need a completely new coffee type. Instead, these are <strong>add-ons (decorators)</strong> that enhance the existing coffee without modifying its core essence.</p><blockquote>Technical Deep Dive:</blockquote><p>The <strong>Decorator Pattern</strong> allows us to dynamically add functionalities to objects <strong>without modifying their base class</strong>.</p><blockquote>Example: Coffee Customization</blockquote><p>Let’s design a coffee shop system where customers can customize their coffee using the <strong>Decorator Pattern</strong>.</p><pre>// Step 1: Define the base component<br>interface Coffee {<br>    String getDescription();<br>    double cost();<br>}<br>// Step 2: Concrete Component (Basic Coffee)<br>class BasicCoffee implements Coffee {<br>    public String getDescription() { return &quot;Plain Coffee&quot;; }<br>    public double cost() { return 5.0; } // Base cost<br>}<br>// Step 3: Abstract Decorator<br>abstract class CoffeeDecorator implements Coffee {<br>    protected Coffee coffee;<br>    public CoffeeDecorator(Coffee coffee) {<br>        this.coffee = coffee;<br>    }<br>    public String getDescription() {<br>        return coffee.getDescription();<br>    }<br>    public double cost() {<br>        return coffee.cost();<br>    }<br>}<br>// Step 4: Concrete Decorators (Add-ons)<br>class Milk extends CoffeeDecorator {<br>    public Milk(Coffee coffee) { super(coffee); }<br>    public String getDescription() { return coffee.getDescription() + &quot;, Milk&quot;; }<br>    public double cost() { return coffee.cost() + 1.5; } // Extra cost<br>}<br>class Sugar extends CoffeeDecorator {<br>    public Sugar(Coffee coffee) { super(coffee); }<br>    public String getDescription() { return coffee.getDescription() + &quot;, Sugar&quot;; }<br>    public double cost() { return coffee.cost() + 0.5; }<br>}<br>// Step 5: Client Code<br>public class DecoratorDemo {<br>    public static void main(String[] args) {<br>        Coffee coffee = new BasicCoffee();<br>        System.out.println(coffee.getDescription() + &quot; -&gt; $&quot; + coffee.cost());<br>        coffee = new Milk(coffee);<br>        System.out.println(coffee.getDescription() + &quot; -&gt; $&quot; + coffee.cost());<br>        coffee = new Sugar(coffee);<br>        System.out.println(coffee.getDescription() + &quot; -&gt; $&quot; + coffee.cost());<br>    }<br>}</pre><blockquote>Use Cases:</blockquote><ul><li><strong>Adding functionalities dynamically</strong> (UI components, Text formatting)</li><li><strong>File streams</strong> (Adding encryption, compression)</li><li><strong>Game character power-ups</strong> (Adding armor, speed boosts)</li></ul><h4>2.3 Facade Pattern — “The Universal Remote”</h4><blockquote>Fun Analogy:</blockquote><p>Think of a <strong>universal remote control</strong> that lets you operate a TV, sound system, and streaming device <strong>with a single button press</strong>. Instead of dealing with multiple complex controls, the remote provides a <strong>simplified interface</strong>.</p><blockquote>Technical Deep Dive:</blockquote><p>The <strong>Facade Pattern</strong> provides a <strong>simple, unified interface</strong> to a <strong>complex subsystem</strong>, making it easier to use.</p><blockquote>Example: Home Theater System</blockquote><p>Imagine controlling multiple devices (TV, Speakers, Streaming Service) with a single command.</p><pre>// Step 1: Subsystem Components (Complex System)<br>class TV {<br>    void turnOn() { System.out.println(&quot;TV turned ON&quot;); }<br>    void turnOff() { System.out.println(&quot;TV turned OFF&quot;); }<br>}<br>class SoundSystem {<br>    void setVolume(int level) { System.out.println(&quot;Volume set to &quot; + level); }<br>}<br>class StreamingService {<br>    void playMovie(String movie) { System.out.println(&quot;Playing movie: &quot; + movie); }<br>}<br>// Step 2: Facade Class (Simplified Interface)<br>class HomeTheaterFacade {<br>    private TV tv;<br>    private SoundSystem sound;<br>    private StreamingService streaming;<br>    public HomeTheaterFacade(TV tv, SoundSystem sound, StreamingService streaming) {<br>        this.tv = tv;<br>        this.sound = sound;<br>        this.streaming = streaming;<br>    }<br>    public void watchMovie(String movie) {<br>        System.out.println(&quot;Preparing to watch a movie...&quot;);<br>        tv.turnOn();<br>        sound.setVolume(10);<br>        streaming.playMovie(movie);<br>    }<br>    public void endMovie() {<br>        System.out.println(&quot;Shutting down...&quot;);<br>        tv.turnOff();<br>    }<br>}<br>// Step 3: Client Code<br>public class FacadeDemo {<br>    public static void main(String[] args) {<br>        TV tv = new TV();<br>        SoundSystem sound = new SoundSystem();<br>        StreamingService streaming = new StreamingService();<br>        HomeTheaterFacade homeTheater = new HomeTheaterFacade(tv, sound, streaming);<br>        homeTheater.watchMovie(&quot;Inception&quot;);<br>        homeTheater.endMovie();<br>    }<br>}</pre><blockquote>Use Cases:</blockquote><ul><li><strong>Simplifying complex APIs</strong> (Database access, System configurations)</li><li><strong>Media streaming services</strong> (Netflix, Spotify)</li><li><strong>Microservices</strong> (Providing a unified API for multiple services)</li></ul><h4>2.4 Proxy Pattern — “The Security Guard”</h4><blockquote>Fun Analogy:</blockquote><p>Imagine a <strong>VIP club</strong> where <strong>not everyone can enter directly</strong>. A <strong>security guard (proxy)</strong> verifies if a person has a valid VIP pass before granting access to the main club.</p><blockquote>Technical Deep Dive:</blockquote><p>The <strong>Proxy Pattern</strong> acts as a placeholder to <strong>control access</strong> to another object. It’s commonly used for:</p><ul><li><strong>Security</strong> (Restricting unauthorized access)</li><li><strong>Lazy loading</strong> (Delaying object creation until needed)</li><li><strong>Logging &amp; Monitoring</strong> (Tracking object interactions)</li></ul><blockquote>Example: Secure Internet Access</blockquote><p>Let’s implement a <strong>proxy for internet access</strong> that <strong>blocks certain websites</strong>.</p><pre>// Step 1: Define an interface<br>interface Internet {<br>    void connectTo(String serverHost);<br>}<br>// Step 2: Real Subject (Actual Internet Connection)<br>class RealInternet implements Internet {<br>    public void connectTo(String serverHost) {<br>        System.out.println(&quot;Connecting to &quot; + serverHost);<br>    }<br>}<br>// Step 3: Proxy Class (Restricted Access)<br>class ProxyInternet implements Internet {<br>    private RealInternet realInternet = new RealInternet();<br>    private static List&lt;String&gt; bannedSites = new ArrayList&lt;&gt;();<br>    static {<br>        bannedSites.add(&quot;blockedsite.com&quot;);<br>        bannedSites.add(&quot;malicious.com&quot;);<br>    }<br>    public void connectTo(String serverHost) {<br>        if (bannedSites.contains(serverHost.toLowerCase())) {<br>            System.out.println(&quot;Access Denied: &quot; + serverHost);<br>            return;<br>        }<br>        realInternet.connectTo(serverHost);<br>    }<br>}<br>// Step 4: Client Code<br>public class ProxyDemo {<br>    public static void main(String[] args) {<br>        Internet internet = new ProxyInternet();<br>        internet.connectTo(&quot;google.com&quot;);<br>        internet.connectTo(&quot;blockedsite.com&quot;);<br>    }<br>}</pre><blockquote>Use Cases:</blockquote><ul><li><strong>Security proxies</strong> (Access control, Firewall)</li><li><strong>Lazy initialization</strong> (Creating heavy objects on demand)</li><li><strong>Logging and monitoring</strong> (Tracking API requests, Database queries)</li></ul><h3>3. Behavioral Design Patterns</h3><p>Behavioral patterns help manage object interactions and responsibilities.</p><h4>3.1 Observer Pattern — “The Social Media Notification”</h4><blockquote>Fun Analogy:</blockquote><p>When you follow someone on Instagram, you get notified of their posts. That’s Observer Pattern in action!</p><blockquote>Technical Deep Dive:</blockquote><p>Observer pattern lets multiple objects (subscribers) listen to and react to events from a subject (publisher).</p><pre>interface Observer {<br>    void update(String message);<br>}<br>class User implements Observer {<br>    private String name;<br>    public User(String name) { this.name = name; }<br>    public void update(String message) {<br>        System.out.println(name + &quot; received: &quot; + message);<br>    }<br>}<br>class SocialMediaPlatform {<br>    private List&lt;Observer&gt; users = new ArrayList&lt;&gt;();<br>    public void follow(Observer user) { users.add(user); }<br>    public void notifyUsers(String message) {<br>        for (Observer user : users) {<br>            user.update(message);<br>        }<br>    }<br>}</pre><blockquote>Use Cases:</blockquote><ul><li>Event-driven systems</li><li>Real-time notifications (Stock updates, News alerts)</li></ul><h4>3.2 Chain of Responsibility Pattern — “The Customer Support System”</h4><blockquote>Fun Analogy:</blockquote><p>Imagine a <strong>customer support system</strong> where user complaints pass through <strong>multiple levels</strong>:</p><ul><li><strong>Level 1:</strong> Chatbot tries to resolve basic queries.</li><li><strong>Level 2:</strong> A human support agent handles complex issues.</li><li><strong>Level 3:</strong> A manager steps in for critical problems.</li></ul><p>Each request is <strong>passed along the chain</strong> until it finds the right handler.</p><blockquote>Technical Deep Dive:</blockquote><p>The <strong>Chain of Responsibility Pattern</strong> allows multiple objects to <strong>process a request sequentially</strong>, passing it along a chain until it’s handled.</p><p>Example: Logging System with Different Levels</p><p>Let’s implement a <strong>logging system</strong> where:</p><ul><li><strong>INFO logs</strong> are handled by the console.</li><li><strong>DEBUG logs</strong> go to a file.</li><li><strong>ERROR logs</strong> are sent to an external monitoring service.</li></ul><pre>// Step 1: Create an Enum for Log Levels<br>enum LogLevel {<br>    INFO, DEBUG, ERROR<br>}<br>// Step 2: Define the Handler Interface<br>abstract class Logger {<br>    protected Logger nextLogger;<br>    public void setNextLogger(Logger nextLogger) {<br>        this.nextLogger = nextLogger;<br>    }<br>    public void logMessage(LogLevel level, String message) {<br>        if (canHandle(level)) {<br>            writeMessage(message);<br>        } else if (nextLogger != null) {<br>            nextLogger.logMessage(level, message);<br>        }<br>    }<br>    protected abstract boolean canHandle(LogLevel level);<br>    protected abstract void writeMessage(String message);<br>}<br>// Step 3: Concrete Handlers<br>class ConsoleLogger extends Logger {<br>    protected boolean canHandle(LogLevel level) {<br>        return level == LogLevel.INFO;<br>    }<br>    protected void writeMessage(String message) {<br>        System.out.println(&quot;[INFO] &quot; + message);<br>    }<br>}<br>class FileLogger extends Logger {<br>    protected boolean canHandle(LogLevel level) {<br>        return level == LogLevel.DEBUG;<br>    }<br>    protected void writeMessage(String message) {<br>        System.out.println(&quot;[DEBUG - File] &quot; + message);<br>    }<br>}<br>class ErrorLogger extends Logger {<br>    protected boolean canHandle(LogLevel level) {<br>        return level == LogLevel.ERROR;<br>    }<br>    protected void writeMessage(String message) {<br>        System.out.println(&quot;[ERROR - Alert Sent] &quot; + message);<br>    }<br>}<br>// Step 4: Client Code<br>public class ChainOfResponsibilityDemo {<br>    public static void main(String[] args) {<br>        Logger consoleLogger = new ConsoleLogger();<br>        Logger fileLogger = new FileLogger();<br>        Logger errorLogger = new ErrorLogger();<br>        // Setting up the chain<br>        consoleLogger.setNextLogger(fileLogger);<br>        fileLogger.setNextLogger(errorLogger);<br>        // Logging messages<br>        consoleLogger.logMessage(LogLevel.INFO, &quot;This is an informational message.&quot;);<br>        consoleLogger.logMessage(LogLevel.DEBUG, &quot;Debugging application.&quot;);<br>        consoleLogger.logMessage(LogLevel.ERROR, &quot;Critical system failure!&quot;);<br>    }<br>}</pre><blockquote>Use Cases:</blockquote><ul><li><strong>Event Handling</strong> (UI event propagation)</li><li><strong>Request Validation Pipelines</strong> (Middleware in web applications)</li><li><strong>Authorization &amp; Security Filters</strong> (JWT authentication in APIs)</li></ul><h4>3.3 Strategy Pattern — “The Payment Methods”</h4><blockquote>Fun Analogy:</blockquote><p>Imagine you’re shopping online and want to pay using <strong>Credit Card, PayPal, or Cryptocurrency</strong>.<br> Each payment method has <strong>different processing logic</strong>, but the checkout process remains the same.</p><p>Technical Deep Dive:</p><p>The <strong>Strategy Pattern</strong> defines a <strong>family of algorithms</strong> and allows switching between them <strong>at runtime</strong> without modifying the client.</p><p>Example: Payment System</p><p>Let’s implement an <strong>online store payment system</strong> where users can pay using:</p><ul><li><strong>Credit Card</strong></li><li><strong>PayPal</strong></li><li><strong>Bitcoin</strong></li></ul><pre>// Step 1: Define the Strategy Interface<br>interface PaymentStrategy {<br>    void pay(int amount);<br>}<br>// Step 2: Implement Concrete Strategies<br>class CreditCardPayment implements PaymentStrategy {<br>    private String cardNumber;<br>    public CreditCardPayment(String cardNumber) {<br>        this.cardNumber = cardNumber;<br>    }<br>    public void pay(int amount) {<br>        System.out.println(&quot;Paid $&quot; + amount + &quot; using Credit Card ending with &quot; + cardNumber.substring(cardNumber.length() - 4));<br>    }<br>}<br>class PayPalPayment implements PaymentStrategy {<br>    private String email;<br>    public PayPalPayment(String email) {<br>        this.email = email;<br>    }<br>    public void pay(int amount) {<br>        System.out.println(&quot;Paid $&quot; + amount + &quot; using PayPal (Email: &quot; + email + &quot;)&quot;);<br>    }<br>}<br>class BitcoinPayment implements PaymentStrategy {<br>    private String walletAddress;<br>    public BitcoinPayment(String walletAddress) {<br>        this.walletAddress = walletAddress;<br>    }<br>    public void pay(int amount) {<br>        System.out.println(&quot;Paid $&quot; + amount + &quot; using Bitcoin (Wallet: &quot; + walletAddress + &quot;)&quot;);<br>    }<br>}<br>// Step 3: Context Class (Shopping Cart)<br>class ShoppingCart {<br>    private PaymentStrategy paymentStrategy;<br>    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {<br>        this.paymentStrategy = paymentStrategy;<br>    }<br>    public void checkout(int amount) {<br>        if (paymentStrategy == null) {<br>            throw new IllegalStateException(&quot;Payment method not selected.&quot;);<br>        }<br>        paymentStrategy.pay(amount);<br>    }<br>}<br>// Step 4: Client Code<br>public class StrategyDemo {<br>    public static void main(String[] args) {<br>        ShoppingCart cart = new ShoppingCart();<br>        // Paying with Credit Card<br>        cart.setPaymentStrategy(new CreditCardPayment(&quot;1234-5678-9012-3456&quot;));<br>        cart.checkout(100);<br>        // Paying with PayPal<br>        cart.setPaymentStrategy(new PayPalPayment(&quot;user@example.com&quot;));<br>        cart.checkout(200);<br>        // Paying with Bitcoin<br>        cart.setPaymentStrategy(new BitcoinPayment(&quot;1A2B3C4D5E6F&quot;));<br>        cart.checkout(300);<br>    }<br>}</pre><blockquote><em>Use</em><strong><em> </em></strong><em>Cases</em><strong><em>:</em></strong></blockquote><ul><li><strong>Payment processing systems</strong> (Multiple payment methods)</li><li><strong>Sorting algorithms</strong> (Bubble sort, Merge sort, Quick sort)</li><li><strong>Compression techniques</strong> (ZIP, RAR, TAR)</li><li><strong>Data parsing strategies</strong> (XML, JSON, CSV)</li></ul><h3>Conclusion</h3><p>Design patterns aren’t just theoretical concepts — they’re practical tools that improve software design and scalability. By relating them to real-world scenarios, we make them intuitive and memorable.</p><p>Now, the next time you work on an LLD problem, you’ll instantly recognize which pattern fits best!</p><p>Stay tuned for more in-depth guides. Happy coding!</p><p><strong>Note:</strong> There are many more design patterns, but these are some of the most important ones to understand and apply in real-world projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pj0fmLNLYfrYvX6dYzYNcg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d29f15d86d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Starter]]></title>
            <link>https://medium.com/@paragkaldate/spring-boot-starter-eb04a619690b?source=rss-20850bddca0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb04a619690b</guid>
            <dc:creator><![CDATA[Parag Kaldate]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 01:31:17 GMT</pubDate>
            <atom:updated>2025-02-09T01:31:17.919Z</atom:updated>
            <content:encoded><![CDATA[<p>Learning, Simplified &amp; Auto-configured!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voeXAR74vGR5wJ6muD3mrQ.jpeg" /></figure><p>Spring Boot is a powerful framework that simplifies Java development by eliminating boilerplate configurations and providing production-ready features. Whether you’re an entry-level or mid-to-senior-level Software Development Engineer (SDE), this guide will help you understand why Spring Boot is essential, how it compares to Spring, and how to use it effectively.</p><h4>Why use Spring boot?</h4><p>Spring Boot offers:</p><ul><li><strong>Stability:</strong> Built on Java, ensuring reliability.</li><li><strong>Connectivity:</strong> Seamless integration with databases, servers, and third-party APIs.</li><li><strong>Cloud-Native Capabilities:</strong> Supports microservices and distributed systems.</li><li><strong>Flexibility:</strong> Can be deployed anywhere — on-premise, cloud, or containers.</li><li><strong>Open Source:</strong> Actively maintained with a strong community.</li></ul><h4>Spring vs. Spring Boot</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8W2RGf6y5SKAH1R-sb2WVg.png" /><figcaption>Spring v/s Spring Boot</figcaption></figure><h3>What is Spring Boot and Why Do We Need It?</h3><p>Spring Boot is a module of the Spring Framework designed for rapid application development. It simplifies the development process by:</p><ul><li>Eliminating boilerplate configuration with <strong>auto-configuration</strong>.</li><li>Providing an <strong>embedded HTTP server</strong> (Tomcat, Jetty, Undertow) for running web applications.</li><li>Supporting <strong>microservices architecture</strong>.</li><li>Offering <strong>production-ready features</strong> like health checks, monitoring, and logging.</li><li>Integrating seamlessly with <strong>DevOps tools</strong> like Docker, Kubernetes, and AWS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmhmU_ZfoaBc44FstVEQWw.png" /></figure><h3>Key Features of Spring Boot</h3><h4>1. Spring Boot CLI</h4><p>The Spring Boot CLI (Command Line Interface) allows developers to quickly build and run Spring applications.</p><pre>$ spring init - dependencies=web myapp<br>$ cd myapp<br>$ ./mvnw spring-boot:run</pre><h4>2. Starter Dependencies</h4><p>Spring Boot provides pre-configured dependencies to avoid version conflicts. Example:</p><pre>&lt;dependency&gt;<br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4>3. Spring Initializr</h4><p>Spring Initializr is a web-based tool to generate Spring Boot projects. You can access it at<a href="https://start.spring.io/"> start.spring.io</a>.</p><h4>4. Auto-Configuration</h4><p>Spring Boot automatically configures beans based on dependencies in the classpath.</p><pre>@SpringBootApplication<br>public class MyApp {<br>  public static void main(String[] args) {<br>    SpringApplication.run(MyApp.class, args);<br>  }<br> }</pre><h4>5. Spring Actuator</h4><p>Spring Actuator provides endpoints for monitoring and managing applications.</p><pre>&lt;dependency&gt;<br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Enable Actuator endpoints:</p><pre>management.endpoints.web.exposure.include=health,info</pre><p>Check health:</p><pre>$ curl http://localhost:8080/actuator/health</pre><h3>Running a Spring Boot Application</h3><p>When you “Run as Java Application,” Spring Boot:</p><ul><li>Automatically launches an embedded Tomcat server.</li><li>Scans for components using @ComponentScan.</li><li>Enables auto-configuration via @EnableAutoConfiguration.</li></ul><h3>Spring Boot Starters</h3><p>A set of dependency management tools that simplify adding necessary dependencies. Examples include:</p><ul><li>spring-boot-starter-web (for web applications)</li><li>spring-boot-starter-data-jpa (for database integration)</li><li>spring-boot-starter-security (for authentication and security)</li></ul><h3>Minimum Requirements for Spring Boot</h3><ul><li><strong>Java Version</strong>: Java 8+</li><li><strong>Spring Framework</strong>: 5.1.9+</li><li><strong>Build Tools</strong>: Maven 3.3+, Gradle 4.4+</li><li><strong>Servlet Containers</strong>: Tomcat 9.0, Jetty 9.4, Undertow 2.0</li></ul><h3>Thymeleaf vs. JSP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/0*DwrhsfzLFA6d_Lki" /><figcaption>Thymeleaf vs. JSP</figcaption></figure><h4>Maven vs. Gradle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*PVHC3bZ63RWx6oxY6V73AA.png" /><figcaption>Maven VS. Gradle</figcaption></figure><h4>Maven Coordinates</h4><ul><li><strong>Group ID</strong>: Identifies organization (com.example)</li><li><strong>Artifact ID</strong>: Identifies project (myapp)</li><li><strong>Version</strong>: Defines version (1.0.0)</li></ul><h3>Spring Boot in Action: Code Examples</h3><h4>1. Creating a REST API with Spring Boot</h4><pre>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class MyController {<br>  @GetMapping(&quot;/hello&quot;)<br>  public String sayHello() {<br>    return &quot;Hello, Spring Boot!&quot;;<br>  }<br>}</pre><h4>2. Service Layer Implementation</h4><pre>@Service<br>public class UserService {<br>  public String getUser() {<br>    return &quot;John Doe&quot;;<br>  }<br>}</pre><h4>3. Repository Layer with JPA</h4><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {}</pre><h4>4. Entity Definition</h4><pre>@Entity<br>public class User {<br>  @Id @GeneratedValue(strategy = GenerationType.IDENTITY)<br>  private Long id;<br>  private String name;<br>}</pre><h3>Spring Boot Core Annotations</h3><ul><li>@SpringBootApplication = @Configuration + @ComponentScan + @EnableAutoConfiguration</li><li>@RestController = @Controller + @ResponseBody</li><li>@EnableAutoConfiguration enables Spring Boot’s automatic configurations.</li><li>@ComponentScan detects components like @Service, @Repository, @Controller.</li></ul><h3>Spring Boot Application Layers</h3><ol><li><strong>Controller Layer</strong>: Handles HTTP requests (@RestController).</li><li><strong>Service Layer</strong>: Contains business logic (@Service).</li><li><strong>Repository Layer</strong>: Manages database interactions (@Repository).</li><li><strong>Model Layer</strong>: Defines data structures.</li><li><strong>Configuration Layer</strong>: Handles application settings.</li></ol><h3>Spring Boot Bean Lifecycle</h3><ol><li><strong>Instantiation</strong>: Spring creates a bean instance.</li><li><strong>Dependency Injection</strong>: Dependencies are injected.</li><li><strong>Initialization</strong>: Custom initialization logic executes (@PostConstruct).</li><li><strong>Destruction</strong>: Cleanup logic executes (@PreDestroy).</li></ol><p>Example:</p><pre>@Component<br>public class MyBean {<br>    @PostConstruct<br>    public void init() {<br>        System.out.println(&quot;Bean initialized&quot;);<br>    }<br><br>    @PreDestroy<br>    public void destroy() {<br>        System.out.println(&quot;Bean destroyed&quot;);<br>    }<br>}</pre><h3>Spring Boot in Microservices</h3><p>Spring Boot is widely used in microservices architectures due to:</p><ul><li><strong>Lightweight nature</strong></li><li><strong>Built-in REST support</strong></li><li><strong>Cloud integration (Spring Cloud, Kubernetes)</strong></li><li><strong>Service Discovery (Eureka, Consul)</strong></li></ul><p>Example: Registering a microservice with Eureka:</p><pre>spring.application.name=user-service<br>eureka.client.service-url.defaultZone=http://localhost:8761/eureka/</pre><h3>Benefits of SpringBoot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*9kTt7xcUQYjap2AARLD13g.png" /></figure><h3>Conclusion</h3><p>Spring Boot simplifies Java application development by reducing configuration overhead and enabling rapid development. Its microservices support, production-ready features, and easy integration with DevOps make it a preferred choice for developers.</p><p><strong>Want to Learn More?</strong> Explore the official<a href="https://spring.io/projects/spring-boot"> Spring Boot Documentation</a>. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb04a619690b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello Go: A Fun and Easy Introduction to Golang]]></title>
            <link>https://medium.com/@paragkaldate/golang-for-beginners-a-fun-and-easy-introduction-b4a2eecdb8c6?source=rss-20850bddca0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4a2eecdb8c6</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[future-technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Parag Kaldate]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 07:25:05 GMT</pubDate>
            <atom:updated>2024-12-30T18:45:11.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDLPJcN3xLrG-0aTdsKsFQ.png" /></figure><h3>Introduction</h3><p>Imagine this: You’re a developer working on a project that needs to handle millions of user requests every second. The solution must be fast, scalable, and efficient while remaining simple to maintain. You explore different programming languages, but many of them either feel too slow, too complex, or not built for concurrency.</p><p>This is where <strong>Golang</strong> (or <strong>Go</strong>) enters the picture. Designed by Google engineers, Go is like that friend who’s always calm, efficient, and reliable no matter how chaotic things get. Whether you’re building a web server, a CLI tool, or even a distributed system, Go is tailored to help you solve problems with speed and simplicity.</p><p>But what makes Go so special? Why is it used by companies like Google, Uber, and Netflix for their high-performance systems? And more importantly, why should <em>you</em> consider learning Go as a beginner?</p><p>In this blog, we’ll explore the essentials of Golang in a way that’s easy, fun, and beginner-friendly. Along the way, we’ll highlight why Go might just become your new favorite language, complete with visuals and examples. So, grab a cup of coffee and let’s dive into the world of Go!</p><h3>Why Learn Golang?</h3><p>When learning a new programming language, it’s natural to ask: “Why should I invest my time in this? What sets it apart from the dozens of other languages out there?”</p><p>Golang, or Go, is not just another language — it’s a practical solution to some of the biggest challenges developers face today. It was created by Google to combine the performance of low-level languages like C++ with the simplicity and readability of modern languages like Python.</p><p>But what makes Go stand out, especially for beginners?</p><ol><li><strong>Simplicity at Its Core</strong><br>Golang is like a breath of fresh air — it strips away unnecessary complexities that bog down other languages. Its clean and concise syntax is easy to read, write, and learn, making it perfect for developers of all skill levels.</li><li><strong>Lightning-Fast Performance</strong><br>Compiled directly to machine code, Go is blazing fast. Whether you’re building a real-time chat app or a high-speed API, Go ensures your programs run as efficiently as possible.</li><li><strong>Built-in Concurrency</strong><br>In today’s world of multi-core processors, handling multiple tasks at once is crucial. Go’s lightweight goroutines and channels make concurrent programming straightforward, giving you tools to maximize your app’s potential.</li><li><strong>Scalable by Design</strong><br>Go is built with scalability in mind. That’s why companies like Netflix and Dropbox use it to power their backend systems, handling millions of requests without breaking a sweat.</li><li><strong>A Language for the Future</strong><br>Golang was designed for modern development needs: cloud computing, microservices, and distributed systems. Its standard library is robust, allowing you to build powerful applications without relying heavily on third-party libraries.</li><li><strong>Community and Opportunities</strong><br>Go has a vibrant, growing community and is widely used in industry-leading projects like Kubernetes, Docker, and Terraform. Learning Go not only boosts your skills but also opens doors to exciting career opportunities.</li></ol><h3>Key Features</h3><p>Golang is packed with features that make it a go-to language for developers worldwide. Let’s explore some of its standout characteristics that set it apart:</p><blockquote>1. Simplicity by Design</blockquote><p>Go was built with one philosophy: keep it simple. Its clean and minimalistic syntax reduces cognitive load, allowing you to focus on solving problems rather than wrestling with the language itself.</p><p>For example, Go avoids complex features like inheritance, making the code easier to write and maintain.</p><blockquote>2. Blazing Fast Compilation</blockquote><p>Unlike interpreted languages, Go is compiled directly into machine code, which makes it incredibly fast — both in execution and compilation time. Whether you’re working on a small project or a large application, you’ll notice the speed right away.</p><blockquote>3. Goroutines and Channels</blockquote><p>Concurrency is often a headache for developers, but not with Go. Goroutines allow you to run multiple functions simultaneously with minimal memory usage. Add channels to the mix, and you’ve got a powerful yet simple way to communicate between tasks.</p><blockquote>4. Garbage Collection</blockquote><p>Go’s built-in garbage collector takes care of memory management for you, freeing you from manual allocation and deallocation. It’s like having a personal janitor for your code.</p><blockquote>5. Standard Library</blockquote><p>Go comes with a robust and versatile standard library. Whether you need to handle HTTP requests, manipulate strings, or work with file systems, Go’s library has you covered.</p><blockquote>6. Cross-Platform Support</blockquote><p>Write once, run anywhere! Go generates standalone binaries, so your applications can run on multiple operating systems without any extra dependencies. This makes deploying your projects a breeze.</p><blockquote>7. Static Typing and Safety</blockquote><p>Go’s static typing catches errors at compile time, ensuring more reliable code. It’s like having a built-in safety net for your applications.</p><blockquote>8. Built-In Tools</blockquote><p>Go provides handy tools like:</p><ul><li><strong>go fmt</strong>: Formats your code automatically.</li><li><strong>go test</strong>: Runs your unit tests with ease.</li><li><strong>go build</strong>: Compiles your code into an executable.</li></ul><p>These tools make development smoother and more efficient.</p><blockquote>9. Open Source and Community-Driven</blockquote><p>Go is open source, and its vibrant community contributes to its ongoing development. With such a dynamic ecosystem, you’re never short of resources, tutorials, and libraries.</p><p>These features combine to make Go not only powerful but also a joy to work with. In the next section, we’ll take a deeper dive into the <strong>Pros and Cons</strong> of using Golang so you can see where it truly shines — and where it might not be the perfect fit.</p><h3>Why Golang stands out?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*2Z-YokkiWt95BtuEtL1KFw.png" /></figure><ol><li><strong>Designed for Simplicity</strong><br>Go’s philosophy revolves around reducing complexity. Its clean, minimalistic syntax ensures faster learning and easier code maintenance compared to verbose languages.</li><li><strong>Modern Concurrency Model</strong><br>Unlike traditional threads, Go’s goroutines are lightweight and scalable, enabling efficient handling of thousands of concurrent tasks, perfect for distributed systems.</li><li><strong>Cloud-Ready by Design</strong><br>As the backbone of tools like Kubernetes and Docker, Go is purpose-built for modern cloud-native applications and excels in microservices and containerization.</li><li><strong>Efficient Compilation and Deployment</strong><br>Go produces compact, standalone binaries, streamlining cross-platform deployments without requiring additional runtimes or dependencies.</li><li><strong>Balanced Performance</strong><br>Go combines the speed of compiled languages with efficient memory management via garbage collection, striking an optimal balance for most applications.</li><li><strong>Pragmatic Developer Tools</strong><br>Built-in tools like go fmt and go test enforce coding standards, ensure reliability, and boost developer productivity without relying on external utilities.</li></ol><h3>Getting Started with Golang</h3><p>Now that we’ve explored what makes Golang special, let’s dive into how you can get started with it! Whether you’re a complete beginner or transitioning from another language, setting up Go and writing your first program is easy. Here’s a step-by-step guide to help you hit the ground running.</p><h4>1. Setting Up Golang</h4><p>First, you’ll need to install Go on your system. Here’s how to do it:</p><blockquote><strong>For Windows</strong>:</blockquote><ul><li>Go to the official <a href="https://golang.org/dl/">Go Downloads page</a> and download the installer.</li><li>Follow the installation instructions and set up Go in your system environment variables.</li></ul><blockquote><strong>For macOS</strong>:</blockquote><ul><li>You can install Go using Homebrew with the command:</li></ul><pre>brew install go</pre><ul><li>Alternatively, download the installer from the Go website and follow the prompts.</li></ul><blockquote><strong>For Linux</strong>:</blockquote><ul><li>On Linux, you can use the package manager for your distribution. For example, on Ubuntu, you can run:</li></ul><pre>sudo apt install golang-go</pre><ul><li>Alternatively, download the latest version from the <a href="https://golang.org/dl/">Go website</a> and install manually.</li></ul><p>Once installed, check if everything is working by typing go version in your terminal. You should see something like:</p><pre>go version go1.18.1 linux/amd64</pre><h4>2. Setting Up Your Workspace</h4><p>Go encourages a clean project structure, and the GOPATH environment variable is key to managing your Go workspace. Here’s a quick setup:</p><ul><li>Create a directory for your Go workspace. For example:</li></ul><pre>mkdir ~/go</pre><ul><li>Inside this workspace, create directories for your projects:</li></ul><pre>mkdir -p ~/go/src/my-first-project</pre><h4>3. Your First Go Program</h4><p>With Go set up, it’s time to write your first program. Open your text editor and create a file called main.go inside your project directory.</p><p>Here’s a simple program to get you started:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    fmt.Println(&quot;Hello, Golang!&quot;)<br>}</pre><p>To run the program, navigate to the directory containing main.go and run:</p><pre>go run main.go</pre><p>You should see the output:</p><pre>Hello, Golang!</pre><p>Congratulations! You’ve just written and executed your first Go program.</p><h4>4. Understanding Go’s Structure</h4><p>Go programs are organized into <strong>packages</strong>. Every Go program starts with the main package if it’s the entry point of the application. You import other packages using the import statement, and Go automatically handles dependencies.</p><h4>5. Next Steps</h4><ul><li>Learn more about <strong>variables</strong>, <strong>data types</strong>, <strong>control structures</strong>, and <strong>functions</strong>.</li><li>Try out Go’s powerful features like <strong>concurrency with goroutines</strong> and <strong>channels</strong>.</li><li>Explore Go’s built-in <strong>testing framework</strong> and tools to ensure your code is reliable.</li></ul><h3>Examples</h3><p>Now that you’ve set up Go and written your first program, let’s have some fun with interactive examples that demonstrate Go’s power in action! These examples will help you explore different aspects of Go while keeping things engaging and simple.</p><h4>1. Goroutines: Concurrency Made Easy</h4><p>Go is known for its lightweight goroutines, which allow you to run multiple functions concurrently. Here’s a simple example where we run two functions concurrently, printing “Hello” and “World” in any order:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func greet(greeting string) {<br>    fmt.Println(greeting)<br>}<br>func main() {<br>    go greet(&quot;Hello&quot;) // goroutine<br>    go greet(&quot;World&quot;) // goroutine<br>    var input string<br>    fmt.Scanln(&amp;input)<br>}</pre><p><strong>What makes this cool?</strong><br> With just the go keyword, we can run multiple tasks at the same time without worrying about complex threading. The output could be &quot;Hello&quot; first or &quot;World&quot; first—demonstrating Go’s simplicity and power in handling concurrency.</p><h4>2. Fibonacci with Goroutines</h4><p>Here’s a more complex example of using goroutines and channels to calculate the Fibonacci sequence concurrently. It shows Go’s concurrency in action:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func fibonacci(n int, result chan int) {<br>    if n &lt;= 0 {<br>        result &lt;- 0<br>        return<br>    } else if n == 1 {<br>        result &lt;- 1<br>        return<br>    } else {<br>        ch1 := make(chan int)<br>        ch2 := make(chan int)<br>        go fibonacci(n-1, ch1) // recursive goroutine<br>        go fibonacci(n-2, ch2) // recursive goroutine<br>        result &lt;- &lt;-ch1 + &lt;-ch2<br>    }<br>}<br><br>func main() {<br>    n := 10<br>    result := make(chan int)<br>    go fibonacci(n, result)<br>    fmt.Println(&quot;The&quot;, n, &quot;th Fibonacci number is:&quot;, &lt;-result)<br>}</pre><p><strong>What’s exciting here?</strong><br> This demonstrates how Go’s concurrency model can speed up complex calculations, even recursion! With goroutines working in parallel, Go can process tasks more efficiently.</p><h4>3. Web Server in 10 Lines of Code</h4><p>Go makes building web servers incredibly simple. In just 10 lines of code, you can create a basic web server that responds with “Hello, Go!” when accessed:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;net/http&quot;<br>)<br><br>func helloHandler(w http.ResponseWriter, r *http.Request) {<br>    fmt.Fprintf(w, &quot;Hello, Go!&quot;)<br>}<br><br>func main() {<br>    http.HandleFunc(&quot;/&quot;, helloHandler)<br>    http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><p><strong>Why is this fun?</strong><br> Go’s built-in web server capabilities make it incredibly easy to get started with web development. Just a few lines of code, and you have a fully functional web server — ideal for building APIs or services.</p><h3>Pros and Cons of Golang</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9q9JiDZYjhKTs1uON8qnRQ.png" /></figure><h3>Common Use Cases</h3><blockquote>Web Development</blockquote><p>Go is used to build fast, scalable web applications and APIs, thanks to its efficient concurrency model.</p><blockquote>Microservices Architecture</blockquote><p>Go’s simplicity, performance, and concurrency make it a popular choice for building microservices.</p><blockquote>Cloud Services and Networking</blockquote><p>Go’s strong networking libraries make it ideal for building cloud-based applications, network servers, and services.</p><blockquote>Devops &amp; Automation</blockquote><p>With Go’s fast compilation and execution, it is commonly used for creating command-line tools, automation scripts, and infrastructure tools.</p><blockquote>Distributed Systems</blockquote><p>Go excels in building distributed systems, thanks to its concurrency model and support for handling multiple tasks at once.</p><blockquote>Data Processing</blockquote><p>Go is used for processing large datasets or performing high-performance computations, thanks to its speed and scalability.</p><blockquote>Blockchain development</blockquote><p>Due to its speed and efficiency, Go is often used in blockchain development, particularly for building blockchain networks and smart contracts.</p><h3>Conclusion</h3><p>Go is a powerhouse — fast, simple, and built for concurrency. It’s perfect for modern web services, microservices, and cloud applications. Whether you’re a beginner or a seasoned developer, Go’s clean syntax and robust performance make it a language worth mastering. In a world where efficiency and scalability matter, Go is the language that delivers.</p><h3>‘Go’ for it!</h3><p>The future of software development is here, and Go is leading the charge. With more and more companies adopting Go for its speed, simplicity, and scalability, now is the perfect time to get on board. Whether you’re building the next big web app, exploring microservices, or diving into cloud computing, Go is the tool you need. Don’t miss out — learn Go today, and position yourself at the forefront of the tech world’s most exciting revolution!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIvDEwt_PVFDYHdKbjTvSQ.png" /></figure><h3>Thank You!</h3><p>Thank you for reading through this introduction to Golang! I hope this gave you a glimpse of the power and simplicity of Go. If you’re excited to explore more, don’t hesitate to dive deeper and start experimenting with the language. Feel free to share your thoughts or questions in the comments — I’d love to hear from you! Happy coding, and good luck on your Golang journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4a2eecdb8c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Java Made Easy!]]></title>
            <link>https://medium.com/@paragkaldate/multithreading-in-java-made-easy-c56def40eebc?source=rss-20850bddca0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c56def40eebc</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[multithreading-in-java]]></category>
            <dc:creator><![CDATA[Parag Kaldate]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 03:44:35 GMT</pubDate>
            <atom:updated>2024-06-03T03:44:35.762Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>What is Multithreading?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*pO9E1HLRmUbdd7rXoffL-g.png" /></figure><p>1. Multithreading is like having multiple helpers working on different tasks at the same time.</p><p>2. Instead of doing one thing at a time, multithreading allows your program to do multiple things simultaneously, making it faster and more efficient.</p><p>3. It’s like having one helper cleaning your room, another doing homework, and a third helping your mom with chores — everything gets done quicker when you divide the work.</p><blockquote><strong>Understanding Threads</strong></blockquote><ul><li><strong>Thread is a subset of Process:</strong> Imagine you’re at a restaurant, and the waiter is the only person serving all the tables. This waiter is like a single thread in a program — they can only handle one task at a time. If the waiter is taking an order from one table, they can’t attend to other tables until they’re done with the first task.</li><li><strong>Multiple Waiters: </strong>Now, let’s say the restaurant hires multiple waiters. Each waiter is like a separate thread in a program. They can all work simultaneously, taking orders from different tables, delivering food, and clearing plates. With multiple threads (waiters), the restaurant can serve more customers faster and more efficiently.</li></ul><blockquote><strong>Single threaded V/S Multithreaded</strong></blockquote><p><strong>A single-threaded</strong> program is like having only one waiter in the restaurant. It can only do one task at a time, so if it’s working on a time-consuming task (like preparing a complicated dish), it can’t do anything else until that task is finished. This can make the program feel slow and unresponsive.</p><p>On the other hand, <strong>a multi-threaded program</strong> is like having multiple waiters in the restaurant. It can handle multiple tasks simultaneously by dividing the work among different threads. While one thread is busy with a long-running task (like preparing that complicated dish), other threads can still take orders, serve drinks, or clear tables, keeping the program responsive and efficient.</p><blockquote><strong>Advantages and Disadvantages of Multithreading</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8VSIAm2MwriTygsptBQDQ.png" /></figure><blockquote><strong>Inter-threads communication</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*GeOWJ4fCryiOH8xSZRCkhw.png" /></figure><p><strong>Inter-thread communication</strong> refers to the way threads in a multithreaded program can exchange data or coordinate their activities with each other. In simple terms, it’s like different workers (threads) talking to each other or sharing information to accomplish a bigger task together.</p><p>Imagine you and your friends are working on a group project. Each person is responsible for a different part of the project, but you all need to communicate and share information with each other to ensure the project is completed successfully.</p><p>Similarly, in a multithreaded program, different threads work on different parts of the overall task. Sometimes, these threads need to communicate with each other to share data, notify each other about certain events, or coordinate their activities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_LhCEL5EjU8kfzgmviwPEw.jpeg" /></figure><p>There are a few ways threads can communicate in Java:</p><h4>1. Shared Memory:</h4><p>Threads can communicate by reading and writing to shared variables or objects in memory. It’s like leaving notes or messages in a shared space for other threads to read and respond to. However, this method requires careful synchronization to avoid race conditions (like two people trying to write on the same note at the same time).</p><h4>2. Wait and Notify:</h4><p>Java provides methods like `wait()`, `notify()`, and `notifyAll()` that allow threads to wait for a specific condition and be notified when that condition is met. It’s like one worker telling another worker, “Hey, I’ve finished my part, now it’s your turn to work on the next step.”</p><h4>3. Blocking Queues:</h4><p>Threads can also communicate by exchanging data through queues. One thread puts data in the queue, and another thread takes data out of the queue. It’s like passing items along a production line, where each worker adds their part before passing it to the next worker.</p><h4>4. Semaphores and Locks:</h4><p>These are like coordinating mechanisms that allow threads to acquire and release resources or control access to shared data. It’s similar to having a traffic signal or a lock on a shared room, ensuring only one worker can access it at a time.</p><p>Inter-thread communication is essential for multithreaded programs to work correctly and efficiently. However, it’s important to manage communication carefully to avoid issues like race conditions, deadlocks, and thread safety problems.</p><blockquote><strong>Preemptive scheduling &amp; Time slicing</strong></blockquote><p><strong>Pre-emptive Scheduling:</strong><br>Imagine you and your friends are playing a game where you take turns rolling a dice. In pre-emptive scheduling, it’s like having a strict teacher who can interrupt any player’s turn and give the dice to the next player. The teacher decides when to stop one player’s turn and switch to the next player, regardless of whether the current player has finished their turn or not.</p><p>Similarly, in a pre-emptive scheduling system, the operating system can interrupt a currently running thread and switch to another thread, even if the first thread hasn’t finished its task. This helps ensure that no single thread monopolizes the CPU for too long, allowing other threads to get a chance to run.</p><p><strong>Time Slicing:</strong><br>Time slicing is a way to implement pre-emptive scheduling. It’s like the teacher giving each player a fixed amount of time (e.g., 30 seconds) to roll the dice. Once a player’s time is up, the teacher interrupts them and gives the dice to the next player, regardless of whether they have finished their turn or not.</p><p>In the context of multithreading, time slicing involves dividing the available CPU time into small time slices or intervals. The operating system assigns a time slice to each thread, allowing it to run for that specific duration. When a thread’s time slice expires, the operating system interrupts that thread and assigns the next time slice to another thread, ensuring that all threads get a chance to run and make progress.</p><p>Time slicing helps prevent any single thread from monopolizing the CPU for an extended period, which could cause other threads to starve (not get a chance to run). It also allows the operating system to provide a responsive and fair environment for all threads to execute.</p><p>By using pre-emptive scheduling and time slicing, multithreaded applications can efficiently share the CPU resources, ensuring that no single thread dominates the system and that all threads can make progress towards completing their tasks.</p><blockquote><strong>Context Switching:</strong></blockquote><p>Context switching is the process of storing and restoring the state (context) of a thread so that the CPU can switch from one thread to another.</p><p>It’s like when you and your friends take turns playing a video game. When your turn ends, you have to save your game progress (context) before passing the controller to the next person. When it’s your turn again, you load your previously saved game state to continue from where you left off.</p><p>In a multithreaded program, the CPU frequently switches between different threads. Each time a switch occurs, the operating system must:</p><p>1. Save the current thread’s context (register values, instruction pointer, etc.) in memory.<br>2. Load the next thread’s previously saved context from memory.</p><p>This context switching process introduces some overhead as the CPU has to do extra work to save and restore contexts instead of executing actual program instructions.</p><p>While context switching is necessary for multithreaded programs to function correctly, excessive switching can impact performance. Developers should be mindful of this and try to minimize unnecessary context switching to ensure efficient multithreaded execution.</p><blockquote><strong>Thread Creation</strong></blockquote><p>In Java, you can create a new thread in two ways: <br>1. by extending the `Thread` class <br>2. by implementing the `Runnable` interface.</p><p>The recommended approach is to implement the `Runnable` interface as it promotes better code design and reusability.</p><p><strong>1. Using the `Thread` class:</strong></p><pre>class MyThread extends Thread {<br> @Override<br> public void run() {<br> // Code to be executed by the new thread<br> System.out.println(&quot;This is a new thread!&quot;);<br> }<br>}<br>// Creating and starting the thread<br>MyThread thread = new MyThread();<br>thread.start(); // Calls the run() method in a separate thread</pre><p><strong>2. Using the `Runnable` interface:</strong></p><pre>class MyRunnable implements Runnable {<br> @Override<br> public void run() {<br> // Code to be executed by the new thread<br> System.out.println(&quot;This is a new thread!&quot;);<br> }<br>}<br>// Creating and starting the thread<br>Runnable runnable = new MyRunnable();<br>Thread thread = new Thread(runnable);<br>thread.start(); // Calls the run() method in a separate thread</pre><p><strong>Understanding `start()` and `run()`</strong></p><p>- The `start()` method is used to create and start a new thread. When you call `start()`, the JVM creates a new thread and calls the `run()` method of that thread in a separate execution path.<br>- The `run()` method contains the code that will be executed by the new thread. Calling `run()` directly (without calling `start()`) will execute the code in the same thread, not creating a new thread.</p><p><strong>Controlling Thread Execution</strong></p><p>Java provides several methods to control the execution of threads:</p><ol><li><strong>`sleep()`:</strong> The `Thread.sleep(long millis)` method pauses the execution of the current thread for the specified number of milliseconds. This can be useful to introduce delays or simulate time-consuming operations.</li></ol><pre>try {<br> Thread.sleep(2000); // Pauses the current thread for 2 seconds<br>} catch (InterruptedException e) {<br> e.printStackTrace();<br>}</pre><p><strong>2. `join()`:</strong> The `join()` method allows one thread to wait for another thread to complete its execution. This is useful when you need to ensure that a task running in a separate thread finishes before continuing with the main thread.</p><pre>Thread worker = new Thread(new MyRunnable());<br>worker.start();<br>try {<br> worker.join(); // Waits for the worker thread to complete<br>} catch (InterruptedException e) {<br> e.printStackTrace();<br>}<br>System.out.println(&quot;Worker thread has finished!&quot;);</pre><p><strong>3. `interrupt()`:</strong> The `interrupt()` method is used to request the termination of a thread. It does not stop the thread immediately but rather sets an interrupt flag that the thread can check and handle accordingly.</p><pre>Thread worker = new Thread(new MyRunnable());<br>worker.start();<br>// Later, if you want to interrupt the worker thread<br>worker.interrupt();</pre><p>It’s important to note that while these methods provide control over thread execution, it’s also crucial to handle situations like thread interruptions and synchronization to ensure thread safety and avoid issues like race conditions and deadlocks.</p><p><strong>Thread Class V/S Runnable Interface</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tab8_i3cRgQk7Zz8bOebhw.png" /></figure><blockquote><strong>sleep() VS wait()</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ot4_zC9RXTlMEdgrHjexHQ.png" /></figure><blockquote>What is <strong>Daemon Threads</strong>?</blockquote><p><em>A Daemon thread</em> in Java is like a background helper that works while your main program is running but doesn’t need to finish its work before the program ends. Think of it as a janitor at a school. The janitor cleans the school (does background tasks) while the school (your main program) is open. But when the school closes (the main program ends), the janitor stops working too, even if the cleaning isn’t done.</p><p>Here are a few key points:</p><p><strong>- Background Task:</strong> It runs in the background doing tasks like garbage collection or other maintenance work.<br><strong>- Stops Automatically:</strong> When all the main (non-daemon) threads are finished, daemon threads stop automatically.<br><strong>- Not Crucial:</strong> They aren’t essential for the program to run; they just help out in the background.</p><p>So, daemon threads are like those helpful background workers that make sure everything runs smoothly without needing to be front and center.</p><blockquote><strong>Synchronization</strong></blockquote><p><em>(One Thread at a time)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLLCXTgeCDUsLlHVb2TvRQ.png" /></figure><p>Imagine a library with only one copy of a popular book. If two people try to read it at the same time, they’ll end up fighting over it and might damage the book. To avoid this, the librarian creates a rule: <strong>only one person can read the book at a time, and others must wait their turn</strong>.</p><p>In Java, synchronization is like the librarian’s rule. It ensures that when one thread (a person) is accessing a shared resource (the book), no other thread can use it until the first thread is done. This prevents conflicts and keeps everything running smoothly.</p><pre>synchronized (object) {<br>    // Code that needs to be synchronized<br>}</pre><p>Here are a few points to make it clearer:</p><p>- <strong>Lock:</strong> When a thread wants to use a shared resource, it locks it. Think of it as signing out the book.<br>- <strong>Wait:</strong> Other threads wanting the same resource must wait until it’s available. Like waiting in line for the book.<br>- <strong>Release:</strong> Once the thread is done, it releases the lock. The next person in line gets the book.</p><p>So, synchronization in Java is like a librarian managing the usage of a popular book, making sure everyone gets their turn without any chaos.</p><p><strong>Static Synchronization:</strong></p><p>Static synchronization is used to control access to static methods or static variables, ensuring that only one thread can execute any synchronized static method of a class at a time. It locks on the Class object associated with the class, so even if multiple instances exist, the synchronized static method is accessed by one thread only.</p><blockquote><strong>Deadlock</strong></blockquote><p>Deadlock occurs in a multithreaded environment when two or more threads are blocked forever, each waiting on the other to release a resource. This situation leads to a standstill where none of the threads can proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ZO3mgfoZpnNxQywsQKnLNg.png" /></figure><p><strong>Key Concepts Related to Deadlock</strong></p><p>1. <strong>Mutual Exclusion: </strong>At least one resource must be held in a non-shareable mode; only one thread can use the resource at any given time.</p><p><strong>2. Hold and Wait: </strong>A thread holding at least one resource is waiting to acquire additional resources held by other threads.</p><p><strong>3. No Preemption: </strong>Resources cannot be forcibly taken from a thread holding them; they must be released voluntarily.</p><p>4. <strong>Circular Wait: </strong>A set of threads are waiting for each other in a circular chain, where each thread holds a resource that the next thread in the chain needs.</p><p><strong>Volatile Keyword</strong></p><p>The volatile keyword in Java is used to indicate that a variable’s value will be modified by different threads. Declaring a variable as volatile ensures that its updates are immediately visible to all threads, preventing the caching of the variable’s value in a thread’s local memory and ensuring that reads and writes to the variable are always done from the main memory.</p><p><strong>Thread Pool</strong></p><p>A thread pool is a collection of pre-instantiated reusable threads. Instead of creating and destroying threads frequently, a thread pool manages a pool of worker threads, which improves performance by reusing threads for multiple tasks, reducing the overhead associated with thread creation and termination, and providing better resource management and control over the number of concurrent threads.</p><p><strong>Thread Safety</strong></p><p>Thread safety in Java means ensuring that shared data structures are accessed by multiple threads in a way that prevents corruption or unexpected behavior. A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads. Techniques to achieve thread safety include synchronization, using atomic variables, and utilizing thread-safe collections.</p><h3>Concurrency Utilities</h3><p>The java.util.concurrent package provides a framework for managing concurrency in Java applications. Key components include:</p><ul><li><strong>Executors</strong>: A framework for managing a pool of threads. It simplifies the process of running tasks asynchronously. Examples include ExecutorService and ScheduledExecutorService.</li><li><strong>CountDownLatch</strong>: A synchronization aid that allows one or more threads to wait until a set of operations being performed by other threads is complete.</li><li><strong>ConcurrentHashMap</strong>: A thread-safe variant of HashMap that allows concurrent reads and writes without needing to synchronize the entire map, improving performance in multithreaded environments.</li></ul><h3>Reentrant Locks</h3><p>ReentrantLock is a lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities. A reentrant lock allows the thread that currently holds the lock to re-acquire it without blocking.</p><h3>Fork/Join Framework</h3><p>The Fork/Join Framework is designed for parallel processing tasks that can be divided into smaller subtasks, which can be executed concurrently. It uses a work-stealing algorithm to efficiently manage the tasks. The framework is particularly useful for recursive algorithms like those used in divide-and-conquer strategies.</p><h3>Callable/Runnable interfaces and Future</h3><ul><li><strong>Runnable</strong> and <strong>Callable</strong> are essential for defining tasks in a way that can be executed by multiple threads.</li><li>Runnable is used for tasks that do not need to return a result or throw checked exceptions.</li><li>Callable is used for tasks that need to return a result or can throw checked exceptions.</li><li>These interfaces enable better task management, improved resource utilization, and cleaner separation between task logic and thread management, which are crucial for effective multithreading.</li><li><strong>Future</strong>: Represents the result of an asynchronous computation. It provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHOF4rwz6HZs4qg5cc9udA.png" /><figcaption>Runnable v/s Callable Interfaces</figcaption></figure><h3>ThreadLocal Variables</h3><p>ThreadLocal provides thread-local variables. Each thread accessing such a variable has its own, independently initialized copy of the variable. ThreadLocal is useful for maintaining per-thread context (like user sessions in web applications) without needing synchronization.</p><h3>ScheduledExecutorService</h3><p>ScheduledExecutorService is part of the java.util.concurrent package and extends ExecutorService to support future and periodic task execution. It allows you to schedule tasks to run after a given delay or periodically at a fixed rate or with a fixed delay between executions.</p><h3>Conclusion</h3><p>Multithreading in Java enables the efficient execution of concurrent tasks, improving application performance and responsiveness. By understanding and effectively using the concepts and tools provided by the Java concurrency framework, developers can build robust, high-performing applications. Managing threads involves careful coordination and synchronization to ensure thread safety and avoid issues such as race conditions and deadlocks. With the right approach, multithreading can significantly enhance the capabilities of your Java applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c56def40eebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Java Essentials: Revisiting Core Concepts”]]></title>
            <link>https://medium.com/@paragkaldate/java-essentials-revisiting-core-concepts-6cf2941128cc?source=rss-20850bddca0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cf2941128cc</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[easy]]></category>
            <dc:creator><![CDATA[Parag Kaldate]]></dc:creator>
            <pubDate>Mon, 27 May 2024 05:51:39 GMT</pubDate>
            <atom:updated>2024-05-27T14:37:40.966Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Java Essentials: Revisiting Core Concepts”</blockquote><blockquote>Introduction:</blockquote><p><em>What is Java?</em></p><ol><li>A high-level, class-based, object-oriented programming language.</li><li>Platform-independent (Write Once, Run Anywhere — WORA).</li></ol><p>Features:</p><p>Simple, Secure, Portable, Object-Oriented, Robust, Multithreaded, High Performance.</p><blockquote>JVM, JDK and JRE:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/0*c9OoscXQWNl_5ww6" /><figcaption>JDK, JRE &amp; JVM</figcaption></figure><p><strong>JVM: </strong>An environment where Java ByteCode can be executed.<br><strong>JRE: </strong>It is an implementation of JVM, i.e. It consists of a set of libraries and tools that JVM uses.<br><strong>JDK:</strong> (JRE + Dev tools) Development Environment.</p><ul><li>J2SE, Standard Edition: Core Java, foundation of all other editions, mainly used to create applications for Desktop environment.</li><li>J2EE, Enterprise Edition: Used for building large-scale, distributed, and multi-tiered enterprise applications, such as web services and network applications.</li><li>J2ME, Micro Edition: Used for developing applications for small, resource-constrained devices like mobile phones and embedded systems.</li></ul><p><strong>JVM is Platform Dependent</strong>, as it is available for many different softwares/hardwares.<br><strong>Java is Platform Independent</strong> because of ByteCode.</p><ul><li>Executing Java file:<br> Compile — javac .java<br> Run — java classname</li><li>public static void ≈ static public void <strong>(Order doesn’t matter)</strong></li><li><strong>Local variables have no default value</strong>: it means that Java does not automatically initialize these variables to any default value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/0*_XOIEbHC38tiZisD" /><figcaption>Access Specifiers in Java</figcaption></figure><blockquote>Data Types and Variables:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*CaokAkDrBrl1Rz6w" /><figcaption>Data types in Java</figcaption></figure><blockquote>Operators</blockquote><ul><li>Arithmetic Operators +, -, *, /, %.</li><li>Relational Operators ==, !=, &gt;, &lt;, &gt;=, &lt;=.</li><li>Logical Operators &amp;&amp;, ||, !.</li><li>Assignment Operators =, +=, -=, *=, /=, %=.</li><li>Unary Operators ++, — .</li></ul><h3>OOP with Java:</h3><blockquote><strong>Constructors in Java:</strong></blockquote><ul><li>Default Constructor — A default constructor is a constructor that takes no arguments. It is automatically provided by the compiler if no other constructor is defined in the class.</li><li>Parameterized Constructor — A parameterized constructor is a constructor that takes one or more arguments. It is used to initialize the object with user-defined values.</li><li>Copy Constructor — Java does not have a built-in copy constructor feature like C++. However, Java provides an alternative way to create copies of objects through the following methods:<br> — <strong>Cloning</strong>: Java provides the Cloneable interface and the clone() method in the Object class. If a class implements the Cloneable interface and overrides the clone() method, objects of that class can be cloned. This creates a new instance with the same state as the original object. <br> — <strong>Copy Constructor</strong>: Although Java does not have a built-in copy constructor, you can create your own copy constructor by defining a constructor that takes an object of the same class as an argument and initializes the new object’s fields with the values from the argument object.<br> — <strong>Object Copying</strong>: You can create a new instance of the class and manually copy the values of all the fields from the original object to the new object.<br> — <strong>Serialization and Deserialization</strong>: You can serialize an object to a byte stream and then deserialize it to create a new object with the same state as the original object.<br> — Among these options, cloning and creating a copy constructor are the most common approaches used in Java for creating copies of objects.</li></ul><blockquote><strong>Static keyword in Java:</strong></blockquote><p>Imagine you have a classroom with multiple students. Each student has their own bag, pencil case, and water bottle. These are their personal belongings, and they can use them whenever they want.</p><p>However, there are some things in the classroom that are shared by all the students, like the blackboard, the teacher’s desk, and the classroom clock. These shared things are called ‘static’ things because they remain the same for everyone in the classroom.</p><p>In Java, the ‘static’ keyword works similarly. When you declare a variable or a method as ‘static’, it becomes a shared thing among all the objects (instances) of that class.</p><p>For example, let’s say you have a class called ‘Student’. Each student object would have their own name, age, and grade. But if you want to keep track of the total number of students in the class, you can declare a ‘static’ variable called ‘totalStudents’. This variable would be shared among all the ‘Student’ objects, and its value would be the same for everyone.</p><p>Here’s an example:</p><pre>class Student {<br>    String name;<br>    int age;<br>    int grade;<br>    static int totalStudents = 0; // Static variable<br><br>    Student(String name, int age, int grade) {<br>        this.name = name;<br>        this.age = age;<br>        this.grade = grade;<br>        totalStudents++; // Incrementing the static variable for each new student<br>    }<br>}</pre><p>In this example, each ‘Student’ object would have its own ‘name’, ‘age’, and ‘grade’, but they would all share the ‘totalStudents’ variable. Whenever a new ‘Student’ object is created, the ‘totalStudents’ variable is incremented by 1.</p><p>Similarly, you can also have ‘static’ methods in a class. These methods can be called without creating an instance of the class, and they can only access and modify ‘static’ variables.</p><p>The ‘static’ keyword in Java helps you manage shared resources and data among objects of the same class. It’s a powerful concept that you’ll use a lot as you continue learning programming.</p><p><strong>Static methods</strong> are used when you want a method to be associated with the class itself, rather than with any specific instance of that class. They are often used for utility or helper methods that don’t require any instance-specific data. Static methods can only access and modify static variables, as they don’t have access to non-static (instance) variables or methods.</p><p><strong><em>Key points about ‘static’ keyword:</em></strong></p><ul><li>Static variables get memory only once — Making it more memory efficient.</li><li>Static members belong to the class, not objects.</li><li>No need to create an object to access static members of the class.</li><li>Static method can access and change a static variable’s value.</li><li>Non-static data members can not be used in a static method.</li><li>Static methods can not be overridden.</li><li><strong>Why is the main method static? — </strong>The main method is declared as static so that it can be invoked by the Java Virtual Machine without creating an instance of the class, as it serves as the entry point for the program’s execution</li></ul><p><strong>‘this’ keyword in Java is used:</strong></p><ul><li>To refer to the current object.</li><li>To invoke current class methods.</li><li>this() is used to invoke the current class constructor from another constructor within the same class.</li><li>Can be passed as an argument to refer to the current object instance.</li></ul><blockquote>Inheritance: (Parent-child/ is-a relationship)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*NHq9hQU8pdC5B8QQ" /></figure><h4>Aggregation &amp; Composition:</h4><p>Aggregation: It is a weak form of association between two objects. In aggregation, one object “has-a” reference to another object, but they have separate lifetimes. The contained object can exist independently without the container object. For example, a Department “has-a” collection of Students.</p><p>Composition: It is a strong form of association between two objects. In composition, one object “owns” another object, and the contained object cannot exist without the container object. The lifecycle of the contained object is dependent on the container object. For example, a Car “has-a” Engine, and the Engine cannot exist without the Car.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pVz9209WfjgZKZM4" /><figcaption>Aggregation VS Composition</figcaption></figure><h4>Super Keyword:</h4><ol><li><strong>Accessing Superclass Members: </strong>The super keyword is used to access members (variables and methods) of the superclass from a subclass. It is particularly useful when there is a name clash between the variables or methods of the superclass and the subclass. In such cases, super allows you to explicitly reference the member of the superclass.</li><li><strong>Calling Superclass Constructors: </strong>The super() call is used to invoke the constructor of the superclass from within the constructor of the subclass. If the superclass does not have a no-argument constructor, the super() call with appropriate arguments must be made in the subclass constructor to ensure proper initialization of the superclass part of the object.</li></ol><blockquote>Polymorphism:</blockquote><p>Polymorphism in Java refers to the ability of objects of different classes to be treated as objects of a common superclass, allowing methods to be called on them that behave differently based on their specific class implementations. This enables flexibility and code reusability in object-oriented programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NasuOrrVmiovlqjL" /><figcaption>Method Overloading VS Method Overriding</figcaption></figure><blockquote>Encapsulation:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FdMf6lFmWguXWBku" /><figcaption>Encapsulation in Java</figcaption></figure><p>Encapsulation is like a capsule that keeps things safely contained inside. It’s a way to bundle data (like variables) and methods (like functions) together into a single unit called a class in programming. It’s like having a box with a lock on it, where you can only access the contents (data) through the lock (methods). This way, the inner workings (implementation details) of the box are hidden, and you can only interact with it through the provided methods. This helps keep the data safe and organized, making it easier to work with and maintain the code.</p><blockquote>Abstraction: (Hiding implementation, showing functionality)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/0*hY-0DYKvwlYmEkwp" /></figure><p>Abstraction is a process of hiding the implementation details and showing only the essential features to the user. For example, Vehicle is an abstract concept that represents a mode of transportation, while Car, Bike, and Scooter are concrete implementations of the Vehicle with specific features and behaviors. A user interacts with a Vehicle without knowing the internal details of how a Car, Bike, or Scooter works, as long as it provides the essential functionality of transportation.</p><ul><li><em>Abstraction hides details, Encapsulation binds data in a unit.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ymQxqIKoTAM5V4CxPt3iw.png" /><figcaption>Abstract Class VS Interface</figcaption></figure><p>Let’s understand with the help of Examples,</p><p><strong>An abstract class</strong> is like a blueprint or a plan for different types of animals. It defines certain common characteristics or behaviors that all animals of that type should have. For example, you can have an abstract class called “Animal” that defines a method called “makeSound()” but doesn’t provide the implementation (the actual code) for that method. This is because different animals make different sounds, so the implementation needs to be provided by the specific types of animals (like dogs, cats, or birds).</p><p><strong>Now, let’s talk about interfaces.</strong> An interface is like a set of rules or instructions that define a specific behavior or ability. For example, you can have an interface called “Flyable” that defines a method called “fly()”. Any animal that can fly, like a bird or a butterfly, must implement (provide the code for) this “fly()” method.</p><p>Here’s an example to make it more clear:</p><p>Suppose you have a Dog class and a Bird class, both extending the abstract Animal class. The Dog class will provide the implementation (actual code) for the “makeSound()” method by barking, while the Bird class will provide the implementation by chirping or tweeting.</p><p>Additionally, the Bird class can implement the “Flyable” interface, which means it must provide the implementation for the “fly()” method, allowing birds to fly.</p><p>But what if you have a Penguin class that extends the Animal class? Penguins can’t fly, so they don’t need to implement the “Flyable” interface. However, they can still extend the Animal class and provide their own implementation for the “makeSound()” method, perhaps by squawking.</p><p>This way, abstract classes and interfaces help us organize different types of animals based on their common characteristics and abilities, making it easier to understand and work with them.</p><blockquote>Java Package:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*9QMb6VhQ7XALV8Yh" /><figcaption>Java Packages</figcaption></figure><p>Let’s go through some of the packages:</p><ol><li>java.lang: This is a core package that is automatically imported in every Java program. It contains fundamental classes like Object (the root class for all Java classes), String, Math (for mathematical operations), and wrapper classes like Integer, Double, etc.</li><li>java.util: This package provides utility classes for data structures, collections, date and time handling, random number generation, and more. It includes classes like ArrayList, HashMap, Date, Random, etc.</li><li>java.awt: This package provides classes for creating graphical user interfaces (GUIs) and for basic graphics operations. It includes classes like Button, Canvas, Frame, Label, etc. However, the awt package has been largely replaced by the swing package in modern Java development.</li><li>java.swing: This package is an extension of the awt package and provides a more sophisticated and flexible set of GUI components. It includes classes like JButton, JFrame, JPanel, JTextField, etc.</li><li>java.io: This package provides classes for input and output operations, such as reading and writing files, handling streams of data, and more. It includes classes like File, InputStream, OutputStream, Reader, etc.</li></ol><p>There are many more packages in Java, such as java.net for networking, java.sql for database connectivity, java.security for security-related operations, and so on.</p><p>Additionally, you can create your own custom packages to organize your Java classes and interfaces. For example, if you’re building a game, you could have a package called com.example.game that contains all the classes related to your game.</p><blockquote>Exception Handling:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*s-AMs7zf_bvsFoVf" /><figcaption>Exception Handling in Java</figcaption></figure><p>Exception handling in Java is a mechanism that allows you to handle errors or exceptional situations that occur during the execution of a program. When an exceptional situation occurs, Java raises an exception object that contains information about the error. Your program can then catch and handle these exceptions using try-catch blocks. The code that might raise an exception is placed inside the try block, and the corresponding catch block(s) handle the specific types of exceptions that might be thrown. This way, your program can gracefully handle errors and continue running instead of abruptly terminating. Exception handling allows you to write robust and reliable code by anticipating and handling potential errors in a controlled and organized manner.</p><h4>Exception Propagation:</h4><p>Imagine you’re in a big office building with multiple floors. You’re on the ground floor, and you need to deliver a package to someone on the 5th floor. You can’t directly go to the 5th floor because there’s no direct access. So, you start from the ground floor and go up to the 1st floor. If someone on the 1st floor can’t receive the package, the package is passed (or propagated) to the 2nd floor. This process continues until the package reaches the 5th floor, where someone can finally receive it.</p><p>Similarly, in Java, when an exception occurs in a method, and that method doesn’t handle the exception, the exception is propagated (or passed) to the method that called it. If that method also doesn’t handle the exception, it’s propagated further up the call stack until either a method handles the exception or the program terminates if no method handles it.</p><p>Here’s a simple example:</p><pre>public static void main(String[] args) {<br>    try {<br>        method1();<br>    } catch (Exception e) {<br>        System.out.println(&quot;Exception caught in main()&quot;);<br>    }<br>}<br><br>public static void method1() {<br>    method2();<br>}<br><br>public static void method2() {<br>    throw new RuntimeException(&quot;Something went wrong!&quot;);<br>}</pre><p>In this example, `method2()` throws a `RuntimeException`. Since `method2()` doesn’t handle the exception, it propagates to `method1()`. `method1()` also doesn’t handle the exception, so it propagates further up to `main()`. Finally, `main()` catches the exception and prints the message.</p><p>So, the exception propagates from the bottom of the call stack (`method2()`) to the top (`main()`), until it’s caught and handled by a suitable `catch` block.</p><blockquote>String Handling:</blockquote><p><em>Strings are Immutable</em></p><p>Imagine a string as a row of blocks, where each block represents a character. For example, the string “HELLO” would be represented as:</p><p>| H | E | L | L | O |</p><p>Once this row of blocks is created, it cannot be changed. You cannot remove, replace, or rearrange the blocks inside.</p><p>If you want a different string, like “WORLD”, Java creates a completely new row of blocks:</p><p>| W | O | R | L | D |</p><p>This new row is separate from the original “HELLO” string. You cannot modify the original string; you can only create a new one.</p><p>Strings are immutable in Java for efficiency and security reasons. By not allowing changes, Java can share the same string values across your program, saving memory and avoiding potential bugs caused by unintended modifications.</p><p>Think of strings as fixed, unchangeable rows of blocks, and you’ll understand why they are immutable in Java.</p><h4>String Pool:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2SrWNIB2BKxka_DH" /><figcaption>String Pool : Java</figcaption></figure><p>The String pool is a special area in the memory (heap) where Java stores and reuses string literals. When you create a new string literal like `”Hello”`, Java first checks if an identical string already exists in the pool. If it does, Java returns a reference to the existing string object instead of creating a new one. This process is called “interning” strings.</p><p>The String pool helps in memory optimization by sharing string literals across the application, reducing the memory footprint and improving execution speed. However, strings created using the `new` operator or string concatenation are not added to the pool and are allocated directly on the heap.</p><p>String str1 = “Hello”; // Retrieves the string from the pool</p><p>String str2 = “Hello”; // Returns a reference to the same object</p><p>String str3 = “World”; // Creates new string object if not already created.</p><p>String str4 = new String(“Hello”); // Creates a new string object outside the pool.</p><p>So, whenever you use a string literal in your code, Java checks the String pool first to see if it can reuse an existing string object, rather than creating a new one every time.</p><h4>StringBuilder VS StringBuffer:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3VbWsWIjm3x-7mTmFHVCg.png" /></figure><blockquote>Garbage Collection:</blockquote><p>Imagine your room is like the computer’s memory, and your toys are like objects created by a Java program. When you’re done playing with a toy, you leave it on the floor (like an unused object taking up memory).</p><p>In C/C++, you have to manually put each toy back in the toy box (deallocate memory for unused objects) when you’re done with it. If you forget to do this, your room (memory) gets cluttered with toys (objects) you don’t need anymore.</p><p>But in Java, there’s a friendly robot (the Garbage Collector) that comes into your room regularly and automatically picks up all the toys (objects) you’re not using anymore and puts them back in the toy box (frees up memory).</p><p>The Garbage Collector (friendly robot) automatically cleans up your room (memory) by putting unused toys (objects) back in the toy box (freeing up memory). This makes it easier to keep your room (memory) tidy without having to manually put away each toy (deallocate memory for each object) like in C/C++.</p><p>In Java, you can also call `<em>System.gc()</em>` to ask the friendly robot to come and clean up your room (run the Garbage Collector), but it might not come immediately.</p><p>So, Java’s Garbage Collection helps manage memory better by automatically cleaning up unused objects, making it easier for programmers (and kids!) to keep their “rooms” (memory) tidy.</p><h4>finalize()</h4><p><em>(Last minute goodbye before an object’s cleanup)</em></p><p>The `finalize()` method is called by the Garbage Collector before an object is removed from memory. It allows for cleanup operations on objects that the Garbage Collector will collect. Note that `finalize()` is called only once for an object.</p><p>Key Points:</p><p>- The Garbage Collector only cleans objects created using the `new` keyword.</p><p>- `finalize()` provides a mechanism to perform cleanup on objects that are about to be garbage collected.</p><p>- The Garbage Collector runs as a daemon thread in the background.</p><p>However, relying on `finalize()` is generally discouraged due to unpredictability and performance costs. Instead, try-with-resources and explicit cleanup methods are preferred for managing resources.</p><blockquote>Serialization &amp; Deserialization</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g1uDsgwVVGIdxZpI" /><figcaption>Serialization in Java</figcaption></figure><p><strong>Key Points:</strong></p><p>1. <strong>Serialization</strong>:<br>- Converts an object into a byte stream.<br>- Used for saving objects to files, sending over a network, etc.</p><p>2. <strong>Deserialization</strong>:<br>- Converts a byte stream back into an object.</p><p><strong>Making a Class Serializable:<br></strong>- Implement the `Serializable` interface.</p><pre>class Photo implements Serializable {<br>      private static final long UID = 2;<br>      // class code<br>}</pre><ul><li>Serializable Interface: A marker interface (no methods to implement) to indicate that a class can be serialized.</li><li>Inheritance: <br>- If a base class implements `Serializable`, all its subclasses are serializable. <br>- To make a subclass non-serializable, implement `writeObject()` and `readObject()` methods to throw `NotSerializableException`.</li></ul><p><strong>Transient Keyword:</strong> Fields marked with `transient` are not serialized.</p><pre>class Photo implements Serializable {<br>      private transient int id;<br>      private String name;<br>      // class code<br>  }</pre><p><strong>Externalizable Interface: </strong>Not a marker interface. Requires implementing `writeExternal()` and `readExternal()` methods.</p><pre> class Photo implements Externalizable {<br>      private int id;<br>      private String name;<br><br>      public void writeExternal(ObjectOutput out) throws IOException {<br>          out.writeInt(id);<br>          out.writeObject(name);<br>      }<br><br>      public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<br>          id = in.readInt();<br>          name = (String) in.readObject();<br>      }<br>  }</pre><p>So that’s about it, understanding the basics of Java is really important for everyone. Whether we’re getting ready for an interview or just trying to get better at coding, knowing these basic things about Java is really helpful. I tried to put this in the simplest way possible, it might not be at much depth, but will surely give an idea and help understand the concept. So, let’s keep exploring and practicing Java, and we’ll keep getting better at it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cf2941128cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>