<?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 Himanshu Papola on Medium]]></title>
        <description><![CDATA[Stories by Himanshu Papola on Medium]]></description>
        <link>https://medium.com/@himanshupapola?source=rss-3f8413f87d59------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KwgVWyao1yyIEZhpq_AN3A.jpeg</url>
            <title>Stories by Himanshu Papola on Medium</title>
            <link>https://medium.com/@himanshupapola?source=rss-3f8413f87d59------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:31:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@himanshupapola/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[Testing in SpringBoot]]></title>
            <link>https://medium.com/@himanshupapola/testing-in-springboot-aaee809e499b?source=rss-3f8413f87d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaee809e499b</guid>
            <dc:creator><![CDATA[Himanshu Papola]]></dc:creator>
            <pubDate>Sat, 02 May 2026 14:17:46 GMT</pubDate>
            <atom:updated>2026-05-02T14:17:46.347Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Boot provides a comprehensive testing framework that allows developers to write unit tests, integration tests, and end-to-end tests with minimal configuration. It leverages popular libraries like <strong>JUnit</strong>, <strong>Mockito</strong>, and <strong>Spring Test</strong> to help ensure that each component of your application works as expected.</p><p>One of the key advantages of Spring Boot testing is its ability to load only the required parts of the application context. This makes tests faster and more focused. Annotations such as @SpringBootTest, @WebMvcTest, and @DataJpaTest allow developers to test specific layers like controllers, services, or repositories independently.</p><h3>Introduction to JUnit</h3><p>JUnit is one of the most popular testing frameworks in Java, widely used for writing and running automated tests. It plays a key role in ensuring that individual units of code (such as methods or classes) work as expected.</p><p>In modern Spring Boot applications, <strong>JUnit 5</strong> is the standard testing framework. It provides a simple and powerful way to create test cases using annotations and assertions.</p><p>Here are the <strong>most important annotations in JUnit (mainly JUnit 5)</strong>:</p><p><strong>1. </strong><strong>@Test</strong></p><p>Marks a method as a test case.</p><pre>@Test<br>void testAddition() {<br>    assertEquals(5, 2 + 3);<br>}</pre><p><strong>2. </strong><strong>@BeforeEach</strong></p><p>Runs <strong>before every test method</strong>. Used for setup (e.g., initializing objects)</p><pre>@BeforeEach<br>void setUp() {<br>    System.out.println(&quot;Before each test&quot;);<br>}</pre><p><strong>3. </strong><strong>@AfterEach</strong></p><p>Runs <strong>after every test method</strong>. Used for cleanup</p><pre>@AfterEach<br>void tearDown() {<br>    System.out.println(&quot;After each test&quot;);<br>}</pre><p><strong>4. </strong><strong>@BeforeAll</strong></p><p>Runs <strong>once before all tests</strong> (must be static)</p><pre>@BeforeAll<br>static void initAll() {<br>    System.out.println(&quot;Before all tests&quot;);<br>}</pre><p><strong>5. </strong><strong>@AfterAll</strong></p><p>Runs <strong>once after all tests</strong> (must be static)</p><pre>@AfterAll<br>static void tearDownAll() {<br>    System.out.println(&quot;After all tests&quot;);</pre><p><strong>6. </strong><strong>@Disabled</strong></p><p>Skips a test</p><pre>@Disabled(&quot;Not ready yet&quot;)<br>@Test<br>void skippedTest() {<br>}</pre><p><strong>7. </strong><strong>@DisplayName</strong></p><p>Gives a custom name to test</p><pre>@Test<br>@DisplayName(&quot;Test addition of two numbers&quot;)<br>void testAdd() {<br>}</pre><p><strong>8. </strong><strong>@Nested</strong></p><p>Used for grouping related tests inside a class</p><pre>@Nested<br>class AdditionTests {<br>    @Test<br>    void testPositiveNumbers() {<br>    }<br>}</pre><p><strong>9. </strong><strong>@Tag</strong></p><p>Used to categorize tests (like grouping)</p><pre>@Test<br>@Tag(&quot;fast&quot;)<br>void fastTest() {<br>}</pre><p><strong>10. </strong><strong>@ParameterizedTest</strong></p><p>Runs same test with different inputs</p><pre>@ParameterizedTest<br>@ValueSource(ints = {1, 2, 3})<br>void testNumbers(int num) {<br>    assertTrue(num &gt; 0);<br>}</pre><p>JUnit is often used with <strong><em>AssertJ</em></strong>, which is a fluent assertion library for Java. It makes test assertions more readable and provider with much more options for assertion compared to traditional assert.</p><p><strong>11. </strong><strong>Basic Assertion (<em>AssertJ)</em></strong></p><pre>Assertions.assertThat(1)<br>          .isEqualTo(1);<br><br>Assertions.assertThatThrownBy(() -&gt; {<br>    int x = 10 / 0;<br>}).isInstanceOf(ArithmeticException.class);<br><br>Assertions.assertThat(list).hasSize(3)<br>                            .contains(&quot;A&quot;,&quot;B&quot;);</pre><h3><strong>Unit Testing VS Integration Testing</strong></h3><p><strong>A. Unit Testing:</strong></p><p>A unit testing covers a single unit where a unit commonly is a single class, but can also be a cluster of cohesive classes that is tested in combination.</p><p>It’s test individual components, such as methods in service class. We use JUnit and Mockito for this.</p><p><strong>B. Integration Testing:</strong></p><p>A test that covers mutliple layesr. This might cover the intrecation between service and the persistence layer instance.</p><p>It focus on interaction between multiple comp`onents. We use tools like @SpringBootTest in this.</p><p><strong><em>Key Annotations in SpringBoot:</em></strong></p><p><strong>A. @SpringBootTest:</strong> Used to create an application context and load the full application for integration test.</p><p><strong>B. @DataJpaTest: </strong>Used to test JPA repo, configuring an in-memory database for the test. Userful in unit testing service layer and persistence layer. Test Repository layer.</p><p><strong>C. @TestConfiguration: </strong>Used to defnie extra bean or configuration for tests.</p><p><strong>D. @WebMVCTest:</strong> Used for testing Spring MVC controllers. It initalizes only the web layer and not the entire context. Useful in Unit Testing controller layer.</p><p><strong>E. @AutoConfigureTestDatabase: </strong>Used to replace the actual database with an embedded database during test.</p><h3>Unit Testing in Practice:</h3><p>Unit testing is the practice of verifying the correctness of the smallest testable parts of an application (units), such as functions, methods, or classes, in isolation from their dependencies. The goal is to ensure that each unit behaves as expected under different conditions.</p><p><strong><em>For example, </em></strong>when testing a component responsible for database interactions, the focus is only on validating data-related operations (like CRUD and custom queries), rather than testing the entire application flow.</p><p>In additon to this we can use <strong><em>Test Container</em></strong> to test database real behaviour.</p><ol><li><strong>Unit Testing Repository Layer:</strong></li></ol><p>The class test whether the EmployeeRepo work correctly, mainly custom methods.</p><pre>@DataJpaTest<br>class EmployeeRepositoryTest {<br><br>    @Autowired<br>    private EmployeeRepository employeeRepository;<br><br>    private Employee employee;<br><br>    @BeforeEach<br>    void setUp() {<br>        employee = Employee.builder()<br>                .id(1L)<br>                .name(&quot;Himanshu&quot;)<br>                .email(&quot;himanshusingh@gmail.com&quot;)<br>                .salary(100L)<br>                .build();<br>    }<br><br>    @Test<br>    void testFindByEmail_whenEmailIsValid_thenReturnEmployee() {<br>        // Arrange, Preparing the test data<br>        employeeRepository.save(employee);<br><br>        // Act, Executing the behavior being tested<br>        List&lt;Employee&gt; employeeList = employeeRepository.findByEmail(employee.getEmail());<br><br>        // Assert, Verifying the result<br>        assertThat(employeeList).isNotNull();<br>        assertThat(employeeList).isNotEmpty();<br>        assertThat(employeeList.getFirst().getEmail()).isEqualTo(employee.getEmail());<br>    }<br><br>    @Test<br>    void testFindByEmail_whenEmailIsNotFound_thenReturnEmptyEmployeeList() {<br>        // Arrange, Given<br>        String email = &quot;notPresent123.aas@gmail.com&quot;;<br><br>        // Act, When<br>        List&lt;Employee&gt; employeeList = employeeRepository.findByEmail(email);<br><br>        // Assert, Then<br>        assertThat(employeeList).isNotNull();<br>        assertThat(employeeList).isEmpty();<br>    }<br>}</pre><h3>Mockito:</h3><p>Simply, Mockito is useful for testing components in isolation without<br>relying on their <strong>actual implementations or external dependencies</strong>.</p><p><strong>Real dependencies like:</strong> Databases, APIs, Other services make tests slow and complex. Mockito replaces them with controlled behavior. It’s mainly used in the service layer to mock repositories and test business logic.</p><h4><strong>Mockito can be used for:</strong></h4><p><strong>A. Mocking:</strong> Mocking means creating a <strong>fake version of a dependency</strong> (like Repository or Mapper). This is done because we don’t want real db calls and real external logic to modify anything.</p><p><strong>Step to create mocks:</strong></p><ol><li>Mockito creates a <strong>fake object of the repository</strong>, and by default its methods return <strong>null (or empty/default values)</strong>.</li></ol><pre>@Mock<br>private EmployeeRepository employeeRepository;</pre><p><strong>B. Stubbing:</strong> Defining the behavior of mock objects when specific<br>methods are called.</p><p><strong>C. Verification: </strong>Checking if certain methods were called on mock<br>objects.</p><p><strong>Mockito Methods:</strong></p><ol><li><strong>Creating Mock</strong><br>with <strong>@Mock</strong> Annotation<br>with Mockito.mock(Classname)</li><li><strong>Stubbing Mock</strong><br><strong>a. when(T methodCall):</strong> Specifies a method call to be stubbed.<br><strong>b. thenReturn(T value):</strong> Sets a return value for a stubbed method call.<br><strong>c. thenThrow(Throwable… throwables):</strong> Throws an exception when a stubbed method call is made.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaee809e499b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Java Concurrency: From Threads to ExecutorService (Complete Guide)]]></title>
            <link>https://medium.com/@himanshupapola/mastering-java-concurrency-from-threads-to-executorservice-complete-guide-df329800acd7?source=rss-3f8413f87d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/df329800acd7</guid>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Himanshu Papola]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 11:20:11 GMT</pubDate>
            <atom:updated>2026-04-29T16:03:33.912Z</atom:updated>
            <content:encoded><![CDATA[<p>If threads always felt confusing… this guide will fix it. We’ll go from absolute basics to real-world concurrency used in backend apps.</p><pre>📚 What we&#39;ll cover:<br><br>🔹 Basics of Concurrency<br>• Process vs Thread (definitions, differences) ✅<br>• Multitasking vs Multithreading (OS vs application level) ✅<br><br>🔹 Thread Fundamentals<br>• Thread lifecycle (New, Runnable, Running, Waiting, Terminated) ✅<br>• Main thread (entry point, execution flow) ✅<br><br>🔹 Creating Threads<br>• Thread class (extends Thread, override run()) ✅<br>• Runnable interface (implements Runnable, preferred approach) ✅<br><br>🔹 Thread Control <br>• sleep() (pause execution) ✅<br>• join() (wait for thread completion) ✅<br>• yield() (hint scheduler) ✅<br>• interrupt() (stop/wakeup thread) ✅<br><br>🔹 Synchronization<br>• Race condition (data inconsistency problem) ✅<br>• Thread safety (safe shared data access) ✅<br>• synchronized methods &amp; blocks (object-level locking) ✅<br><br>🔹 Inter-Thread Communication<br>• wait() (release lock &amp; wait) ✅<br>• notify() / notifyAll() (wake threads) ✅<br>• Producer–Consumer problem (thread coordination)<br><br>🔹 Memory Concepts<br>• volatile keyword (visibility guarantee)<br>• Memory consistency basics (shared variables)<br><br>🔹 Thread Issues<br>• Deadlock (circular waiting)<br>• Thread states &amp; transitions (debugging behavior)<br><br>🔹 Modern Concurrency (Real-World)<br>• ExecutorService (thread pool management)<br>• Thread pools (fixed, cached pools)<br>• submit() vs execute(), shutdown()<br><br>🔹 Callable &amp; Future<br>• Callable (returns result)<br>• Future (async result handling)<br>• get() (blocking result retrieval)<br><br>🔹 CountDownLatch<br>• Thread coordination (wait for multiple tasks)<br>• countDown() &amp; await() usage</pre><h3><strong>1. Basics of Concurrency:</strong></h3><p>Concurrency is one of those foundational concepts in computer science that every developer eventually runs into whether you’re building a web server, a mobile app, or a high-performance data processor. It’s what allows modern systems to feel responsive, handle multiple tasks at once, and make the most of today’s multi-core CPUs.</p><p>In this beginner-friendly blog post, we’ll break down the <strong>basics of concurrency</strong> with crystal-clear explanations.</p><p><strong>A. What exactly Is a Process?</strong></p><p>Think of a <strong>process</strong> as a complete, independent program running on your computer.</p><p><strong><em>A process is an instance of a program in execution. It includes the program’s code, data, open files, and all the resources it needs to run.</em></strong></p><ul><li>It has its <strong>own isolated memory space</strong> (called the address space). This means whatever happens inside one process can’t accidentally mess up another process’s data.</li><li>The operating system (OS) manages processes: it allocates CPU time, memory, and I/O resources to each one.</li></ul><p><strong>Examples:</strong></p><ul><li>Opening Google Chrome → creates a new process.</li><li>Running a Python script → creates a process.</li><li>Starting Microsoft Word → another process.</li></ul><p><strong>B. What Is a Thread?</strong></p><p>A <strong>thread</strong> is often called a “lightweight process.” It lives <em>inside</em> a process.</p><p><strong><em>A thread is the smallest unit of execution within a process. It shares the same memory space and resources as other threads in that process.</em></strong></p><ul><li>Threads are the actual workers that execute code. A single process can have multiple threads running concurrently.</li><li>The OS still schedules threads, but they’re much cheaper to create and switch between than full processes.</li></ul><p><strong>C. What is Multitasking?</strong></p><p><strong><em>Multitasking allows an operating system to run multiple processes simultaneously.</em></strong></p><p>On single-core CPUs, this is done through <strong>time-sharing</strong>, rapidly switching between tasks. On multi-core CPUs, <strong>true parallel execution</strong> occurs, with tasks distributed across cores. The <strong>OS scheduler</strong> balances the load, ensuring efficient and responsive system performance.</p><p>Multitasking is an <strong>OS-level</strong> feature. It’s how your computer (Windows, macOS, Linux) can run Chrome, Spotify, VS Code, and 20 background services <em>at the same time</em> without everything freezing.</p><p><strong>Key point</strong>: Multitasking works with <strong>processes</strong> — each one completely isolated with its own memory space.</p><p><strong>D. What is Multithreading?</strong></p><p><strong><em>Multithreading is the ability of a single process to execute multiple threads concurrently.</em></strong></p><p>While multitasking manages many separate programs, multithreading lets <strong>one program</strong> split its work into multiple lightweight threads that share the same memory and resources.</p><p>Multithreading is an <strong>application-level</strong> technique. It’s what makes your web browser feel snappy — one thread downloads images while another renders the page, all inside the <em>same</em> Chrome process.</p><p><strong>Key point</strong>: Threads are fast and cheap, but they share everything — so developers must handle synchronization carefully (locks, queues, etc.)</p><p><strong>Example:</strong></p><p><em>A process is a running instance of a program, such as Spotify or VLC. Each process operates independently and has its own memory space. When multiple applications like Spotify and VLC run together, it is called multiprocessing (or multitasking).</em></p><p><em>A thread, on the other hand, is a smaller unit of execution within a process. A s ingle process can have multiple threads that share the same memory and work together. For example, in Spotify, different threads handle music playback, network streaming, and user interface simultaneously. This is known as multithreading.</em></p><p><strong>Context Switching (in Multithreading)</strong></p><ul><li>Saves the state of the current thread and loads the next thread’s state (lighter/faster inside the same process).</li><li>Lets multiple threads share the CPU smoothly so one app can run tasks concurrently.</li></ul><p><strong>Time Slicing (in Multithreading)</strong></p><ul><li>Divides CPU time into small quanta so each thread inside a process gets its fair turn.</li><li>Ensures fair CPU sharing among threads, preventing any single thread from blocking the app.</li></ul><h3><strong>Java Threads:</strong></h3><p>When you run a Java program, it doesn’t just execute line by line randomly, it runs inside something called a <strong>thread</strong>.</p><p>Think of a thread like a worker inside your program. One program can have multiple workers doing different tasks at the same time.</p><h4>A. Thread Fundamentals</h4><p>Before creating threads, you need to understand how they behave.</p><h4>1. Thread Lifecycle</h4><p>A thread doesn’t just start and end instantly — it goes through multiple states:</p><h4>🟢 New</h4><ul><li>Thread is created but not started yet</li><li>Example: new Thread()</li></ul><h4>🟡 Runnable</h4><ul><li>Thread is ready to run and waiting for CPU</li><li>After calling .start()</li></ul><h4>🔵 Running</h4><ul><li>Thread is actively executing code</li><li>CPU has given it time to run</li></ul><h4>🟠 Waiting / Blocked</h4><ul><li>Thread is paused temporarily</li><li>Happens when:</li><li>sleep()</li><li>wait()</li><li>waiting for I/O</li></ul><h4>🔴 Terminated</h4><ul><li>Thread has finished execution</li><li>run() method is complete</li></ul><p>👉 Flow looks like:</p><pre>New → Runnable → Running → Waiting → Running → Terminated<br><br>class ThreadLifeCycle extends Thread {<br>  @Override<br>  public void run() {<br>        // 4. Running<br>        System.out.println(&quot;Running&quot;);<br>        try {<br>            Thread.sleep(1000);<br>        }  catch (InterruptedException e) {<br>            System.out.println(&quot;ThreadLifeCycle Interrupted&quot;);<br>        }<br>  }<br>}<br><br>ThreadLifeCycle t1 = new ThreadLifeCycle(); <br>System.out.println(t1.getState()); // 1. New<br>t1.start(); <br>System.out.println(t1.getState()); // 2. Runnable<br>Thread.sleep(100);<br>System.out.println(t1.getState()); // 3. Blocked - Waiting<br>t1.join();<br>System.out.println(t1.getState()); // 5. Terminated</pre><h4>2. Main Thread (Entry Point)</h4><p>Every Java program starts with a <strong>main thread</strong>.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello World&quot;);<br>    }<br>}</pre><ul><li>main() method runs inside the <strong>main thread</strong></li><li>It is the <strong>first thread created automatically</strong></li><li>All other threads are created from it</li></ul><blockquote><em>Main thread = boss → creates worker threads</em></blockquote><h4><strong>B. Creating Threads</strong></h4><p>In Java, there are <strong>two main ways</strong> to create threads:</p><ol><li><strong>Using Thread Class (extends Thread) :</strong></li></ol><p>You create a class that <strong>extends </strong><strong>Thread</strong> and override the run() method.</p><pre>class Creating_Thread_1 extends Thread {<br>    @Override<br>    public void run() {<br>        System.out.println(&quot;Creating Thread By Extending Thread Class&quot;);<br>        System.out.println(Thread.currentThread().getName());<br>    }<br>}<br><br>Creating_Thread_1 obj = new Creating_Thread_1();<br>obj.start();</pre><p>When we call <strong>start() </strong>Java<strong> :</strong></p><p>a. Creates a <strong>new thread in JVM</strong></p><p>b. Calls run() inside that new thread</p><p>Extending thread class is generally a bad practice as we are don’t have multiple inheritance in Java and it’s a bad design.</p><p><strong>2. Using Runnable Interface :</strong></p><p>You create a class that <strong>implements </strong><strong>Runnable</strong>, and pass it to a Thread.</p><pre>class Creating_Thread_2 implements Runnable {<br>    @Override<br>    public void run() {<br>        System.out.println(&quot;Creating Thread By Implementing Runnable Interface&quot;);<br>    }<br>}<br><br>Creating_Thread_2 obj2 = new Creating_Thread_2();<br>Thread t1 = new Thread(obj2);<br>t1.start();</pre><h4>C. Thread Methods</h4><pre><br>// 1. Thread Methods<br>class ThreadMethods implements Runnable {<br>    @Override<br>    public void run() {<br>        System.out.println(&quot;Thread Methods&quot;);<br>        try {<br>            // 2nd Method (Waiting Thread)<br>            Thread.sleep(1000);<br>        } catch (InterruptedException e) {<br>            System.out.println(&quot;Thread Interrupted&quot;);<br>        }<br>    }<br>}<br><br>public class A01_Thread_Methods {<br><br>    public  static void main(String[] args) throws InterruptedException {<br>        ThreadMethods thread = new ThreadMethods();<br>        Thread t2 = new Thread(thread);<br>        <br>        // 1st Method (Starting a thread)<br>        t2.start();<br>        <br>        // 3rd Method (Main will wait for t2 Thread to be terminated, we can also tell time)<br>        t2.join();<br>        <br>        // 4th (Getting State)<br>        System.out.println(t2.getState());<br>        <br>        // 5th (Setting Name)<br>        t2.setName(&quot;Thread Methods&quot;);<br>        <br>        <br>        // 6th (Thread Prority)<br>        t1.setPriority(Thread.MAX_PRIORITY);<br>        t2.setPriority(Thread.MIN_PRIORITY);<br>        t3.setPriority(Thread.NORM_PRIORITY);<br>    }<br>}</pre><pre>// 2. Thread Yield and Priority<br>class Thread_Interrupt implements Runnable {<br>    @Override<br>    public void run() {<br><br>        // interrupt does NOT stop this loop automatically<br>        for (int i = 0; i &lt; 3; i++) {<br>            System.out.println(Thread.currentThread().getName() + &quot; is running&quot;);<br>            Thread.yield(); // just a hint, may be ignored<br>        }<br><br>        try {<br>            // interrupt affects here → throws exception if flag is set<br>            Thread.sleep(1000);<br>        } catch (InterruptedException e) {<br>            System.out.println(e.getMessage());<br>        }<br>    }<br>}<br><br>public class A03_Thread_Interrupt {<br>    public static void main(String[] args) {<br><br>        Thread_Interrupt task = new Thread_Interrupt();<br><br>        Thread t1 = new Thread(task);<br>        t1.start();<br>        t1.interrupt(); // sets interrupt flag (doesn&#39;t stop immediately)<br><br>        new Thread(task).start();<br>        new Thread(task).start();<br>    }<br>}</pre><h4>D. Synchronization</h4><p>When multiple threads work on the <strong>same data</strong>, problems can happen if they change it at the same time. That is why Java gives us <strong>synchronization</strong>.</p><p>Synchronization is used to: avoid race conditions, keep data consistent, make shared data thread-safe.</p><p><strong>Thread Safety: </strong>A code or object is <strong>thread-safe</strong> if multiple threads can use it safely without causing wrong results. So if many threads access shared data and still the result stays correct, then it is thread-safe.</p><p><strong>Race Condition:</strong> happens when two or more threads access the same variable, at least one thread modifies it, final result becomes unpredictable</p><p>Let’s understand this better with code:</p><pre>// Let&#39;s say we have counter<br><br>public class A01__Counter {<br>    int count = 0;<br><br>    public void increment() {<br>        count++;<br>    }<br><br>    public int getCount() {<br>        return count;<br>    }<br><br>}<br><br>// We have three thread that do action on these counter<br>public class A01_Synchronization {<br>    public static void main(String[] args) throws InterruptedException {<br><br>        A01__Counter counter = new A01__Counter();<br><br>        // Thread 1<br>        Thread t1 = new Thread(() -&gt; {<br>            for (int i = 1; i &lt;= 1000; i++) {<br>                counter.increment();<br>            }<br>        });<br><br>        // Thread 2<br>        Thread t2 = new Thread(() -&gt; {<br>            for (int i = 1; i &lt;= 1000; i++) {<br>                counter.increment();<br>            }<br>        });<br><br>        // Thread 3<br>        Thread t3 = new Thread(() -&gt; {<br>            for (int i = 1; i &lt;= 1000; i++) {<br>                counter.increment();<br>            }<br>        });<br><br>        t1.start();<br>        t2.start();<br>        t3.start();<br><br>        t1.join();<br>        t2.join();<br>        t3.join();<br><br>        // Expected = 3000<br>        // Actual = Any random even less then 3000, 2321, 1322, 2422<br>        System.out.println(counter.getCount());<br><br>    }<br>}</pre><p>Why this happens? Why does count is not 3000?</p><p>Because count++ is <strong>not one single step</strong>. It actually happens in 3 steps:</p><ol><li>read current value of count</li><li>add 1</li><li>write back new value</li></ol><p>So if two threads do this together:</p><ul><li>Thread 1 reads 5</li><li>Thread 2 reads 5</li><li>Thread 1 writes 6</li><li>Thread 2 writes 6</li></ul><p>Now one update is lost. This is called a <strong>race condition</strong>.</p><p>Let’s fix this issue using <strong>synchronized </strong>keyword. It allows <strong>only one thread at a time</strong> to enter a critical section. A <strong>critical section</strong> means the part of code where shared data is modified.</p><pre>class Counter {<br>    int count = 0;<br><br>    // If a method is marked synchronized, then a thread must get the lock before entering it.<br>    synchronized void increment() {<br>        count++;<br>    }<br>    //Now if one thread is inside increment(), another thread must wait.<br>}</pre><pre>// Instead of Synchronize whole method we can sync only block<br>synchronized(lockObject) {<br>    // critical section<br>}</pre><pre>🔹 Inter-Thread Communication<br>• wait() (release lock &amp; wait)<br>• notify() / notifyAll() (wake threads)<br>• Producer–Consumer problem (thread coordination)</pre><p><strong>E. Inter-Thread Communication:</strong></p><p>When multiple threads work on the same data, they need to coordinate so they don’t cause inconsistency. Instead of repeatedly checking a condition (busy waiting), Java provides inter-thread communication using methods like wait(), notify(), and notifyAll().</p><p>Inter-thread communication allows one thread to pause its execution using wait() until another thread signals it using notify() or notifyAll() when a condition becomes true.</p><p>These methods work only when a thread holds a lock on the object. <strong><em>When we use </em></strong><strong><em>synchronized, we are already using an intrinsic lock (monitor lock) provided by Java, which makes this communication possible.</em></strong></p><p>While synchronized provides an intrinsic (automatic) lock, Java also offers <strong>manual locking mechanisms</strong> through the Lock interface in java.util.concurrent.locks, such as ReentrantLock.</p><p>In this approach, the programmer explicitly controls when to acquire and release the lock using methods like lock(), tryLock(), and unlock(). This provides more flexibility compared to synchronized, such as the ability to try acquiring a lock without blocking or to set a timeout.</p><p>To understand logic of manual locking let’s see the code:</p><pre>public class Locks {<br>    // We have balance with 100 Rs<br>    private int balance = 100;<br><br>    // Withdraw method that withdraw money and tell remains <br>    public void withdraw(int amount) {<br>        System.out.println(Thread.currentThread().getName() + &quot; attempting to withdraw &quot; + amount);<br><br>        if (balance &gt;= amount) {<br>            System.out.println(Thread.currentThread().getName() + &quot; proceeding with withdrawal &quot;);<br><br>            try {<br>                Thread.sleep(1000); // simulate delay<br>            } catch (InterruptedException e) {}<br><br>            balance -= amount;<br>            System.out.println(Thread.currentThread().getName() + &quot; Remains &quot; + balance);<br>        } else {<br>            System.out.println(Thread.currentThread().getName() + &quot; cannot withdraw &quot;);<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        Locks bankAccount = new Locks();<br><br>        Runnable task = () -&gt; bankAccount.withdraw(50);<br><br>        Thread t1 = new Thread(task, &quot;Thread 1&quot;);<br>        Thread t2 = new Thread(task, &quot;Thread 2&quot;);<br><br>        t1.start();<br>        t2.start();<br>    }<br>}</pre><pre>Thread 1: checks balance → sees 100 ✅<br>Thread 2: checks balance → also sees 100 ✅<br><br>Thread 1: sleeps<br>Thread 2: sleeps<br><br>Thread 1: subtracts → 50<br>Thread 2: subtracts → also thinks 100 → makes it 50 ❌<br><br>Both threads access and modify shared data without synchronization, <br>leading to a race condition where they operate on stale values.<br><br>Now there are two solution to this problem:<br>1. Synchronized<br>2. ReentrantLock</pre><p><strong>Solution: We use ReentrantLock to control locking manually</strong></p><pre>// 🔐 Creating the Lock<br>private final Lock lock = new ReentrantLock();<br><br>public void withdraw(int amount) {<br>        lock.lock();<br>        try {<br>            System.out.println(Thread.currentThread().getName() + &quot; trying to withdraw &quot; + amount);<br><br>            if (balance &gt;= amount) {<br>                balance -= amount;<br>                System.out.println(Thread.currentThread().getName() +<br>                        &quot; withdrew. Remaining: &quot; + balance);<br>            } else {<br>                System.out.println(Thread.currentThread().getName() +<br>                        &quot; insufficient balance! Current: &quot; + balance);<br>            }<br><br>        } finally {<br>            lock.unlock();<br>        }<br>}<br><br>public static void main(String[] args) {<br>        Lock_Actions bank = new Lock_Actions();<br><br>        Thread t1 = new Thread(() -&gt; bank.withdraw(80), &quot;Thread 1&quot;);<br>        Thread t2 = new Thread(() -&gt; bank.withdraw(80), &quot;Thread 2&quot;);<br><br>        t1.start();<br>        t2.start();<br>}</pre><h4>E. Thread Pool:</h4><p>If you create a new thread for every task:</p><ul><li>🧠 High memory usage</li><li>⏳ Time wasted creating/destroying threads</li><li>🚫 Too many threads → system slowdown (context switching overhead)</li></ul><p><strong>What is a Thread Pool?</strong></p><p>A <strong>thread pool</strong> is a collection of pre-created threads that are reused to execute tasks. Instead of:</p><ul><li>Creating a new thread every time</li><li>We Submit tasks to a pool</li><li>Available threads pick up tasks and execute them</li></ul><p><strong>How It Works?</strong></p><ol><li>Thread pool creates a fixed number of threads (say 5)</li><li>Tasks are placed in a queue</li><li>Threads pick tasks from the queue</li><li>After finishing, threads go back to the pool (not destroyed)</li></ol><p><strong><em>We use the Executor Framework to manage thread pools.</em></strong></p><pre>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br><br>public class Main {<br>    public static void main(String[] args) {<br><br>        // Create a thread pool with 5 threads<br>        ExecutorService executor = Executors.newFixedThreadPool(5);<br><br>        for (int i = 1; i &lt;= 5; i++) {<br>            int taskId = i;<br><br>            // Submit tasks to thread pool<br>            executor.execute(() -&gt; {<br>                System.out.println(<br>                    &quot;Task &quot; + taskId + &quot; is executed by &quot; +<br>                    Thread.currentThread().getName()<br>                );<br>            });<br>        }<br><br>        // Shutdown the executor<br>        executor.shutdown();<br>    }<br>}</pre><p>The given Java program demonstrates how to use the <strong>Executor Framework</strong> to manage threads efficiently using a thread pool. Instead of manually creating threads, the program uses an ExecutorService, which is a high-level API provided in the java.util.concurrent package. This simplifies thread management by handling thread creation, reuse, and task execution internally.</p><p>In the program, a <strong>fixed thread pool of size 5</strong> is created using Executors.newFixedThreadPool(5). This means that at most five threads will be active at any given time. These threads are created once and reused for multiple tasks, which improves performance by avoiding the overhead of repeatedly creating and destroying threads.</p><p>A loop is used to submit five tasks to the executor. Each task is defined using a lambda expression that implements the Runnable interface. Inside the loop, a separate variable taskId is created to hold the value of the loop counter because lambda expressions require variables to be effectively final. Each submitted task simply prints a message indicating which task is being executed and by which thread.</p><p>The execute() method is used to submit tasks to the thread pool. Once submitted, the executor assigns each task to an available thread. If all threads are busy, additional tasks are placed in a queue and executed when a thread becomes free. This ensures efficient utilization of system resources.</p><p>Finally, the shutdown() method is called to stop the executor from accepting new tasks while allowing already submitted tasks to complete execution. This is an important step to properly release resources and avoid memory leaks.</p><p>Overall, this program shows how the <strong>Executor Framework abstracts the complexity of thread management</strong> by allowing developers to focus only on defining tasks, while the framework efficiently handles their execution using a thread pool.</p><h4>Callable Future</h4><pre>import java.util.concurrent.*;<br><br>public class Main {<br>    public static void main(String[] args) throws Exception {<br><br>        ExecutorService executor = Executors.newFixedThreadPool(2);<br><br>        Callable&lt;Integer&gt; task = () -&gt; {<br>            Thread.sleep(1000); // simulate work<br>            return 100;<br>        };<br><br>        Future&lt;Integer&gt; future = executor.submit(task);<br><br>        System.out.println(&quot;Task submitted...&quot;);<br><br>        Integer result = future.get(); // waits for result<br><br>        System.out.println(&quot;Result: &quot; + result);<br><br>        executor.shutdown();<br>    }<br>}</pre><p>In this example, a <strong>Callable</strong> task is defined using a lambda expression. Unlike Runnable, which does not return any value, Callable is designed to perform a computation and return a result. Here, the task simulates work by pausing for one second using Thread.sleep(1000) and then returns the value 100. This makes Callable useful when a background task needs to produce a result.</p><h4>submit() Method</h4><p>The task is submitted to the executor using the submit() method. This is important because, unlike execute(), the submit() method returns a Future object. When submit() is called, the task starts executing in a separate thread from the pool, while the main thread continues its execution independently.</p><h4>Future</h4><p>The <strong>Future</strong> object acts as a placeholder for the result of the asynchronous computation. It does not contain the result immediately but represents a value that will be available later once the task completes.</p><h4>future.get()</h4><p>After submitting the task, the program prints &quot;Task submitted…&quot;, showing that the main thread does not wait initially. However, when future.get() is called, the main thread pauses and waits until the background task finishes execution. Once completed, it retrieves the result (100). This shows how Future helps in synchronizing asynchronous tasks when the result is required.</p><h4>shutdown()</h4><p>Finally, the shutdown() method is called on the executor. This stops the executor from accepting new tasks and ensures that all previously submitted tasks are completed before the program terminates. It is an important step for proper resource management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df329800acd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Types in Javascript]]></title>
            <link>https://medium.com/@himanshupapola/data-types-in-javascript-7aed0a9bfc46?source=rss-3f8413f87d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aed0a9bfc46</guid>
            <dc:creator><![CDATA[Himanshu Papola]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 12:38:05 GMT</pubDate>
            <atom:updated>2025-12-06T12:38:05.433Z</atom:updated>
            <content:encoded><![CDATA[<p>When we start working with JavaScript, the first thing we must understand is <strong>data types</strong>. They tell the JavaScript engine <em>what kind of value</em> we are working with. Without data types, we cannot store, compare, or process information properly.</p><p>JavaScript has <strong>two main categories</strong> of data types:</p><ul><li><strong>Primitive Data Types</strong></li><li><strong>Non-Primitive (Reference) Data Types</strong></li></ul><p>Let’s explore each one with examples.</p><h3>1. Primitive Data Types</h3><h4><strong><em>A. Number:</em></strong></h4><p>In JavaScript, <strong>numbers are one of the most important data types</strong>.</p><p>JavaScript uses <strong>64-bit floating-point</strong> representation (IEEE 754), which means: <strong>integers, decimals, negative numbers, scientific notation </strong>all belong to <strong>one single type </strong><strong>number</strong>.</p><pre>// Number<br>let numberInt = 25;<br>let numberFloat = 25.5;<br>let numberNeg = -25;<br>let numerSci = 2.5e6; // 2.5 * 10^6<br>let big = 1234567890123456789012345678901234567890n; // BigInt<br><br>// Methods<br>let numberN = 3.14159;<br>console.log(numberN.toFixed(2)); // &quot;3.14&quot;<br>console.log(numberN.toPrecision(2)); // &quot;3.1&quot;<br>console.log(numberN.toExponential(2)); // &quot;3.14e+0&quot;<br><br>// Type Conversion<br>console.log(parseInt(&quot;100px&quot;)); // 100<br>console.log(parseFloat(&quot;12.5em&quot;)); // 12.5<br>console.log(Number(&quot;123&quot;)); // 123<br>console.log(Number(&quot;12.34&quot;)); // 12.34<br>console.log(Number(&quot;12abc&quot;)); // NaN<br>console.log(String(123)); // &quot;123&quot;<br>console.log(Boolean(1)); // true<br>console.log(Boolean(0)); // false<br><br>console.log(Number.isInteger(numberInt)); // true<br>console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991<br>console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991  <br>console.log(Number.NEGATIVE_INFINITY); // -Infinity<br>console.log(Number.POSITIVE_INFINITY); // Infinity<br>console.log(Number.isNaN(NaN)); // true<br><br>console.log(typeof numberInt); // &quot;number&quot;<br>console.log(numberInt.toString()); // &quot;25&quot;<br><br>console.log(1/0); // Infinity<br>console.log(0/1); // 0<br>console.log(&quot;hello&quot;/2); // NaN<br><br>let numberC = new Number(1);<br>let numberD = new Number(1);<br>console.log(numberC == numberD); // false (because they are objects)<br>console.log(numberC === numberD); // false<br><br>console.log(1 == &quot;1&quot;);<br>console.log(1 === &quot;1&quot;);<br><br>console.log(Math.max(1,2,3,4,5)); // 5<br>console.log(Math.min(1,2,3,4,5)); // 1<br>console.log(Math.floor(Math.random() * (8 - 2 + 1) + 2)); // random number between 2 and 8<br>console.log(Math.round(4.6)); // 5<br>console.log(Math.round(4.4)); // 4<br>console.log(Math.floor(4.9)); // 4<br>console.log(Math.ceil(4.1)); // 5<br>console.log(Math.pow(2,3)); // 8</pre><h4>B. Boolean:</h4><p>A <strong>Boolean</strong> represents only <strong>two values</strong>:</p><ul><li>true, false</li></ul><p>It is used in conditions, comparisons, and logic operations.</p><pre>let isTrue = true;<br>let isFalse = false;<br><br>console.log(typeof isTrue); // boolean<br>console.log(typeof isFalse); // boolean<br><br>// Conversion<br>// Truthy values<br>console.log(Boolean(true)); // true<br>console.log(Boolean(1)); // true<br>console.log(Boolean(&quot;Hello&quot;)); // true<br>console.log(Boolean([])); // true<br>console.log(Boolean({})); // true<br>console.log(Boolean(function() {})); // true<br>console.log(Boolean(-10)); // true <br><br>// Falsy values<br>console.log(Boolean(0)); // false<br>console.log(Boolean(&quot;&quot;)); // false<br>console.log(Boolean(null)); // false<br>console.log(Boolean(undefined)); // false<br>console.log(Boolean(NaN)); // false<br>console.log(false); // false<br><br>// Equality<br>console.log(true == 1); // true<br>console.log(1 &gt; 2); // false<br>console.log(1 == &quot;1&quot;); // true<br>console.log(&quot;1&quot; === true); // false<br><br>// Double NOT operator<br>console.log(!!false); // false<br>console.log(!!0); // false<br><br>// Logical Operators<br>console.log(true &amp;&amp; false); // false<br>console.log(true || false); // true<br>console.log(!true); // false</pre><h4>C. Undefined:</h4><p>undefined is a primitive value in JavaScript. It means <strong>&quot;a variable exists, but no value has been assigned.&quot; </strong>JavaScript itself gives undefined when something has <strong>no value</strong>.</p><pre>// Undefined: variable declared but no value assigned<br>let undefinedX;<br>console.log(undefinedX);            // undefined<br>console.log(typeof undefinedX);     // &quot;undefined&quot;<br><br>// Functions with no return always return undefined<br>function test() {}<br>console.log(test());                // undefined<br>console.log(typeof test());         // &quot;undefined&quot;<br><br>// Missing object property → undefined<br>let obj = { name: &quot;John&quot; };<br>console.log(obj.age);               // undefined<br><br>// Out-of-range array index → undefined<br>let arr = [1, 2, 3];<br>console.log(arr[5]);                // undefined<br><br>// undefined vs null<br>let a = null;   // intentional empty value<br>let b;          // undefined<br>console.log(a == b);   // true  (loose: treats both as empty)<br>console.log(a === b);  // false (different types)<br><br>// undefined is falsy<br>if (undefined) {<br>  console.log(&quot;Won&#39;t print&quot;);<br>}<br><br>// undefined in math → NaN<br>console.log(undefinedX + 5); // NaN</pre><h4>D. Null:</h4><p>In JavaScript, null is a special primitive value that represents an <strong>intentional empty value</strong>. We use it when we <em>want</em> a variable to be empty.</p><p>It is different from <strong>undefined</strong>, which means “value not assigned yet.”</p><pre>// Null — intentional empty value<br>let nullA = null;<br>console.log(nullA); // null<br><br>// typeof null → &quot;object&quot; (a long-standing JavaScript bug)<br>console.log(typeof nullA); // object<br><br>// Equality checks<br>console.log(nullA === null); // true  (same type + value)<br>console.log(nullA == null);  // true  (special rule: null only equals undefined + null)<br><br>// Arithmetic with null<br>console.log(1 + null);       // 1   (null → number 0 in arithmetic)<br>console.log(&quot;Hello&quot; + null); // &quot;Hellonull&quot; (null → string &quot;null&quot; in concatenation)<br>console.log(null == false);  // false (no type coercion toward boolean here)<br><br>// Comparisons with numbers<br>console.log(null &gt; 0);  // false  (null → 0, so 0 &gt; 0 is false)<br>console.log(null &gt;= 0); // true   (0 &gt;= 0 is true)<br>console.log(null &lt; 0);  // false  (0 &lt; 0 is false)<br>console.log(null &lt;= 0); // true   (0 &lt;= 0 is true)<br><br>// Equality with number 0<br>console.log(null == 0);  // false  (special rule: null only equals undefined)<br>console.log(null === 0); // false  (different types)</pre><h4>E. String:</h4><p>In JavaScript, a <strong>string</strong> represents text. Anything written inside <strong>quotes</strong> is treated as a string.</p><pre>let str1 = &quot;Hello, World!&quot;;<br>let str2 = &#39;JavaScript is fun.&#39;;<br>let str3 = `Template literals are powerful! ${str1}`;<br>let str4 = `Template ${1+1}`;<br><br>console.log(str1);<br>console.log(str2);<br>console.log(str3);<br>console.log(str4);<br><br>// Methods<br><br>// Coverting Case<br>console.log(str1.toUpperCase());<br>console.log(str1.toLowerCase());<br><br>// Trimming<br>console.log(str1.trim());<br>console.log(str1.trimStart());<br>console.log(str1.trimEnd());<br><br>// Searching<br>console.log(str1.includes(&quot;World&quot;)); // true<br>console.log(str1.startsWith(&quot;Hello&quot;)); // true<br>console.log(str1.endsWith(&quot;!&quot;)); // true<br><br>// Repeating and Padding<br>console.log(str1.repeat(2)); // &quot;Hello, World!Hello, World!&quot;<br>console.log(str1.padStart(20, &#39;*&#39;)); // &quot;*******Hello, World!&quot;<br>console.log(str1.padEnd(20, &#39;*&#39;)); // &quot;Hello, World!*******&quot;<br><br>// Extracting Characters<br>console.log(str1.charAt(0)); // &quot;J&quot;<br>console.log(str1.at(0)); // &quot;J&quot;<br>console.log(str1[0]); // &quot;J&quot;<br><br>// Extracting Substrings<br>console.log(str1.slice(0, 5)); // &quot;Hello&quot;<br>console.log(str1.slice(0)); // &quot;Hello, World!&quot;<br>console.log(str1.substring(0, 5)); // &quot;Hello&quot;<br>console.log(str1.substring(-1, 5)); // &quot;Hello&quot;<br><br>// Replacing<br>console.log(str1.replace(&quot;World&quot;, &quot;JavaScript&quot;)); // &quot;Hello, JavaScript!&quot;<br>console.log(str1.replaceAll(&quot;l&quot;, &quot;L&quot;)); // &quot;HeLLo, WorLd!&quot;<br><br>// Splitting<br>console.log(str1.split(&quot;, &quot;)); // [&quot;Hello&quot;, &quot;World!&quot;]<br>console.log(str1.split(&quot;&quot;,5)); // [&quot;H&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;]<br>console.log(str1.split(&quot;,&quot;, 2)); // [&quot;Hello&quot;, &quot; World!&quot;]<br><br>// Cocantenation<br>console.log(str1.concat(&quot; &quot;, str2));<br>console.log(str1 + &quot; &quot; + str2);<br>console.log(`${str1} ${str2}`);<br><br>// Join<br>console.log([&quot;Hello&quot;, &quot;World&quot;].join(&quot;, &quot;)); // &quot;Hello, World&quot;<br>console.log([&quot;2023&quot;, &quot;10&quot;, &quot;05&quot;].join(&quot;-&quot;)); // &quot;2023-10-05&quot;<br>console.log(str1.split(&quot;&quot;).join(&quot;-&quot;)); // &quot;H-e-l-l-o-,- -W-o-r-l-d-!&quot;<br><br>// Searching Indexes<br>console.log(str1.indexOf(&quot;o&quot;)); // 4<br>console.log(str1.lastIndexOf(&quot;o&quot;));<br>console.log(str1.indexOf(&quot;o&quot;, 5)); // 8<br><br>// Type Conversion<br>console.log(String(123)); // &quot;123&quot;<br>console.log(String(true)); // &quot;true&quot;<br>console.log(String(null)); // &quot;null&quot;<br>console.log(String(undefined)); // &quot;undefined&quot;<br>console.log(String({key: &quot;value&quot;})); // &quot;[object Object]&quot;<br>console.log(String([1,2,3])); // &quot;1,2,3&quot;<br>console.log(Number(&quot;123&quot;)); // 123<br>console.log(Boolean(&quot;&quot;)); // false<br>console.log(Boolean(&quot;Hello&quot;)); // true</pre><h3>2. Non Primitive Data Types</h3><p>Non-primitives are <strong>objects</strong>. They <strong>store references</strong>, not actual values.</p><h4>1. Object</h4><p>General container that stores data in <strong>key–value</strong> pairs.</p><pre>let user = { name: &quot;Himanshu&quot;, age: 21 };</pre><p>Everything that is not a number, string, boolean, bigint, null, or undefined is an <strong>object</strong>.</p><h4>2. Array</h4><p>Ordered list of values (special kind of object).</p><pre>let arr = [10, 20, 30];</pre><h4>3. Function</h4><p>Functions are also <strong>objects</strong>, but callable.</p><pre>function greet() { console.log(&quot;Hi&quot;); }</pre><h4>4. Date</h4><p>Represents date/time.</p><pre>let d = new Date();</pre><h4>5. RegExp</h4><p>Regular expressions.</p><pre>let pattern = /hello/;</pre><h4>6. Map</h4><p>Key-value pairs (keys can be <em>any</em> type).</p><pre>let m = new Map();<br>m.set(&quot;id&quot;, 1);</pre><h4>7. Set</h4><p>Collection of unique values.</p><pre>let s = new Set([1, 2, 2]);</pre><h3>Ways To Declare Variable:</h3><h4>1. Var:</h4><p>When we write JavaScript, var is the oldest way to declare variables. It’s not recommended to use it.</p><ul><li>Variable declared using varis <strong>Globally-scoped or function-scoped</strong>.</li><li>Var can be redeclared and updated.</li><li>Var variables are hoisted at top but initialized to undefined.</li><li>Var variables don’t respect block scope.</li></ul><pre>if (true) {<br>  var name = &quot;JS&quot;;<br>}<br>console.log(name); // &quot;JS&quot;<br><br>var x = 10;<br>var x = 20; // redeclared — allowed<br>x = 30;     // updated — allowed<br><br>console.log(a); // undefined<br>var a = 5;<br><br>for (var i = 0; i &lt; 3; i++) {}<br>console.log(i); // 3</pre><p><strong>2. Const:</strong></p><p>const was introduced in ES6 (2015) and is used to declare variables that should <strong>not be reassigned</strong>.</p><ul><li>Cannot be <strong>redeclared </strong>or <strong>reassigned.</strong></li><li>const follows <strong>block scope</strong>, meaning it only exists inside { }.</li><li>Value is not constant, the<strong> <em>reference</em> </strong>is constant.</li><li>Use with arrays/objects that won’t change reference.</li></ul><pre>// const → ES6 (2015), cannot reassign or redeclare<br>const x = 10;<br>// x = 20; ❌<br><br><br>// Block scope<br>{<br>  const a = 5;<br>  console.log(a); // 5<br>}<br>// console.log(a); ❌<br><br>// Reference is constant (arrays)<br>const arr = [1, 2, 3];<br>arr.push(4);  <br>// arr = []; ❌<br><br>// Reference is constant (objects)<br>const obj = { name: &quot;A&quot; };<br>obj.name = &quot;B&quot;;<br>// obj = {}; ❌<br><br>// Often used with arrow functions<br>const add = (a, b) =&gt; a + b;<br>console.log(add(2, 3)); // 5</pre><h4><strong>3. let:</strong></h4><ul><li>let was introduced in <strong>ES6 (2015)</strong>.</li><li>Variables declared with let <strong>cannot be redeclared</strong>, but <strong>can be reassigned</strong>.</li><li>let has <strong>block scope</strong> (limited to { }).</li><li>Use let only when we <strong>cannot</strong> use const (i.e., value must change)</li></ul><pre>// let → ES6, cannot redeclare, can reassign<br>let x = 10;<br>x = 20; <br>// let x = 30; //cannot redeclare<br><br><br>// Block scope<br>{<br>  let a = 5;<br>  console.log(a); // 5<br>}<br>// console.log(a); //not accessible outside block<br><br><br>// Reassigning values<br>let count = 1;<br>count = 2; // allowed<br><br><br>// Use let when value needs to change<br>for (let i = 0; i &lt; 3; i++) {<br>  console.log(i);<br>}</pre><p><strong>Hoisiting:</strong></p><p>Variable decleared with let and const are hosited at top but <strong>unlike </strong><strong>var</strong>, they are <strong>not initialized</strong> during hoisting.</p><p>They stay in the TDZ (Temporal Dead Zone) The TDZ is the phase from the <strong>start of the scope</strong> until the <strong>declaration line</strong>. During the TDZ, the variable exists but <strong>cannot be accessed</strong>.</p><p>Accessing let or const before declaration → ReferenceError because the variable is not initialized yet.</p><h3>3. Extra Concepts:</h3><blockquote><strong><em>A. Type Conversion vs Type Coercion in JavaScript</em></strong></blockquote><p>JavaScript handles data types in two ways:</p><ul><li><strong>Type Conversion</strong> → We manually convert the type.</li><li><strong>Type Coercion</strong> → JavaScript automatically converts the type.</li></ul><p>Let’s break both in a very easy way.</p><p><strong>1. Type Conversion (Explicit Conversion)</strong></p><p>We tell JavaScript to convert the value. We use functions like <strong>Number()</strong>, <strong>String()</strong>, <strong>Boolean()</strong>, <strong>parseInt()</strong>, etc.</p><pre>const inputYear = &#39;1991&#39;;<br>console.log(inputYear + 18);            // &#39;199118&#39;  (string + number = string)<br>console.log(Number(inputYear) + 18);    // 2009      (converted to number)<br>console.log(parseInt(inputYear) + 18);  // 2009</pre><h4>2. Type Coercion (Implicit Conversion)</h4><p>JavaScript automatically converts types for us. This happens with <strong>operators</strong>: + - * / ==</p><pre>console.log(&#39;I am &#39; + 23 + &#39; years old&#39;); // &#39;I am 23 years old&#39;<br>console.log(&#39;23&#39; - &#39;10&#39; - 3); // 10<br>console.log(&#39;23&#39; + &#39;10&#39; + 3); // &#39;23103&#39;<br>console.log(&#39;23&#39; * &#39;2&#39;); // 46<br>console.log(&#39;23&#39; / &#39;2&#39;); // 11.5<br><br>let n = &#39;1&#39; + 1; // &#39;11&#39;<br>n = n - 1; // 10</pre><blockquote><strong><em>B. Eqaulity Operator</em></strong></blockquote><p>JavaScript has <strong>two main equality operators. </strong>They look similar but behave very differently.</p><ol><li><strong>Loose Equality → </strong><strong>==</strong></li><li><strong>Strict Equality → </strong><strong>===</strong></li></ol><p><strong>1. Strict Equality (===)</strong></p><p><strong>No type conversion </strong>and both <strong>value and type must match</strong></p><pre>console.log(18 === 18);   // true<br>console.log(18 === &#39;18&#39;); // false<br>console.log(true === 1);  // false<br>console.log(null === undefined); // false</pre><p>Strict → safest → used in real projects.<br>It checks exactly: <em>same type? same value?</em></p><p><strong>2. Loose Equality (==)</strong></p><p><strong>Allows type coercion, </strong>Tries to convert both sides to the same type before comparing</p><pre>console.log(18 == &#39;18&#39;); // true  (string → number)<br>console.log(true == 1);  // true  (true → 1)<br>console.log(false == 0); // true  (false → 0)</pre><p>JS automatically changes types → unexpected results sometimes.</p><blockquote><strong><em>Special Weird Cases (very important)</em></strong></blockquote><p>Loose equality has some strange behaviors, This is why developers avoid == in production.</p><pre>console.log(null == undefined); // true<br>console.log(&#39;&#39; == 0);           // true<br>console.log(&#39;&#39; == false);       // true<br>console.log(&#39;0&#39; == false);      // true</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aed0a9bfc46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete SQL: The Only Guide You’ll Ever Need]]></title>
            <link>https://medium.com/@himanshupapola/complete-sql-the-only-guide-youll-ever-need-42e8c6cb7112?source=rss-3f8413f87d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/42e8c6cb7112</guid>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Himanshu Papola]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 15:28:10 GMT</pubDate>
            <atom:updated>2025-12-03T15:28:10.021Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL has been around for more than four decades, yet it remains the backbone of every serious application we build today. From banking systems and e-commerce platforms to analytics dashboards and mobile apps, SQL quietly powers the data operations behind the scenes.</p><p>Whether we are filtering millions of rows, joining complex relationships, or analyzing trends across time, SQL gives us a consistent, declarative language to express <em>what</em> we want instead of <em>how</em> to compute it. That simplicity is why SQL is equally loved by developers, analysts, data engineers, and even AI workflows today.</p><p>This guide is designed to be the last SQL tutorial we’ll ever need. We begin with fundamentals, build up to complex concepts like window functions and query optimization, and wrap everything in production-grade best practices.</p><h3>What is SQL (Structured Query Language)?</h3><p>SQL, or <strong>Structured Query Language</strong>, is a standardized programming language specifically designed for managing and manipulating <strong>relational databases</strong>. It was originally developed by <strong>IBM in the 1970s</strong> as part of their System R project.</p><p>SQL allows us to perform all essential database operations often referred to as <strong>CRUD</strong>: <strong>Create</strong> data, <strong>Read</strong> data, <strong>Update</strong> data, <strong>Delete</strong> data.</p><p>With SQL, we can define database structures, insert new information, modify existing records, and retrieve exactly the data we need whether it’s a single row or millions of them. It remains the most widely used language for working with structured data in modern applications.</p><h3>SQL Data Types:</h3><p>SQL provides different categories of data types to store different kinds of information in a relational database. The four most commonly used categories are:</p><blockquote><strong><em>a) Numeric Data Types:</em></strong></blockquote><p>Used to store numbers such as integers, decimals, and floating-point values.</p><p><strong>Common Numeric Sub-Types:</strong></p><pre>| Data Type         | Description                                         |<br>| ----------------- | --------------------------------------------------- |<br>| INT               | Whole numbers (no decimals)                         |<br>| SMALLINT          | Smaller range of whole numbers                      |<br>| BIGINT            | Very large whole numbers                            |<br>| DECIMAL(p, s)     | Exact numeric values with fixed precision and scale |          |<br>| FLOAT             | Approximate floating-point numbers                  |<br>| DOUBLE            | Larger or more precise floating-point numbers       |<br><br>CREATE TABLE Office_Numeric (<br>    emp_id INT,<br>    age SMALLINT,<br>    salary DECIMAL(10,2),<br>    performance_score FLOAT<br>);</pre><blockquote><strong><em>b) Character Data Types</em></strong></blockquote><p>Used for storing text (single characters, short strings, long strings).</p><p><strong>Common Character Sub-Types:</strong></p><pre>| Data Type       | Description                    |<br>| --------------- | ------------------------------ |<br>| CHAR(n)         | Fixed-length string            |<br>| VARCHAR(n)      | Variable-length string         |<br>| TEXT            | Long text data                 |<br><br>CREATE TABLE Office_Character (<br>    emp_id INT,<br>    emp_name VARCHAR(50),<br>    emp_grade CHAR(2),<br>    remarks TEXT<br>);</pre><blockquote><strong><em>c) Date &amp; Time Data Types</em></strong></blockquote><p>Used for storing dates, times, and timestamps.</p><p><strong>Common Sub-Types:</strong></p><pre>| Data Type                | Description                   |<br>| ------------------------ | ----------------------------- |<br>| DATE                     | Stores date only (YYYY-MM-DD) |<br>| TIME                     | Stores time only (HH:MM:SS)   |<br>| DATETIME / TIMESTAMP     | Stores both date and time     |<br>| YEAR                     | Stores only the year          |<br><br>CREATE TABLE Office_DateTime (<br>    emp_id INT,<br>    joining_date DATE,<br>    login_time TIME,<br>    created_at TIMESTAMP<br>);</pre><blockquote><strong><em>d) Boolean Data Type</em></strong></blockquote><p>Stores logical values: <strong>TRUE</strong> or <strong>FALSE</strong>.</p><p><strong>Common Sub-Types:</strong></p><pre>| Data Type   | Description                                  |<br>| ----------- | -------------------------------------------- |<br>| BOOLEAN     | TRUE or FALSE                                |<br>| BIT         | Stores 0 or 1 (used for boolean-like values) |<br><br>CREATE TABLE Office_Boolean (<br>    emp_id INT,<br>    is_active BOOLEAN,<br>    is_remote BIT<br>);</pre><h3>Types of Keys:</h3><p>In SQL keys are used to uniquely identify record and establish realtionship between tables.</p><blockquote><strong><em>1. PRIMARY KEY</em></strong></blockquote><p>A <strong>Primary Key</strong> uniquely identifies each row in a table.</p><ul><li>Cannot be NULL</li><li>Cannot be duplicate</li><li>Only <strong>one</strong> primary key per table (but it can be composite)</li></ul><pre>CREATE TABLE Employees (<br>    emp_id INT,<br>    name VARCHAR(50),<br>    email VARCHAR(50),<br>    PRIMARY KEY (emp_id)<br>);</pre><blockquote><strong><em>2. FOREIGN KEY</em></strong></blockquote><p>A <strong>Foreign Key</strong> links one table to another. It references a <strong>primary key</strong> of another table.</p><pre>CREATE TABLE Employees (<br>    emp_id INT,<br>    name VARCHAR(100),<br>    department VARCHAR(50),<br>    PRIMARY KEY (emp_id)<br>);</pre><pre>CREATE TABLE SalaryBreakdown (<br>    salary_id INT PRIMARY KEY, <br>    emp_id INT,                            <br>    basic DECIMAL(10,2),<br>    deductions DECIMAL(10,2),<br>    FOREIGN KEY (emp_id) REFERENCES Employees(emp_id)<br>);</pre><blockquote><strong><em>3. CANDIDATE KEY</em></strong></blockquote><p>A <strong>Candidate Key</strong> is a column (or set of columns) that can <em>uniquely</em> identify rows. A table can have <strong>multiple candidate keys</strong>, but only one becomes the <strong>Primary Key</strong>.</p><pre>CREATE TABLE Users (<br>    user_id INT,<br>    email VARCHAR(100),<br>    phone VARCHAR(20),<br>    PRIMARY KEY (user_id)<br>);</pre><p>Here:</p><ul><li>user_id, email, phone → <strong>candidate keys</strong></li><li>Only user_id is chosen as <strong>primary key</strong>.</li></ul><blockquote><strong><em>4. ALTERNATE KEY</em></strong></blockquote><p>A <strong>Candidate Key</strong> that is <strong>not selected</strong> as the Primary Key is called an <strong>Alternate Key</strong>.</p><p>In the same example above:</p><ul><li>email and phone are <strong>alternate keys</strong>.</li></ul><pre>CREATE TABLE Users (<br>    user_id INT PRIMARY KEY,<br>    email VARCHAR(100) UNIQUE,     -- Alternate Key<br>    phone VARCHAR(20) UNIQUE       -- Alternate Key<br>);</pre><blockquote><strong><em>5. COMPOSITE KEY</em></strong></blockquote><p>A <strong>key made of multiple columns</strong> used together to uniquely identify a row.<br> Used when a single column cannot do the job.</p><pre>CREATE TABLE OrderItems (<br>    order_id INT,<br>    product_id INT,<br>    quantity INT,<br>    PRIMARY KEY (order_id, product_id)<br>);</pre><p>order_id + product_id together → unique identifier.</p><blockquote><strong><em>6. UNIQUE KEY</em></strong></blockquote><p>A column that must have <strong>unique values</strong>, but <strong>can have one NULL</strong> (depends on DBMS).</p><pre>CREATE TABLE Students (<br>    roll_no INT PRIMARY KEY,<br>    email VARCHAR(100) UNIQUE<br>);</pre><ul><li>email must be unique</li><li>But the table still has a primary key (roll_no)</li></ul><h3>Creating and Managing Database:</h3><pre>-- 1. CREATE DATABASE<br>CREATE DATABASE company_db;<br><br>-- 2. SHOW DATABASES <br>SHOW DATABASES;<br><br>-- 3. USE DATABASE<br>USE company_db;<br><br>-- 4. DROP DATABASE<br>DROP DATABASE company_db;<br><br>-- 5. ALTER DATABASE (SQL only) <br>ALTER DATABASE old_db MODIFY NAME = new_db;</pre><h3>Creating and Managing Table:</h3><blockquote><strong><em>1. Creating Table</em></strong></blockquote><pre>-- 1. Basic Table<br>CREATE TABLE Employees (<br>    emp_id INT,<br>    name VARCHAR(50),<br>    age INT<br>);<br><br>-- 2. Table With PRIMARY KEY<br>CREATE TABLE Employees (<br>    emp_id INT PRIMARY KEY,<br>    name VARCHAR(50),<br>    age INT<br>);<br><br>-- 3. Table With AUTO_INCREMENT<br>CREATE TABLE Employees (<br>    emp_id INT AUTO_INCREMENT PRIMARY KEY,<br>    name VARCHAR(50),<br>    age INT<br>);<br><br>-- 4. Table With NOT NULL + DEFAULT<br>CREATE TABLE Employees (<br>    emp_id INT PRIMARY KEY,<br>    name VARCHAR(50) NOT NULL,<br>    age INT DEFAULT 18<br>);<br><br>-- 5. Table With UNIQUE Key<br>CREATE TABLE Users (<br>    user_id INT PRIMARY KEY,<br>    email VARCHAR(100) UNIQUE<br>);<br><br>-- 6. Table With FOREIGN KEY<br>CREATE TABLE Departments (<br>    dept_id INT PRIMARY KEY,<br>    dept_name VARCHAR(50)<br>);<br><br>CREATE TABLE Employees (<br>    emp_id INT PRIMARY KEY,<br>    name VARCHAR(50),<br>    dept_id INT,<br>    FOREIGN KEY (dept_id) REFERENCES Departments(dept_id)<br>);<br><br>-- 8. Table With CHECK Constraint<br>CREATE TABLE Employees (<br>    emp_id INT PRIMARY KEY,<br>    name VARCHAR(50),<br>    age INT CHECK (age &gt;= 18)<br>);<br><br>-- 9. Create Table From Another Table (Copy Data + Structure)<br>CREATE TABLE BackupEmployees AS<br>SELECT * FROM Employees;<br><br>-- 10. Create Table From Another Table (Only Structure)<br>CREATE TABLE BackupEmployees AS<br>SELECT * FROM Employees WHERE 1 = 0;<br><br>-- 11. Safe DROP + CREATE Pattern (Production Style)<br>DROP TABLE IF EXISTS Employees;<br><br>CREATE TABLE Employees (<br>    emp_id INT PRIMARY KEY,<br>    name VARCHAR(50)<br>);</pre><blockquote><strong><em>2. Alter Table</em></strong></blockquote><p>ALTER TABLE is used to <strong>change an existing table</strong> without deleting it.</p><p>We can use it to: <strong>Add column, Drop column, Modify column, Rename column, Rename table, Add constraints (PRIMARY, UNIQUE, CHECK, FOREIGN), Drop constraints.</strong></p><pre>-- 1. Add a New Columns<br>ALTER TABLE Employees<br>ADD department VARCHAR(50),<br>ADD joining_date DATE;<br><br>-- 2. Drop a Column<br>ALTER TABLE Employees<br>DROP COLUMN age;<br><br>-- 3. Modify Column Type<br>ALTER TABLE Employees<br>MODIFY salary DECIMAL(12,2);<br><br>-- 4. Rename Column (MySQL)<br>ALTER TABLE Employees<br>CHANGE COLUMN name full_name VARCHAR(50);<br><br>-- 5. Rename Table<br>ALTER TABLE Employees<br>RENAME TO Staff;<br><br>-- 6. Add PRIMARY KEY (single column)<br>ALTER TABLE Employees<br>ADD PRIMARY KEY (emp_id);<br><br>-- 7. Add UNIQUE Constraint<br>ALTER TABLE Users<br>ADD CONSTRAINT unique_email UNIQUE (email);<br><br>-- 8. Drop PRIMARY KEY<br>ALTER TABLE Employees<br>DROP PRIMARY KEY;</pre><blockquote><strong><em>3. Drop Table</em></strong></blockquote><p>DROP TABLE permanently deletes a table <strong>and all data inside it</strong>.</p><pre>-- 1. Drop a Table<br>DROP TABLE IF EXISTS Employees;</pre><blockquote><strong><em>4. Inserting in Table</em></strong></blockquote><pre>CREATE TABLE A04_Inserting_In_Table (<br>    emp_id INT PRIMARY KEY AUTO_INCREMENT,<br>    name VARCHAR(200),<br>    age INT<br>);<br><br>-- 1. Basic INSERT (Insert into all columns in order)<br>INSERT INTO A04_Inserting_In_Table<br>VALUES (101, &quot;Himanshu&quot;, 25);<br><br>-- 2. INSERT Into Specific Columns (Recommended)<br>INSERT INTO A04_Inserting_In_Table (emp_id, name, age)<br>VALUES (102, &quot;Rakesh&quot;, 26);<br><br>-- 3. INSERT Multiple Rows at Once<br>INSERT INTO A04_Inserting_In_Table (emp_id, name, age)<br>VALUES<br>    (103, &#39;Riya&#39;, 22),<br>    (104, &#39;Karan&#39;, 30),<br>    (105, &#39;Sneha&#39;, 27);<br><br>-- 4. INSERT Using AUTO_INCREMENT (Skip PK)<br>INSERT INTO A04_Inserting_In_Table ( name, age)<br>VALUES (&#39;Mehul&#39;, 24);<br><br><br>-- 5. INSERT With NULL Values<br>INSERT INTO A04_Inserting_In_Table (emp_id, name, age)<br>VALUES (106, NULL, 23);<br><br>-- 6. INSERT Into One Table From Another Table<br>INSERT INTO A04_Inserting_In_Table (name, age)<br>SELECT name, age<br>FROM A04_Inserting_In_Table;</pre><blockquote><strong><em>5. Selecting Data In Table</em></strong></blockquote><p>The SQL Select statement is used to reteriev data from database. It allows us to specify which column data we want from which table to get data.</p><pre>-- 1. Create table<br>CREATE TABLE A05_Employee_Table (<br>      emp_id INT PRIMARY KEY,<br>      first_name VARCHAR(50),<br>      last_name VARCHAR(50),<br>      age INT,<br>      salary DECIMAL(10,2),<br>      department VARCHAR(50),<br>      phone VARCHAR(15)<br>);<br><br>-- 2. Insert sample rows (some NULL phones)<br>INSERT INTO A05_Employee_Table (emp_id, first_name, last_name, age, salary, department, phone)<br>VALUES<br>    (1, &#39;Amit&#39;,   &#39;Sharma&#39;, 28, 45000.00, &#39;IT&#39;,        &#39;9876543210&#39;),<br>    (2, &#39;Neha&#39;,   &#39;Verma&#39;,  26, 52000.00, &#39;Finance&#39;,   NULL),<br>    (3, &#39;Rahul&#39;,  &#39;Patil&#39;,  30, 39000.00, &#39;HR&#39;,        &#39;9988776655&#39;),<br>    (4, &#39;Priya&#39;,  &#39;Singh&#39;,  24, 47000.00, &#39;IT&#39;,        NULL),<br>    (5, &#39;Karan&#39;,  &#39;Desai&#39;,  32, 55000.00, &#39;Marketing&#39;, &#39;9123456789&#39;);<br><br>-- 3. Selecting Particular Columns<br>SELECT first_name, last_name, age<br>    FROM A05_Employee_Table;<br><br>-- 4. Selecting Distinct Data Columns<br>SELECT DISTINCT first_name FROM A05_Employee_Table;<br><br>-- 5. Selecting All Columns<br>SELECT * FROM A05_Employee_Table;<br><br>-- 6. Selecting and Applying Arithmetic Operation<br>SELECT<br>    salary * 2 AS Double_Salary<br>FROM<br>    A05_Employee_Table;<br><br>-- 7. Concatenation of Data<br>SELECT<br>    CONCAT(first_name, &#39; &#39; ,last_name) AS Full_Name<br>FROM<br>    A05_Employee_Table;<br><br>-- 8. Literal Text<br>SELECT &quot;Hello World&quot; AS Welcome;<br><br>-- 9. Replacing Null Values<br>SELECT<br>    emp_id,<br>    first_name,<br>    COALESCE(phone, &quot;No Phone Provided&quot;)<br>FROM<br>    A05_Employee_Table;<br><br>SELECT<br>    emp_id,<br>    first_name,<br>    IFNULL(phone, &quot;No Phone Provided&quot;)<br>FROM<br>    A05_Employee_Table;</pre><blockquote><strong><em>6. Filtering Data Using Where Caluse</em></strong></blockquote><p>The <strong>WHERE clause</strong> in SQL is used to filter rows from a table and return only those records that satisfy a specific condition.</p><p>A query can contain only one WHERE clause, but that single clause may include multiple conditions combined using logical operators such as <strong>AND</strong>, <strong>OR</strong>, and <strong>NOT</strong>.</p><p>When writing conditions inside the WHERE clause, the data types used in the comparison must match the column’s data type.</p><p>The WHERE clause is essential for filtering records based on criteria such as numeric ranges, string matches, and NULL checks, making it a fundamental part of retrieving meaningful data from a database.</p><p><strong>Where clause can be combined with multiple operator to filter data as per choice:</strong></p><pre>-- 1. Create table<br>CREATE TABLE A05_Employee_Table (<br>                                    emp_id INT PRIMARY KEY,<br>                                    first_name VARCHAR(50),<br>                                    last_name VARCHAR(50),<br>                                    age INT,<br>                                    salary DECIMAL(10,2),<br>                                    department VARCHAR(50),<br>                                    phone VARCHAR(15)<br>);<br><br>-- 2. Insert sample rows (some NULL phones)<br>INSERT INTO A05_Employee_Table (emp_id, first_name, last_name, age, salary, department, phone)<br>VALUES<br>    (1, &#39;Amit&#39;,   &#39;Sharma&#39;, 28, 45000.00, &#39;IT&#39;,        &#39;9876543210&#39;),<br>    (2, &#39;Neha&#39;,   &#39;Verma&#39;,  26, 52000.00, &#39;Finance&#39;,   NULL),<br>    (3, &#39;Rahul&#39;,  &#39;Patil&#39;,  30, 39000.00, &#39;HR&#39;,        &#39;9988776655&#39;),<br>    (4, &#39;Priya&#39;,  &#39;Singh&#39;,  24, 47000.00, &#39;IT&#39;,        NULL),<br>    (5, &#39;Karan&#39;,  &#39;Desai&#39;,  32, 55000.00, &#39;Marketing&#39;, &#39;9123456789&#39;);<br><br>-- 3. WHERE with Comparison Operators (First True Value returned here)<br>SELECT * from A05_Employee_Table WHERE salary &gt; 40000<br>                                     or age &gt; 22<br>                                     or salary &lt; 50000<br>                                     or age != 26;<br><br>-- 4. WHERE with Between<br>SELECT * FROM A05_Employee_Table WHERE age BETWEEN 22 AND 27;<br><br>-- 5. WHERE with In Set (Check if value is in Set)<br>SELECT * FROM A05_Employee_Table WHERE salary IN (52000, 44000, 49000);<br><br>-- 6. WHERE with Logical Operator (AND, OR, NOT)<br>SELECT * FROM A05_Employee_Table<br>WHERE<br>    (department = &#39;HR&#39; OR department = &#39;IT&#39;)<br>AND (age &gt;= 30)<br>AND NOT (phone IS NULL);</pre><pre>-- 7. WHERE with LIKE<br>-- Where can be used to filter row based upon pattern match.<br>-- It&#39;s commonly used to search for specific pattern<br>-- It&#39;s used with WildCards like % and _<br>-- Here % Wildcard match zero or more character. It represents any number of character including no char at all.<br>-- The _ Wildcard match exactly one character. It&#39;s used when we want to search for pattern with specific number of char.<br><br>-- 7.1 Match First Name Starting from A<br>SELECT *<br>FROM A05_Employee_Table<br>WHERE first_name LIKE &#39;A%&#39;;<br><br>-- 7.2 Match First Name ending with A<br>SELECT *<br>FROM A05_Employee_Table<br>WHERE first_name LIKE  &#39;%A&#39;;<br><br>-- 7.3 Match First Name Patter &#39;Am%&#39;<br>SELECT *<br>FROM A05_Employee_Table<br>WHERE first_name LIKE  &#39;Am%&#39;;<br><br>-- 7.4 Match First Name Start with A ends with T<br>SELECT *<br>FROM A05_Employee_Table<br>WHERE first_name LIKE &#39;A%_T&#39;;<br><br>-- 7.5 Match 3 Char Long start with A<br>SELECT *<br>FROM A05_Employee_Table<br>WHERE first_name LIKE &#39;A__&#39;</pre><blockquote><strong><em>7. Sorting and Limiting Results</em></strong></blockquote><p>The <strong>Order BY</strong> clause is used to order data in <strong>ASC </strong>or <strong>DESC </strong>order and <strong>Limit </strong>to limit total number of rows returned.</p><pre>-- 1. Sorting By One Column<br>SELECT first_name, salary, age<br>FROM a05_employee_table<br>ORDER BY salary DESC ;<br><br>-- 2. Sorting By Multi Columns<br>SELECT first_name, salary, age<br>FROM a05_employee_table<br>ORDER BY salary , age DESC;<br><br>-- 3. Limiting Output<br>SELECT first_name, salary, age<br>FROM a05_employee_table<br>LIMIT 3;</pre><h3><strong><em>8. SQL Function</em></strong></h3><p>SQL functions are <strong>predefined</strong> or <strong>user-defined</strong> operations that take one or more input values, process them, and return a <strong>single output value</strong>.</p><p>Functions help us perform calculations, manipulate data, and retrieve information from the database in a structured and reusable way. They allow operations to be executed directly inside a SQL query without needing separate code.</p><h4><strong>Types of SQL Functions:</strong></h4><blockquote><strong><em>1. Scalar Functions:</em></strong></blockquote><p>Scalar functions operate on <strong>individual values</strong> and return <strong>one result per row</strong>. They accept one or multiple arguments and return a value of the <strong>same</strong> or <strong>different</strong> data type.</p><pre>-- 1. Single Row Functions<br>    <br>-- 1.1. String Functions<br>SELECT UPPER(first_name) AS First_Name FROM a05_employee_table;<br>SELECT LOWER(first_name) AS First_Name FROM a05_employee_table;<br>SELECT CONCAT(first_name,&quot; &quot;, last_name) AS Full_Name FROM a05_employee_table;<br>SELECT TRIM(first_name) AS Trimmed_Name FROM a05_employee_table;<br>SELECT SUBSTRING(first_name, 1,2) AS Sub_Name FROM a05_employee_table;<br><br>-- 1.2. Numeric Functions<br>SELECT ROUND(salary) FROM a05_employee_table;<br>SELECT FLOOR(salary) FROM a05_employee_table;<br>SELECT CEIL(salary) FROM a05_employee_table;<br>SELECT ABS(salary) FROM a05_employee_table;<br><br>-- 1.3. Maths<br>SELECT SIN(90) AS SIN_90;<br><br>-- 1.4. COALESCE<br>SELECT COALESCE(phone, &quot;No Phone Number&quot;) FROM a05_employee_table;</pre><pre>-- 2. Conversion Functions<br><br>-- 2.1 CAST(Value as Datatype)<br>SELECT CAST(salary AS CHAR) AS Salary_Text<br>FROM a05_employee_table;<br><br>SELECT CAST(&#39;123&#39; AS SIGNED ) AS String_To_Int;<br><br>SELECT CAST(NOW() AS CHAR) AS Date_Text;<br><br>-- 2.2 CONVERT() for extra formatting<br>SELECT CONVERT(salary, CHAR) AS Salary_Text<br>FROM a05_employee_table;</pre><h3>Joins in SQL</h3><p>A Join caluse is used to combine rows from two or more table based on a related column between them. Joins allow us to fetch data from multiple table in single query.</p><p>Let’s say we have two tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*CyF3UAaGEJROtZCmAxg1Tg.png" /><figcaption><strong>Table 1:</strong> <strong>a_10_employees</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*lFZww-1JaxHeKow4sPK0Iw.png" /><figcaption><strong>Table 2: a_10_department</strong></figcaption></figure><blockquote><strong><em>A. Inner Join:</em></strong></blockquote><p>The Inner Join keyword selects record that have matching value in both the table.</p><pre>-- 1. Inner Join (Returns Matching value in Both table)<br>SELECT e.emp_id, e.emp_name, d.dept_id<br>FROM a_10_employees e<br>INNER JOIN a_10_department d<br>ON e.dept_id = d.dept_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*Gh0gb1Htbc_Wlo1Ox1a9gQ.png" /><figcaption><strong>Inner Join</strong></figcaption></figure><blockquote><strong><em>B. Left Join:</em></strong></blockquote><p>Left Join returns all record from left table and matching record from right table if not matched null is right.</p><pre>SELECT e.emp_id, e.emp_name, d.dept_name<br>FROM a_10_employees e<br>LEFT JOIN a_10_department d<br>ON e.dept_id = d.dept_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*eupK0BtHRAoQ6NPPmiwaUQ.png" /><figcaption><strong>Left Join</strong></figcaption></figure><blockquote><strong><em>C. Right Join:</em></strong></blockquote><p>Returns all record from Right table and matching record from Left table. If no match is found null in left.</p><pre>SELECT e.emp_id, e.emp_name, d.dept_name<br>FROM a_10_employees e<br>RIGHT JOIN a_10_department d<br>ON e.dept_id = d.dept_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*c9uVmNpoR17ZF6mmFBLmvg.png" /><figcaption><strong>Right Join</strong></figcaption></figure><blockquote><strong><em>D. Full Outer Join:</em></strong></blockquote><p>It combines effect from Left and Right Join, will null on no match.</p><pre>SELECT e.emp_id, e.emp_name, d.dept_name<br>FROM A_10_Employees e<br>LEFT JOIN A_10_Department d<br>ON e.dept_id = d.dept_id<br><br>UNION<br><br>SELECT e.emp_id, e.emp_name, d.dept_name<br>FROM a_10_employees e<br>RIGHT JOIN a_10_department d<br>ON e.dept_id = d.dept_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*dtCDOu2fAa7rhQO7zMDMHg.png" /></figure><blockquote><strong><em>E. Cross Join:</em></strong></blockquote><p>Does a cartesian product</p><pre>SELECT *<br>FROM A_10_Employees e<br>CROSS JOIN A_10_Department d;</pre><blockquote><strong><em>F. Self Join:</em></strong></blockquote><p>Joining the <strong>same table with itself</strong>.</p><pre>SELECT e1.emp_name AS Employee1,<br>       e2.emp_name AS Employee2,<br>       e1.dept_id<br>FROM a_10_employees e1<br>JOIN a_10_employees e2<br>ON e1.dept_id = e2.dept_id<br>AND e1.emp_id != e2.emp_id;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42e8c6cb7112" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything You Need To Know Binary Trees]]></title>
            <link>https://medium.com/@himanshupapola/everything-you-need-to-know-binary-trees-e25090914093?source=rss-3f8413f87d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/e25090914093</guid>
            <category><![CDATA[binary-tree]]></category>
            <dc:creator><![CDATA[Himanshu Papola]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 15:18:43 GMT</pubDate>
            <atom:updated>2025-12-03T15:18:43.928Z</atom:updated>
            <content:encoded><![CDATA[<pre># Binary Tree – Complete Topic Flow <br><br>---<br><br>## 1. Introduction to Trees<br>- What is a Tree?<br>- Real-world use cases:<br>  - File systems<br>  - Compilers<br>  - Database indexing<br>  - Network routing<br>  - Hierarchical data representation<br><br>---<br><br>## 2. Basic Terminologies<br>These must be clear before we implement anything:<br><br>- Root  <br>- Parent Node  <br>- Child Node  <br>- Siblings  <br>- Leaf Node  <br>- Internal Node  <br>- Edge / Link  <br>- Degree of a Node (number of children)  <br>- Degree of Tree (max degree of any node)  <br>- Depth of Node (distance from root)  <br>- Height of Node  <br>- Height of Tree  <br>- Level of a Node  <br>- Subtree  <br>- Balanced vs Unbalanced Tree  <br>- Skewed Tree  <br>  - Left-skewed Tree  <br>  - Right-skewed Tree  <br><br>---<br><br>## ✅ 3. Binary Tree Basics<br>- Definition  <br>- Properties  <br>- Maximum nodes at level L = 2^L  <br>- Maximum nodes in a tree of height h = 2^(h+1) - 1  <br><br>---<br><br>## ✅ 4. Types of Binary Trees<br>- Strict Binary Tree (each node has 0 or 2 children)  <br>- Full Binary Tree (every internal node has 2 children)  <br>- Complete Binary Tree (all levels filled except last, filled left to right)  <br>- Perfect Binary Tree  <br>- Degenerate / Skewed Tree  <br>- Balanced Binary Tree (AVL, Red-Black – later)  <br><br>---<br><br>## ✅ 5. Creating / Building a Binary Tree<br>Ways to create:<br><br>- Static creation (hardcoded)  <br>- Level-order insertion (using queue)  <br>- Preorder-based construction (using recursion, -1 as null)  <br><br>---<br><br>## ✅ 6. Traversal of Binary Trees<br><br>### Depth First Traversals<br>- Inorder (LNR)  <br>- Preorder (NLR)  <br>- Postorder (LRN)  <br><br>### Breadth First Traversal<br>- Level Order Traversal (using queue)  <br><br>---<br><br>## ✅ 7. Operations on Binary Trees<br>- Searching a node  <br>- Inserting a node  <br>- Deleting a node  <br><br>---<br><br>## ✅ 8. Tree Properties &amp; Utility Problems<br>- Count total number of nodes  <br>- Calculate height / depth  </pre><h3>1. Introduction to Trees</h3><p>A <strong>tree</strong> is a <em>non-linear</em>, <em>hierarchical</em> data structure where elements are arranged in levels. Unlike arrays or linked lists, <strong>ordering is not based on position</strong>, but on <strong>parent–child relationships</strong>.</p><p>When we need <strong>ordering</strong>, we use <em>linear</em> structures such as:</p><ul><li><strong>Linked List</strong> → Sequential navigation</li><li><strong>Stack</strong> → LIFO</li><li><strong>Queue</strong> → FIFO</li></ul><p>Trees solve problems where hierarchy matters file systems, HTML DOM, organizational charts, routing, etc.</p><h4><strong>Terminology:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAuCdNfr0J8CTPls34Dsbg.png" /><figcaption>From GeeksForGeeks</figcaption></figure><ul><li><strong>Nodes:</strong> They are just elements of the tree.</li><li><strong>Root Node:</strong> The topmost node of the tree. <br><strong>Example:</strong> A is the root.</li><li><strong>Parent Node:</strong> A node that has one or more children.<strong> <br>Example:</strong> A is parent of B and C.</li><li><strong>Child Node:</strong> A node that comes from a parent. <br><strong>Example: </strong>B and C are children of A.</li><li><strong>Leaf Node:</strong> A node with no children. <br><strong>Example:</strong> K, L, M, N, O, P, G.</li><li><strong>Edge (Link):</strong> The line connecting two nodes. <br><strong>Example:</strong> A → B, A → C.</li><li><strong>Siblings:</strong> Nodes that share the same parent. <br><strong>Example:</strong> B &amp; C, D &amp; E, K &amp; L.</li><li><strong>Ancestor:</strong> Any node above a given node. <br><strong>Example:</strong> For L → H, D, B, A are ancestors.</li><li><strong>Descendant:</strong> Any node below a given node. <br><strong>Example: </strong>Descendants of B → D, E, H, I, K, L, M.</li><li><strong>Degree of Node:</strong> Number of direct children of a node. <br><strong>Example:</strong> A = 2, H = 2, K = 0.</li><li><strong>Degree of Tree:</strong> Maximum degree of any node. <br>Here the maximum is <strong>2</strong>.</li><li><strong>Depth of Node:</strong> Steps from the root down to the node. <br><strong>Example:</strong> A = 0, B = 1, D = 2, H = 3, K = 4.</li><li><strong>Level of Node:</strong> How far a node is from the root, counted in levels.<br><strong>Example: </strong>A = 0, B = 1, K = 4.</li><li><strong>Height of Node:</strong> Steps from the node down to its deepest leaf. <br><strong>Example:</strong> Height of H = 1, Height of B = 3.</li><li><strong>Height of Tree:</strong> Height of the root. Here the height is <strong>4</strong>.</li></ul><h3>2. Binary Tree</h3><p>A <strong>Binary Tree</strong> is a tree in which each node can have 0, 1, or at most 2 children. Even an <strong>empty tree</strong> is considered a valid binary tree.</p><h4><strong>Types of Binary Trees:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*OiFPARTlrk6qUTvdFTxRcg.png" /><figcaption><strong>Types</strong></figcaption></figure><p><strong>1. Strict Binary Tree:</strong></p><ul><li>Every node has <strong>excatly 0 or 2 children</strong>.</li><li>No node is allowed to have only one child.</li></ul><p><strong>2. Full Binary Tree:</strong></p><ul><li>All node has exactly two children and all leaft are at same level.</li><li>Total nodes = 2^(h + 1) — 1 when perfectly full.</li></ul><p><strong>3. Complete Binary Tree:</strong></p><ul><li>In it every level, expect last is completely filled, and all node in the last level are far left as possible.</li></ul><p><strong>4. Skewed Binary Tree:</strong></p><ul><li>Skewed Binary Trees are a special type of binary tree where all nodes are aligned only to one side either left or right.</li></ul><h4><strong>Creating Binary Tree:</strong></h4><ol><li><strong>Static Creation:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*dizFZwbIyqnuKpHyZCCGPA.png" /></figure><p>Here we created various nodes and attached them manually.</p><pre>public class Basic_Binary_Tree {<br>    public static void main(String[] args) {<br>        // Creating a root node at height 0<br>        BinaryTreeNode&lt;Integer&gt; root = new BinaryTreeNode&lt;&gt;(1);<br><br>        // Creating node 2 and 3 at height 1<br>        BinaryTreeNode&lt;Integer&gt; left = new BinaryTreeNode&lt;&gt;(2);<br>        BinaryTreeNode&lt;Integer&gt; right = new BinaryTreeNode&lt;&gt;(3);<br>        root.left = left;<br>        root.right = right;<br><br>        // Creating node 4,5,6 at height 2<br>        BinaryTreeNode&lt;Integer&gt; twoLeft = new BinaryTreeNode&lt;&gt;(4);<br>        BinaryTreeNode&lt;Integer&gt; twoRight = new BinaryTreeNode&lt;&gt;(5);<br>        BinaryTreeNode&lt;Integer&gt; threeRight = new BinaryTreeNode&lt;&gt;(6);<br>        left.left = twoLeft;<br>        left.right = twoRight;<br>        right.right = threeRight;<br><br>        // Printing tree (will see later)<br>        printTree(root);<br>    }<br>}<br><br>// Output<br>1:L:2,R:3<br>2:L:4,R:5<br>4:<br>5:<br>3:R:6<br>6:</pre><p><strong>2. Input From User:</strong></p><p><strong>a. Resursive Input (Pre Order Input)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*RYYTug_GvbJ5Pz-maRsxNw.png" /></figure><pre>public static BinaryTreeNode&lt;Integer&gt; takeTreeInput() {<br><br>    Scanner sc = new Scanner(System.in);<br><br>    // Take data for the current node<br>    int rootData = sc.nextInt();<br><br>    // Base case: if -1, this node is NULL<br>    if (rootData == -1) return null;<br><br>    // Create node<br>    BinaryTreeNode&lt;Integer&gt; root = new BinaryTreeNode&lt;&gt;(rootData);<br><br>    // LEFT child<br>    System.out.println(&quot;Enter left of &quot; + rootData);<br>    root.left = takeTreeInput();<br><br>    // RIGHT child<br>    System.out.println(&quot;Enter right of &quot; + rootData);<br>    root.right = takeTreeInput();<br><br>    return root;<br>}<br></pre><pre>// Here let say we have tree<br>        1<br>      /   \<br>     2     3<br>    / \     \<br>   4   5     6<br><br>// Now input is in of form (Root → Left Subtree → Right Subtree)<br>1 -&gt; 2 -&gt; 4 -&gt; -1, -1 -&gt; 5 -&gt; -1,-1 <br>3 -&gt; -1 -&gt; 6 -&gt; -1,-1</pre><p><strong>b. Level Order Insertion:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*DcECM2XpXHJYG9sJVHvSoQ.png" /></figure><p>Preorder Input cannot build trees automatically but in Level Order we insert nodes level by level, from left to right. This make creating a tree more intuitive.</p><p>Level Order Insertion is actually a <strong>BFS. </strong>It uses a Queue because we must preserve the exact order of nodes as they appear level by level. FIFO behavior ensures that the first node inserted is the first to be processed, which is the only way to correctly fill a binary tree from left to right in level order.</p><pre>public static BinaryTreeNode&lt;Integer&gt; takeInputLevelWise() {<br>    Scanner sc = new Scanner(System.in);<br>    Queue_Custom&lt;BinaryTreeNode&lt;Integer&gt;&gt; queue = new Queue_Custom&lt;&gt;();<br><br>    int rootData;<br>    System.out.println(&quot;Enter root data&quot;);<br>    rootData = sc.nextInt();<br>    <br>    if (rootData == -1) return null;<br><br>    BinaryTreeNode&lt;Integer&gt; root = new BinaryTreeNode&lt;&gt;(rootData);<br>    queue.enQueue(root);<br><br>    while (!queue.isEmpty()) {<br>       BinaryTreeNode&lt;Integer&gt; current = queue.deQueue();<br>       <br>       System.out.println(&quot;Enter the left child of the queue&quot;);<br>       int leftChild = sc.nextInt();<br>       if (leftChild != -1) {<br>          BinaryTreeNode&lt;Integer&gt; leftChildNode = new BinaryTreeNode&lt;&gt;(leftChild);<br>          queue.enQueue(leftChildNode);<br>          current.left = leftChildNode;<br>       };<br><br>       System.out.println(&quot;Enter the right child of the queue&quot;);<br>       int rightChild = sc.nextInt();<br>       if (rightChild != -1) {<br>           BinaryTreeNode&lt;Integer&gt; rightChildNode = new BinaryTreeNode&lt;&gt;(rightChild);<br>           queue.enQueue(rightChildNode);<br>           current.right = rightChildNode;<br>        };<br>    }<br><br>    return root;<br>}</pre><p>Here, We use a queue so that we always know which node’s children to insert next, allowing us to build the binary tree level-by-level.</p><p><strong>Let’s dry run it to understand:</strong></p><pre>// Initial State<br>queue = empty<br>front = 0, rear = -1, size = 0<br><br>// 1. Insert the first node (root = 1)<br>root = new BinaryTreeNode&lt;&gt;(1);<br>queue.enQueue(root);<br><br>// Inside Queue<br>queue = [ 1 ]<br>front = 0, rear = 0, size = 1<br><br>//-------------------------------------------------------------<br><br>// 2. Dequeue each node until queue becomes empty (ITERATIVE)<br>current = queue.deQueue();   // returns Node(1)<br><br>// Queue state after dequeue<br>queue = [ ]<br>front = 1, rear = 0, size = 0<br><br>// ----- Processing Node(1) -----<br><br>// Setting LEFT child<br>leftChild = 2;<br>leftChildNode = new BinaryTreeNode&lt;&gt;(leftChild);<br>current.left = leftChildNode;<br>queue.enQueue(leftChildNode);<br><br>// Queue State<br>queue = [ 2 ]<br>front = 1, rear = 1, size = 1<br><br>//-------------------------------------------------------------<br><br>// Setting RIGHT child<br>rightChild = 3;<br>rightChildNode = new BinaryTreeNode&lt;&gt;(rightChild);<br>current.right = rightChildNode;<br>queue.enQueue(rightChildNode);<br><br>// Queue State<br>queue = [ 2, 3 ]<br>front = 1, rear = 2, size = 2<br><br>// ------------------ NEXT ITERATION ---------------------------<br><br>// Dequeue next node<br>current = queue.deQueue();   // Node(2) (i.e left child)<br><br>// Queue State<br>queue = [ 3 ]<br>front = 2, rear = 2, size = 1<br><br>// and so on until -1 is entered and null returned </pre><h3>1. Traversing: (Recusrive Approaches)</h3><blockquote><strong><em>A. Pre-order Traversal [Root-Left-Right]</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ml1Y3NIsmuhw-RnXd6nUQ.png" /><figcaption><strong>Pre-Order Traversal is [1, 2, 4, 5, 3, 6]</strong></figcaption></figure><p>Tree traversals define the order in which we visit nodes. One of the most important traversal methods is <strong>Pre-order Traversal</strong>, classified under <strong>Depth-First Search (DFS)</strong>. The key idea is that we <strong>always process the current node before we explore its children</strong>, hence the name “Pre”-order. Preorder traversal can be used to copy and clone the tree.</p><p>It have biggest limitation that alone it can’t be used to build the original tree. The structure of pre-order traversal can be same for different trees. Here, adding a null market while traversing for leaft node will fix this limitation.</p><p>Preorder visits nodes in this order: <strong>Root &gt; Left Subtree &gt; Right Subtree</strong></p><pre>public static &lt;T&gt; void preOrder(BinaryTreeNode&lt;T&gt; root, List&lt;T&gt; result) {<br>    if (root == null) {<br>        result.add(null);<br>        return;<br>    }<br>    result.add(root.data);<br>    preOrder(root.left, result);<br>    preOrder(root.right, result);<br>}<br><br>// Output<br>// [1, 2, 4, null, null, 5, null, null, 3, null, 6, null, null]</pre><blockquote><strong><em>B. Post-order Traversal [Left-Right-Root]</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvbYwqyDCMgfkU2CvsOhSA.png" /><figcaption><strong>Post-Order Traversal is [ 4, 5, 2, 6, 3, 1]</strong></figcaption></figure><p>Post-Order Traversal is another core Depth-First Search (DFS) technique. The key idea is that <strong>we always process a node <em>after</em> exploring both of its children</strong>, hence the name <strong>“Post”-order</strong>.</p><p>Postorder traversal can be used in scenarios where children must be handled before the parent, especially in deletion operations, freeing memory, evaluating expressions, and postfix expression generation.</p><p>Post-order visits nodes in order: <strong>Left Subtree → Right Subtree → Root</strong></p><pre>public static &lt;T&gt; void postOrder(BinaryTreeNode&lt;T&gt; root, List&lt;T&gt; result) {<br>    if (root == null) {<br>        return;<br>    }<br>    postOrder(root.left, result);<br>    postOrder(root.right, result);<br>    result.add(root.data);<br>}<br><br>// Output<br>// [4, 5, 2, 6, 3, 1]</pre><blockquote><strong><em>C. In-order Traversal [Left-Root-Right]</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*iIuAyr2tBkjcY08OCXWAlg.png" /><figcaption>In-Order Tree</figcaption></figure><p><strong>In-Order Traversal</strong> is another fundamental Depth-First Search (DFS) technique. The key idea is that <strong>we always process the left subtree first, then the node itself, and then the right subtree.</strong></p><p>Post-order visits nodes in order: <strong>Left Subtree → Root → Root Subtree</strong></p><pre>public static &lt;T&gt; void inOrder(BinaryTreeNode&lt;T&gt; root, List&lt;T&gt; result) {<br>    if (root == null) return;<br><br>    inOrder(root.left, result);<br>    result.add(root.data);<br>    inOrder(root.right, result);<br>}</pre><blockquote><strong><em>D. Level-order Traversal [Using Queues]</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*DcECM2XpXHJYG9sJVHvSoQ.png" /></figure><p><strong>Level-order Traversal</strong> is the only traversal method based on <strong>Breadth-First Search (BFS)</strong> instead of DFS. The key idea is that we visit the tree <strong>level by level</strong>, from top to bottom, and from left to right within each level.</p><p>To accomplish this ordering, we use a <strong>Queue</strong>, because it follows FIFO (First-In-First-Out) order the same order we want nodes to be processed in.</p><pre>public static &lt;T&gt; List&lt;List&lt;T&gt;&gt; levelOrder(BinaryTreeNode&lt;T&gt; root) {<br><br>    List&lt;List&lt;T&gt;&gt; ans = new ArrayList&lt;&gt;();<br>    if (root == null) return ans;<br><br>    Queue&lt;BinaryTreeNode&lt;T&gt;&gt; queue = new LinkedList&lt;&gt;();<br>    queue.add(root);<br><br>    while (!queue.isEmpty()) {<br><br>        int size = queue.size();<br>        List&lt;T&gt; level = new ArrayList&lt;&gt;();<br><br>            for (int i = 0; i &lt; size; i++) {<br><br>                BinaryTreeNode&lt;T&gt; node = queue.poll();<br>                if (node == null) continue;<br><br>                level.add(node.data);<br><br>                if (node.left != null) queue.add(node.left);<br>                if (node.right != null) queue.add(node.right);<br>            }<br><br>            ans.add(level);<br>    }<br><br>    return ans;<br>}<br><br>// [[1], [2, 3], [4, 5, 6]]</pre><h3>2. Operations of Binary Tree</h3><blockquote><strong><em>a. Searching a Node: </em></strong><em>Choose any of travesral and search.</em></blockquote><pre>private static boolean searchNode(BinaryTreeNode&lt;Integer&gt; root, int value) {<br>    if  (root == null) return false;<br>    if (root.data == value) return true;<br><br>    boolean res1 = searchNode(root.left, value);<br>    if (res1) return true;<br><br>    return searchNode(root.right, value);<br>}</pre><blockquote><strong><em>b. Inserting a Node: </em></strong><em>Only level order insertion makes sense.</em></blockquote><pre>private static BinaryTreeNode&lt;Integer&gt; insertNode(BinaryTreeNode&lt;Integer&gt; root, int value) {<br><br>    if (root == null) {<br>        return new BinaryTreeNode&lt;&gt;(value);<br>    }<br><br>    Queue&lt;BinaryTreeNode&lt;Integer&gt;&gt; queue = new LinkedList&lt;&gt;();<br>    queue.add(root);<br><br>    while (!queue.isEmpty()) {<br><br>        BinaryTreeNode&lt;Integer&gt; node = queue.poll();<br><br>        if (node.left == null) {<br>            node.left = new BinaryTreeNode&lt;&gt;(value);<br>            return root;<br>        } else {<br>            queue.add(node.left);<br>        }<br><br>        if (node.right == null) {<br>            node.right = new BinaryTreeNode&lt;&gt;(value);<br>            return root;<br>        } else {<br>            queue.add(node.right);<br>        }<br>    }<br><br>    return root;<br>}</pre><blockquote><strong><em>c. Deleting a Node</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRHoQQjsOAh5RA3wS6w_Lw.png" /></figure><p><strong><em>Steps to Delete a Node:</em></strong></p><ol><li>Find the node that we want to delete</li><li>Find the deepest (last) node in the tree</li><li>Copy the deepest node’s value to the node we want to delete</li><li>Delete the deepest node</li></ol><pre>public static BinaryTreeNode&lt;Integer&gt; deleteNode(BinaryTreeNode&lt;Integer&gt; root, int key) {<br>        if (root == null) return null;<br><br>        // If tree has only one node<br>        if (root.left == null &amp;&amp; root.right == null) {<br>            if (root.data == key) return null;<br>            return root;<br>        }<br><br>        Queue&lt;BinaryTreeNode&lt;Integer&gt;&gt; q = new LinkedList&lt;&gt;();<br>        q.add(root);<br><br>        BinaryTreeNode&lt;Integer&gt; keyNode = null;         // node to delete<br>        BinaryTreeNode&lt;Integer&gt; currentNode = null;     // deepest node<br>        BinaryTreeNode&lt;Integer&gt; lastNodeParent = null;  // parent of deepest node<br><br>        // Step 1 &amp; 2: find keyNode + deepest node parent<br>        while (!q.isEmpty()) {<br>            currentNode = q.poll();<br><br>            if (currentNode.data == key) keyNode = currentNode;<br><br>            if (currentNode.left != null) {<br>                lastNodeParent = currentNode.left;<br>                q.add(currentNode.left);<br>            }<br><br>            if (currentNode.right != null) {<br>                lastNodeParent = currentNode.right;<br>                q.add(currentNode.right);<br>            }<br>        }<br><br>        if (keyNode == null) return root; // key not found<br><br>        // Step 3: copy deepest node&#39;s data into keyNode<br>        keyNode.data = currentNode.data;<br><br>        // Step 4: delete deepest node safely<br>        if (lastNodeParent == null) {<br>            root = null;<br>        } else if (lastNodeParent.left == currentNode) {<br>            lastNodeParent.left = null;<br>        } else {<br>            lastNodeParent.right = null;<br>        }<br><br>        return root;<br>}</pre><blockquote><strong><em>d. Number of Nodes</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCyKkufJximrIKmWzBEfHA.png" /></figure><p><strong>Simple Logic:</strong> count(root) = 1 + count(root.left) + count(root.right)</p><pre>public static int numNodes(BinaryTreeNode&lt;Integer&gt; root) {<br>    if (root == null) {return 0;}<br><br>    int leftNodesCount = numNodes(root.left);<br>    int rightNodesCount = numNodes(root.right);<br><br>    return leftNodesCount + rightNodesCount + 1;<br>}</pre><blockquote><strong><em>e. Height/Depth of Tree</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVHQY3MOknT3ZgMO0QxoDg.png" /></figure><p><strong>Height: </strong>Number of nodes on the longest path from the current node down to a leaf<strong><br>Depth:</strong> Number of nodes from the root to the current node</p><pre>                  1<br>                 / \<br>                2   3<br>               / \   \<br>              4   5   6 <br><br>Depth(1) = 1         (just node 1)<br>Depth(2) = 2         (1 → 2)<br>Depth(4) = 3         (1 → 2 → 4)<br><br>Height(4) = 1        (leaf → only itself)<br>Height(2) = 2        (2 → 4 or 2 → 5)<br>Height(1) = 3        (1 → 2 → 4 OR 1 → 3 → 6) (Height of Tree)</pre><pre>private static int heightOfTree(BinaryTreeNode&lt;Integer&gt; root) {<br><br>    if (root == null) {return 0;}<br><br>    int leftHeight = heightOfTree(root.left);<br>    int rightHeight = heightOfTree(root.right);<br><br>    return 1 + Math.max(leftHeight, rightHeight);<br>}</pre><blockquote><strong><em>f. Number of Leaf Nodes</em></strong></blockquote><pre>private static int numLeafNodes(BinaryTreeNode&lt;Integer&gt; root) {<br><br>    if (root == null) {return 0;}<br><br>    int left = numLeafNodes(root.left);<br>    int right = numLeafNodes(root.right);<br><br>    if (root.left == null &amp;&amp; root.right == null){<br>        return 1;<br>    }<br><br>    return left + right;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e25090914093" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Streams: The Functional Style That Improves Your Codebase]]></title>
            <link>https://medium.com/@himanshupapola/java-streams-the-functional-style-that-improves-your-codebase-e978c90f5885?source=rss-3f8413f87d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/e978c90f5885</guid>
            <dc:creator><![CDATA[Himanshu Papola]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 14:10:24 GMT</pubDate>
            <atom:updated>2025-11-23T14:10:24.812Z</atom:updated>
            <content:encoded><![CDATA[<p>Java Streams were introduced in <strong>Java 8 (2014)</strong> as part of Java’s shift toward a more modern, expressive, and functional programming style. Before Streams, most data processing relied on loops, temporary variables, and a lot of boilerplate.</p><p>It worked but it also made code noisy, repetitive, and difficult to maintain as projects grew. Streams were created to change that.</p><p>Instead of thinking about <em>how</em> to iterate through data, Streams allow us to describe <em>what</em> we want to do: filter items, transform values, group results, or collect them into new structures. This declarative style makes code cleaner, more readable, and closer to the way we naturally think about data much like SQL or other functional languages.</p><h4><strong>Creating Streams in Java</strong></h4><p>In Java, a <em>Stream</em> represents a pipeline of data operations, not a data structure by itself. Because of this, Streams are always <em>created from a source</em>. The source is usually a collection, an array, a generated sequence, or even an I/O channel.</p><p>Java provides several convenient ways to create Streams depending on where the data comes from.</p><pre>// 1. Creating a Stream from a Collection<br>List&lt;Integer&gt; numbers = List.of(1, 2, 3, 4, 5);<br>Stream&lt;Integer&gt; stream = numbers.stream();<br><br>// 2. Creating a Stream from an Array<br>int[] arr = {1, 2, 3};<br>Stream&lt;String&gt; stream = Stream.of(names);<br><br>String[] strs = {&quot;a&quot;, &quot;b&quot;};<br>Stream&lt;String&gt; stringStream = Arrays.stream(strs);<br><br>// 3. Creating a Stream Using Stream.of()<br>Stream&lt;String&gt; stream = Stream.of(&quot;Java&quot;, &quot;Stream&quot;, &quot;API&quot;);<br><br>// 4. Creating Streams from Files (I/O Streams)<br>Stream&lt;String&gt; lines = Files.lines(Path.of(&quot;data.txt&quot;));</pre><h4>Intermediate Operations in Java Streams</h4><p>Once a Stream is created, we usually apply <strong>intermediate operations</strong> to transform or filter the data these operations do <strong>not</strong> execute immediately. Instead, they build up a processing pipeline that runs only when a <strong>terminal operation</strong> is called.</p><p>Intermediate operations are:</p><ul><li><strong>lazy</strong> (they don’t run immediately)</li><li><strong>chainable</strong> (each one returns a new Stream)</li><li><strong>transformational</strong> (they change the form of data but not the source)</li></ul><pre>public class Intermediate_Operation {<br>    public static void main(String[] args) {<br><br>        // Creating a 2D list to demonstrate flatMap operations<br>        List&lt;List&lt;String&gt;&gt; nestedList = new ArrayList&lt;&gt;(<br>                List.of(<br>                        new ArrayList&lt;&gt;(List.of(&quot;A1&quot;, &quot;A2&quot;, &quot;A3&quot;)),<br>                        new ArrayList&lt;&gt;(List.of(&quot;B1&quot;, &quot;B2&quot;)),<br>                        new ArrayList&lt;&gt;(List.of(&quot;C1&quot;, &quot;C2&quot;, &quot;C3&quot;, &quot;C4&quot;)))<br>        );<br><br>        // Flattening a 2D list into a single list<br>        List&lt;String&gt; flattendList = nestedList.stream()<br>                .flatMap(list -&gt; list.stream())<br>                .collect(Collectors.toList());<br><br>        // Stream from int[] (boxed to Integer)<br>        int[] arr = {1,2,3,4,5};<br>        Stream&lt;Integer&gt; arrayStream = Arrays.stream(arr).boxed();<br><br>        // Stream from String[]<br>        String[] strs = {&quot;a&quot;, &quot;b&quot;};<br>        Stream&lt;String&gt; stringStream = Arrays.stream(strs);<br><br><br>        // --------------------- Intermediate Operations ---------------------<br><br><br>        // 1. filter() → keep elements starting with &quot;A&quot;<br>        List&lt;String&gt; startWithA = flattendList.stream()<br>                .filter(str -&gt; str.startsWith(&quot;A&quot;))<br>                .collect(Collectors.toList());<br>        System.out.println(startWithA);<br><br>        // Counting elements that start with &quot;B&quot;<br>        Long countStartWithB = flattendList.stream()<br>                .filter(str -&gt; str.startsWith(&quot;B&quot;))<br>                .count();<br>        System.out.println(countStartWithB);<br><br><br>        // 2. map() → convert each string to lowercase<br>        List&lt;String&gt; lowerCased = flattendList.stream()<br>                .map(str -&gt; str.toLowerCase())<br>                .collect(Collectors.toList());<br><br>        // Multiply each number by 2<br>        List&lt;Integer&gt; mulByTwo = arrayStream<br>                .map(x -&gt; x * 2)<br>                .collect(Collectors.toList());<br><br><br>        // 3. sorted() → natural sort for List&lt;List&lt;String&gt;&gt;<br>        List&lt;String&gt; sortedStream = flattendList.stream()<br>                .sorted()<br>                .collect(Collectors.toList());<br><br>        List&lt;String&gt; customSorting = flattendList.stream()<br>                .sorted((s1,s2)-&gt; s1.length() - s2.length())<br>                .collect(Collectors.toList());<br><br><br>        // 4. distinct() → remove duplicate strings<br>        Long len = flattendList.stream()<br>                .distinct()<br>                .count();<br><br>        // Remove duplicates from sorted list<br>        List&lt;String&gt; distinctList = flattendList.stream()<br>                .distinct()<br>                .collect(Collectors.toList());<br><br><br>        // 5. limit() → take first 3 elements<br>        List&lt;String&gt; limitedList = flattendList.stream()<br>                .limit(3)<br>                .collect(Collectors.toList());<br>        System.out.println(limitedList);<br><br><br>        // 6. peek() → debug/inspect elements (prints during stream flow)<br>        // 7. skip() → skip first 3 elements<br>        Stream&lt;String&gt; stringStreame = listOfLists.stream()<br>                .flatMap(list -&gt; list.stream())<br>                .skip(3);<br><br>        // Using skip + peek together for debugging<br>        limitedList.stream()<br>                .skip(1)<br>                .peek(n -&gt; System.out.println(n))  // prints element during pipeline<br>                .collect(Collectors.toList());<br>    }<br>}</pre><h4>Terminal Operations in Java Streams</h4><p>Terminal operations produce a result and <strong>close</strong> the stream. After this, the stream cannot be reused.</p><pre>public class Terminal_Operations {<br><br>    public static void main(String[] args) {<br><br>        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);<br><br>        // Stream.of() example<br>        Stream&lt;String&gt; strings = Stream.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;);<br><br><br>        // 1. Collect → Convert Stream back to List<br>        List&lt;Integer&gt; numbersStreamList = numbers.stream()<br>                .collect(Collectors.toList());<br><br><br>        // 2. forEach → Terminal: print each number<br>        numbersStreamList.stream()<br>                .forEach(System.out::print);<br><br>        System.out.println();<br><br><br>        // 3. Reduce can mulitple types<br><br>        // Type 1️⃣: reduce(identity, accumulator)<br>        // 0 is starting value<br>        // a accumulated value<br>        // b current element<br>        int sum = numbers.stream()<br>                .reduce(0, (a, b) -&gt; a + b);<br>        System.out.println(&quot;Sum = &quot; + sum);<br><br><br>        // Type 2️⃣: reduce(accumulator)<br>        // No identity provided<br>        // a = first element of the stream<br>        // b = current element (next element)<br>        // returns Optional&lt;T&gt; because stream may be empty<br>        Optional&lt;Integer&gt; max = numbers.stream()<br>                .reduce((a, b) -&gt; a &gt; b ? a : b);<br>        <br>        System.out.println(&quot;Max = &quot; + max.orElse(0));<br><br><br>        // Type 3️⃣: reduce(identity, accumulator, combiner)<br>        // identity = starting value (initial seed)<br>        // accumulator = (a, b) → combines identity/result with current element<br>        // combiner = (x, y) → combines partial results when running in parallel<br>        int sumParallel = numbers.parallelStream()<br>                .reduce(<br>                    0,                       // identity<br>                    (a, b) -&gt; a + b,         // accumulator<br>                    (x, y) -&gt; x + y          // combiner<br>                );<br>        <br>        System.out.println(&quot;Parallel Sum = &quot; + sumParallel);<br><br>        // 4. count → Count elements in stream<br>        long count = strings.count();<br>        System.out.println(&quot;Count = &quot; + count);<br><br><br>        // 5. anyMatch / allMatch / noneMatch → Boolean checks<br>        boolean anyGreaterThan10 = numbers.stream()<br>                .anyMatch(x -&gt; x &gt; 10);<br>        System.out.println(&quot;Any &gt; 10 ? &quot; + anyGreaterThan10);<br><br><br>        // 6. findFirst → Find first element &gt; 5<br>        int firstGreaterThan5 = numbers.stream()<br>                .filter(x -&gt; x &gt; 5)<br>                .findFirst()<br>                .orElse(0);<br>        System.out.println(&quot;First &gt; 5 = &quot; + firstGreaterThan5);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e978c90f5885" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full Guide: Java Collection Framework]]></title>
            <link>https://medium.com/@himanshupapola/full-guide-java-collection-framework-665e15a7a78d?source=rss-3f8413f87d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/665e15a7a78d</guid>
            <category><![CDATA[collection-framework]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Himanshu Papola]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 15:49:40 GMT</pubDate>
            <atom:updated>2025-12-01T22:43:00.566Z</atom:updated>
            <content:encoded><![CDATA[<p>When Java was first introduced, developers didn’t have a unified way to store and manage groups of objects. Everyone wrote their own data structures, which led to <strong>code duplication, bugs, poor performance, and incompatibility</strong>. Even array had its own limitations.<br>To solve this, Java introduced the <strong>Collection Framework</strong>, a standard toolkit of powerful, reusable data structures.</p><h3>Java Collections Framework</h3><p>The <strong>Java Collection Framework </strong>is a <strong>set of ready made data structures and algorithms</strong> that help us store, retrieve, and process data efficiently. Simply Java collection framework provides an architecture to store and manipulate a group of objects.</p><p>It provides us with all kinds of data structure implementations like List, Set, Map, Stack and Queue and a lot. They are dynamic meaning they can grow or shrink in size, and they come with built-in methods for common operations.<strong> java.util</strong> package contains all classes and interface that are required by collection framework.</p><h3>Collections Framework Hierarchy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWHxULu77N92NjorwdHXrA.png" /></figure><h3><strong><em>A. </em></strong><strong><em>Iterable (root interface)</em></strong></h3><p>Iterable&lt;T&gt; is the <strong>top-most root interface</strong> of the Java Collection Framework. Every collection type (List, Set, Queue, etc.) directly or indirectly <strong>implements </strong><strong>Iterable</strong>.</p><blockquote><strong><em>Why Iterable Exists?</em></strong></blockquote><p>We needed:</p><ul><li>A <strong>common way to loop</strong> over any collection.</li><li>A <strong>standard contract</strong> that all collection classes must follow.</li><li>Support for <strong>enhanced for-loop</strong> (for-each loop).</li><li>Support for <strong>Iterator API</strong> (safe traversal).</li></ul><p>Without Iterable, every collection would need its own logic for iteration i.e. not scalable, not maintainable.</p><p>Here, Iterable is an interface. It defines a rule:</p><pre>Iterator&lt;T&gt; iterator();</pre><p>which means, Iterable does not implement this method itself. It only <em>declares</em> it.</p><p>All <strong>collection interfaces </strong>(List, Set, Queue, etc.) <strong>extend Iterable interface.</strong> So any class that implements these interfaces must provide the iterator() method because of this, every collection can provide an Iterator for traversal.</p><p>Example:ArrayList.iterator(),HashSet.iterator(), LinkedList.iterator()</p><p>Here, <strong>Iterator is the object that actually performs the looping.</strong></p><p>It has forwarded only direction to check use<strong> hasNext().</strong><br>We access an element using <strong>next().</strong> <br>To modify we have only <strong>remove()</strong> method.<br>It always start at the beginning.<br>It provides us with<strong> forEach()</strong> method too.</p><pre>public class A01_Iterable_Iterator {<br>    public static void main(String[] args) {<br><br>        // List supports forEach() because it is Iterable<br>        List&lt;String&gt; list = Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);<br><br>        // Using forEach to print elements<br>        list.forEach(i -&gt; System.out.println(i));<br><br>        // Using Iterator to loop through elements<br>        Iterator&lt;String&gt; iterator = list.iterator();<br>        while (iterator.hasNext()) {<br>            System.out.println(iterator.next());<br>        }<br><br>        // HashSet also gives an Iterator for traversal<br>        Set&lt;String&gt; set = new HashSet&lt;&gt;(Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;));<br>        Iterator&lt;String&gt; iterator2 = set.iterator();<br><br>        // Removing an element safely during iteration<br>        while (iterator2.hasNext()) {<br>            String str = iterator2.next();<br>            if (str.equals(&quot;b&quot;)) {<br>                iterator2.remove();<br>            }<br>        }<br><br>        // Printing updated Set<br>        System.out.println(set);<br>    }<br>}</pre><blockquote><strong>List Iterator is a special iterator designed only for Lists.</strong></blockquote><p>It supports:</p><ul><li>forward and backward traversal</li><li>index-based navigation (nextIndex(), previousIndex())</li><li>modification operations (add(), set(), remove()) during iteration</li></ul><p>This functionality is possible because <strong>only List has an ordered and indexed structure</strong>.</p><p><strong>Why only List supports ListIterator?</strong></p><p>The List interface <em>declares</em> two methods:</p><pre>public interface List&lt;E&gt; extends Collection&lt;E&gt; {<br>    ListIterator&lt;E&gt; listIterator();<br>    ListIterator&lt;E&gt; listIterator(int index);<br>}</pre><p>Because List declares these methods:</p><ul><li>Any class that implements List (like ArrayList, LinkedList, Vector)<br> <strong>must also implement these methods</strong>.</li></ul><pre>public class A02_List_Iterator {<br>    public static void main(String[] args) {<br><br>        List&lt;String&gt; list = new ArrayList&lt;&gt;(Arrays.asList(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;));<br>        ListIterator&lt;String&gt; listIterator = list.listIterator();<br><br>        while (listIterator.hasNext()){<br>            System.out.print(listIterator.next() + &quot; &quot;);<br>        }<br><br>        while (listIterator.hasPrevious()){<br>            System.out.print(listIterator.previous() + &quot; &quot;);<br>        }<br><br>        ListIterator&lt;String&gt; listIterator2 = list.listIterator();<br>        while (listIterator2.hasNext()){<br>            System.out.println(listIterator2.nextIndex());<br>            System.out.println(listIterator2.next());<br>        }<br>        System.out.println();<br>    }<br>}</pre><h3><strong><em>B. </em></strong><strong><em>Collection (Interface)</em></strong></h3><p>Collection is the <strong>root interface</strong> for all collection types in Java, except for Map. Here collection extends iterable interface thus inheriting its properties.</p><p>It defines the <strong>basic operations</strong> that any group of objects should support like adding, removing, checking size, checking emptiness, checking containment, and iteration.</p><p>A collection represents a group of objects, known as its elements.</p><p><strong>Major child interfaces of Collection:</strong></p><p>The Collection interface has <strong>three main sub-interfaces</strong>:</p><pre>Collection<br>   ├── List<br>   ├── Set<br>   └── Queue</pre><p>Because ArrayList, LinkedList, HashSet, etc. all <strong>implement Collection</strong>, they inherit all the common operations defined in the Collection interface.</p><p><strong>These methods allow us to:</strong> Add elements, Remove elements, Check presence, Convert to array, IterateBulk operations (addAll, removeAll, retainAll), Check size and emptiness.</p><pre>public class A01_Collection_Interface {<br>    public static void main(String[] args) {<br><br>        // Creating a Collection using ArrayList implementation<br>        // Implementation could have been Set or Queue classes too.<br>        Collection&lt;String&gt; collection = new ArrayList&lt;&gt;();<br><br>        // Adding elements<br>        collection.add(&quot;Himanshu&quot;);<br>        collection.add(&quot;Raj&quot;);<br>        collection.add(&quot;Daniel&quot;);<br>        collection.add(&quot;Alex&quot;);<br><br>        // Checking if an element exists<br>        System.out.println(collection.contains(&quot;Himanshu&quot;));<br>        System.out.println(collection.contains(&quot;Raju&quot;));<br><br>        // Converting Collection to array<br>        // Creating string array with array size 0 (for resizing)<br>        String[] str = collection.toArray(new String[0]);<br>        System.out.println(Arrays.toString(str));<br><br>        // Iterating using Iterator<br>        Iterator&lt;String&gt; iterator = collection.iterator();<br>        while (iterator.hasNext()) {<br>            System.out.println(iterator.next());<br>        }<br><br>        // Removing elements<br>        collection.remove(&quot;Himanshu&quot;);<br><br>        // Adding multiple elements<br>        collection.addAll(List.of(&quot;Himanshu&quot;, &quot;Ram&quot;));<br><br>        // Removing all matching elements<br>        collection.removeAll(List.of(&quot;Himanshu&quot;, &quot;Ram&quot;, &quot;Max&quot;));<br><br>        // Keeping only the specified elements (others removed)<br>        collection.retainAll(List.of(&quot;Himanshu&quot;, &quot;Ram&quot;, &quot;Max&quot;));<br><br>        // Checking if all elements exist in the collection itself (always true)<br>        System.out.println(collection.containsAll(collection));<br><br>        // Checking empty and size<br>        System.out.println(collection.isEmpty());<br>        System.out.println(collection.size());<br><br>        // Clearing all elements<br>        collection.clear();<br><br>        // Another example with a Collection<br>        Collection&lt;String&gt; days = new ArrayList&lt;&gt;();<br>        days.add(&quot;Monday&quot;);<br>        days.add(&quot;Tuesday&quot;);<br>        days.add(&quot;Wednesday&quot;);<br><br>        // Adding a list of elements<br>        days.addAll(List.of(&quot;Thursday&quot;, &quot;Friday&quot;, &quot;Saturday&quot;, &quot;Sunday&quot;));<br><br>        // Removing multiple elements<br>        days.removeAll(List.of(&quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;));<br><br>        // Checking size<br>        days.size();<br><br>        // Clearing all elements<br>        days.clear();<br><br>        // New operations (basic checks)<br>        collection.add(&quot;Hi&quot;);<br>        collection.remove(&quot;hi&quot;);        // case-sensitive remove<br>        collection.contains(&quot;hi&quot;);      // case-sensitive contains<br>        collection.clear();             // remove everything<br>        collection.size();              // current size<br>        collection.isEmpty();           // check if empty<br>        collection.toArray(new String[0]); // convert to array<br>    }<br>}</pre><h3><strong><em>C. </em></strong><strong><em>List (Interface)</em></strong></h3><p>List is a sub interface of Collection that represents an ordered, indexed, and duplicate-allowed sequence of elements.</p><p>List provides additional List-specific methods that Collection does not have, such as get(int index), set(int index, E element), add(int index, E element), remove(int index), indexOf(Object o), lastIndexOf(Object o), listIterator() and subList(int from, int to).</p><p>Class Implementation of List:</p><pre>List<br>   ├── ArrayList<br>   ├── LinkedList<br>   ├── Vector<br>   └── Stack</pre><h4><strong>List Implementation Classes:</strong></h4><blockquote><strong><em>1. ArrayList:</em></strong></blockquote><p>In Java, ArrayList is a <strong>resizable-array implementation</strong> of the List interface, part of the java.util package. Unlike normal arrays, an ArrayList can <strong>automatically grow or shrink</strong> as we add or remove elements.</p><p><strong>🕸️ Key Characteristics of ArrayList:</strong></p><p><strong>1. Dynamic Sizing: </strong>You don’t need to give an initial size, internally, Java creates a <strong>dynamic array</strong>. When this array becomes full, the ArrayList <strong>increases its capacity</strong> automatically.</p><p><strong>2. Default Capacity = 10</strong></p><p>If you create an ArrayList like:</p><pre>ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();</pre><p>Java lazily initializes an internal array of <strong>size 10</strong> the moment you add the first element.</p><p><strong>3. Automatic Growth = 1.5x of current capacity</strong></p><p>When ArrayList becomes full (size==capacity)</p><pre>newCapacity = oldCapacity + (oldCapacity / 2)</pre><p>Example:</p><ul><li>Old capacity = 10<br> New = 10 + 5 = <strong>15</strong></li></ul><p>So ArrayList grows by <strong>50% each time</strong>.</p><p><strong>4. Indexed Access: </strong>Fast get(index) and set(index, value) operations → <strong>O(1)</strong> time, works like a normal array internally.</p><p><strong>5. Ordered Collection: </strong>Maintains insertion order (0 → n-1).</p><p><strong>6. Allows Duplicates: </strong>Any number of duplicates are allowed.</p><p><strong>7. Not Synchronized: </strong>ArrayList is <strong>not thread-safe</strong>.</p><p>For thread safety:</p><pre>List&lt;String&gt; synchronizedList = Collections.synchronizedList(new ArrayList&lt;&gt;());</pre><p><strong>8. Allows Null Elements: </strong>Multiple null entries are allowed.</p><p><strong>🕸️ Different Ways to Create an ArrayList:</strong></p><pre>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;<br><br>public class A02_ArrayList {<br>    public static void main(String[] args) {<br>          // 1️⃣ Using Default Constructor (Most Common)<br>          ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();<br><br>          // 2️⃣ With Initial Capacity<br>          ArrayList&lt;String&gt; list2 = new ArrayList&lt;&gt;(20);<br>          <br>          // 3️⃣ Copying from Another Collection<br>          ArrayList&lt;String&gt; list3 = new ArrayList&lt;&gt;(list);<br>          ArrayList&lt;Integer&gt; list7 = new ArrayList&lt;&gt;(List.of(1,2,3,4,5));<br>          ArrayList&lt;Integer&gt; list8 = new ArrayList&lt;&gt;(Arrays.asList(1,2,3,4,5));<br>          <br>          // 4️⃣ Raw ArrayList (Not Recommended)<br>          ArrayList list4 = new ArrayList();<br>          list4.add(&quot;Apple&quot;);<br>          <br>          // 5️⃣ Fixed-Size List using Arrays.asList()<br>          // You cannot add or remove elements modify allowed<br>          List&lt;String&gt; temp = Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);<br>          ArrayList&lt;String&gt; list9 = new ArrayList&lt;&gt;(temp);<br>          <br>          // 6️⃣ Immutable List using List.of() (Java 9+)<br>          // A completely immutable list, No add/remove/set allowed<br>          // No null values allowed  <br>          // High-performance and memory-efficient<br>          List&lt;String&gt; list5 = List.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);<br>          ArrayList&lt;String&gt; list10 = new ArrayList&lt;&gt;(list5);<br>          <br>          // 7️⃣ Creating an ArrayList Using List Interface (Recommended)<br>          List&lt;String&gt; list11 = new ArrayList&lt;&gt;();<br><br>          // 8️⃣ Creating class object ArrayList<br>          ArrayList&lt;Student&gt; students = new ArrayList&lt;&gt;();<br>          students.add(new Student(&quot;Aman&quot;, 22));<br>          students.add(new Student(&quot;Ravi&quot;, 20));<br><br>          list3.sort((a, b) -&gt; b.length() - a.length());<br>  }<br>}</pre><blockquote><strong><em>2. LinkedList:</em></strong></blockquote><p>LinkedList is another implementation of the List interface, but unlike ArrayList (which uses a dynamic array), LinkedList uses a <strong>doubly linked list</strong> internally. This makes it very efficient for <strong>insertions and deletions</strong>, especially at the beginning and end.</p><p><strong><em>LinkedList implements both the </em></strong><strong><em>List interface and the </em></strong><strong><em>Deque interface.</em></strong></p><p>So LinkedList behaves like:</p><ul><li>a <strong>List</strong> (ordered, index-based, allows duplicates)</li><li>a <strong>Deque</strong> (double-ended queue → add/remove at both ends)</li><li>This gives us ablitiy to make our Linked list behave like queue, stack and list with their specific methods.</li></ul><pre>public class LinkedLists {<br>    public static void main(String[] args) {<br>        LinkedList&lt;String&gt; cars = new LinkedList&lt;&gt;();<br><br>        cars.add(&quot;BMW&quot;);<br>        cars.add(&quot;Ford&quot;);<br><br>        // Almost all method are avb<br>        cars.addFirst(&quot;Toyota&quot;);<br>        cars.addLast(&quot;Honda&quot;);<br>        cars.removeFirst();<br>        cars.removeLast();<br><br><br>        System.out.println(cars.getFirst());<br>        System.out.println(cars.getLast());<br><br>        System.out.println(cars);<br>    }<br>}</pre><blockquote><strong><em>3. Stack:</em></strong></blockquote><p>Stack is a <strong>class</strong> in Java that represents the <strong>LIFO (Last-In-First-Out)</strong> data structure. It is part of <strong>java.util</strong> and is a <strong>legacy class</strong> (older design), but still used in simple programs and interviews.</p><p>Internally, Stack actually extends <strong>Vector</strong>, which means it is <strong>synchronized</strong> (thread-safe but slower) and uses <strong>dynamic array</strong> internally</p><p>It’s not recommended for modern applications prefer <strong>Deque (ArrayDeque)`</strong> to implement stacks.</p><pre>public class Stacks {<br>  public static void main(String[] args) {<br>        Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();<br><br>        Stack&lt;Integer&gt; stack2 = new Stack&lt;&gt;();<br>        stack2.push(1);<br>        stack2.push(2);<br>        stack2.push(3);<br>        stack2.pop();<br>        System.out.println(stack.isEmpty());<br>        System.out.println(stack2);<br><br>        stack.push(1);<br>        stack.push(2);<br>        stack.pop();<br>        System.out.println(stack.isEmpty());<br>        System.out.println(stack.peek());<br>        System.out.println(stack);<br>        System.out.println(stack2.peek());;<br>    }<br>}</pre><blockquote><strong><em>4. Vector:</em></strong></blockquote><p>Vector is a <strong>legacy class</strong> in Java (from Java 1.0) that implements the <strong>List</strong> interface. It is very similar to ArrayList, but with one key difference:</p><p><strong>Vector is synchronized (thread-safe) and ArrayList is NOT synchronized.</strong></p><p>Because of this, Vector is <strong>slower</strong> than ArrayList and almost nobody uses it in modern code.</p><pre>public class Vectors {<br>    public static void main(String[] args) {<br>        Vector&lt;String&gt; v = new Vector&lt;&gt;();<br><br>        v.add(&quot;A&quot;);<br>        System.out.println(v.get(0));<br>  }<br>}</pre><h3><strong><em>D. </em></strong><strong><em>Set (Interface)</em></strong></h3><p>Set is a unordered c<strong>ollection</strong> that <strong>does not allow duplicate elements</strong>. It models the <strong>mathematical set</strong>, where each element appears only once. It does not maintian the specific order of element.</p><p>Set interface provides powerful methods for union (addAll), intersection (retainAll), difference (removeAll), search (contains/containsAll), and cleaning (clear), while always preventing duplicates.</p><p><strong>🕸️ Key Characteristics of Set</strong></p><p><strong>1. No Duplicates Allowed: </strong>If you try to add a duplicate, the Set will ignore it.</p><pre>Set&lt;Integer&gt; s = new HashSet&lt;&gt;();<br>s.add(10);<br>s.add(10); // ignored</pre><p><strong>2. Unordered Collection: </strong>Most Set implementations <strong>do not maintain order</strong>.</p><p><strong>3. Allows null (except TreeSet): </strong>HashSet → allows one null, LinkedHashSet → allows one null, TreeSet → ❌ does NOT allow null (because it uses sorting)</p><p><strong>4. Fast Searching: </strong>Sets are optimized for <strong>quick lookup</strong>, unlike lists.</p><p>It’s common implemenation classes are:</p><pre>Set<br> ├── HashSet<br> ├── LinkedHashSet<br> └── SortedSet<br>        └── TreeSet</pre><h4>Set Implementation Classes:</h4><blockquote><strong><em>1. HashSet:</em></strong></blockquote><p>HashSet is a Java class that implements the Set interface and extends AbstractSet. It stores <strong>unique elements only</strong>, has <strong>no guaranteed order</strong>, and gives <strong>O(1)</strong> performance for add, remove, and search operations.</p><p><strong>Key Points Before Understanding the Internals:</strong></p><p><strong>1. HashSet uses HashMap internally: </strong>Every element you add to a HashSet is stored as a <strong>key</strong> inside a HashMap, and the value is a single constant dummy object <strong>(</strong><strong>PRESENT)</strong> used for all elements.</p><p><strong>2. No ordering: </strong>Because HashSet uses hashing, elements are not stored in<strong> </strong>insertion order and appear in <strong>random order.</strong></p><p><strong>3. Only one null allowed: </strong>HashSet allows <strong>one null element</strong>, because HashMap allows <strong>one null key</strong>.</p><p><strong>4. Default capacity &amp; load factor</strong></p><ul><li><strong>Default capacity:</strong> 16, <strong>Load factor:</strong> 0.75</li></ul><pre>// Resizing happens when:<br>size &gt; capacity * loadFactor<br><br>// (Example: 16 * 0.75 = 12 → resize occurs when size crosses 12)</pre><p><strong>5. No direct get(index): </strong>HashSet has <strong>no get(key)</strong> or <strong>get(index)</strong> method.<br> You must iterate using iterator(),enhanced for-loop, streams.</p><p><strong>6. Fail-Fast Iterator: </strong>If the HashSet is modified during iteration, it throws:</p><pre>ConcurrentModificationException</pre><p>Except when using the iterator’s own remove() method.</p><h4><strong>Internal Working of HashSet: (Important)</strong></h4><p>When you write and initalize with first element:</p><pre>HashSet&lt;String&gt; set = new HashSet&lt;&gt;();<br><br>A HashMap is created.<br>HashMap&#39;s default capacity (max size it can store) = 16<br>HashMap&#39;s default load factor = 0.75<br><br>Let capacity = 16 (default)<br>Load factor = 0.75<br><br>Threshold = 16 × 0.75 = 12 (elements filled)<br><br>When the 13th element is added, HashMap resizes to capacity 32. <br>newCapacity = oldCapacity * 2<br>(multiple of 2)</pre><p>HashMap have <strong>lazy initialization </strong>which means after first insertion capacity becomes 16 earilier it was 0.</p><p>Since <strong>HashSet is just a wrapper over HashMap</strong>, everything about storage, resizing, hashing, and collisions comes from <strong>HashMap</strong>.</p><h4><strong>How HashSet stores elements internally</strong></h4><p>When you do:</p><pre>HashSet&lt;String&gt; set = new HashSet&lt;&gt;();<br>set.add(&quot;A&quot;);<br><br>// Internally<br>map.put(&quot;A&quot;, PRESENT);</pre><p><strong>Step 1 —</strong> HashSet stores every element as a key in HashMap</p><p>When you write:</p><pre>HashSet&lt;String&gt; set = new HashSet&lt;&gt;();<br>set.add(&quot;A&quot;);<br><br>// Internally it becomes<br>// HashSet itself does NO hashing,<br>// No bucket calculation,<br>// No collision handling.<br><br>👉 HashSet just calls HashMap.<br>map.put(&quot;A&quot;, PRESENT);</pre><p>&quot;A&quot; becomes the <strong>key, </strong>PRESENT is a <strong>dummy constant value</strong> used for all elements. HashSet stores <strong>only keys</strong>, values are ignored.</p><p><strong>Step 2 — </strong>Hashing (decides where element goes)</p><p>After map.put(“A”,PRESENT),</p><p><strong>i.</strong> HashMap calls the element’s <strong>hashCode(</strong>) and improves it using <strong>Hash Spread.</strong></p><pre>// Takes key&#39;s hashCode<br>&quot;A&quot;.hashCode()<br><br>// Then spreads bits using XOR to reduce bucket collisions<br>finalHash = hash ^ (hash &gt;&gt;&gt; 16);</pre><p><strong>ii. </strong>HashMap calculates the array position (bucket index) where the key–value pair will be stored. Note that even if two elements are different, their bucket index can still be the same. Bucket index not decide element equality — hashCode + equals() do.</p><pre>int index = (n - 1) &amp; finalHash;<br><br>Where:<br>n = current capacity (initially 16)<br>&amp; = bitwise AND<br>This ensures the index falls within array bounds (0–15).</pre><p><strong>iii.</strong> Collision Handling (when two elements land in the same bucket)</p><p>After HashMap calculates the bucket index, two situations are possible:</p><blockquote><strong><em>1. If the bucket is EMPTY → insert directly</em></strong></blockquote><p>HashMap stores &quot;A&quot; in that bucket as a new node.</p><blockquote><strong><em>2. If the bucket is not empty → collision occurs</em></strong></blockquote><p>When two elements land in the same bucket (collision),<br>HashMap must check if the new element already exists.</p><p>HashMap then checks:</p><ol><li><strong>If hashes are different → add as next node (Linked List)</strong></li><li><strong>If hashes are same → call existingKey.equals(newKey)</strong></li></ol><p><strong>A. If equals() returns true → Duplicate</strong></p><ul><li>The element already exists in HashSet</li><li>HashSet will NOT insert it</li><li>add() returns <strong>false</strong></li></ul><p><strong>B. If equals() returns false → Different element</strong></p><ul><li>Not a duplicate</li><li>HashMap inserts it into the bucket</li><li>As a <strong>linked list node</strong>, or</li><li>A <strong>tree node</strong> (if treeified)</li></ul><p><strong>iv. Resize &amp; Rehash (When HashSet grows)</strong></p><p>HashMap (used internally by HashSet) expands automatically when too many elements are stored using threshold and Loadfactor.</p><pre>if (capacity*loadFactor &gt; total current element)<br>      Increase by size of 2 <br>16 → 32 → 64 → 128 → ...</pre><p>After resizing, HashMap must redistribute all elements because:</p><ul><li>bucket count changed</li><li>bucket index calculation depends on capacity</li></ul><p>So HashMap <strong>recomputes the bucket index</strong> for every existing key and places them in their new buckets.</p><p>When HashSet becomes 75% full, HashMap doubles in size and redistributes all keys so buckets stay evenly filled and performance stays fast.</p><p><strong>HashSet Methods:</strong></p><pre> public class A01_Set_Interface {<br>    public static void main(String[] args) {<br>        Set&lt;String&gt; set = new HashSet&lt;&gt;();<br>        Set&lt;String&gt; set2 = new HashSet&lt;&gt;();<br>        Set&lt;Integer&gt; set3 = Set.of(1,2,3);<br><br>        System.out.println(set2) ;<br>        set.add(&quot;a&quot;);<br>        set.add(&quot;b&quot;);<br>        set.add(&quot;c&quot;);<br><br>        set2.add(&quot;d&quot;);<br>        set2.add(&quot;a&quot;);<br>        set2.add(&quot;b&quot;);<br><br>        System.out.println(set);<br>        System.out.println(set2);<br><br>        //common element remains<br>        set.retainAll(set2);<br>        System.out.println(set);<br><br>        //ad set2 to set1 no dupes<br>        set.addAll(set2);<br>        System.out.println(set);<br><br>        //Return boolean of all elements in 1 and 2 are same<br>        System.out.println(set.containsAll(set2));<br><br>        // Remove all common elements<br>        set.removeAll(set2);<br>        System.out.println(set);<br><br>        // Thread safe<br>        Set&lt;Integer&gt; set4 = new ConcurrentSkipListSet&lt;&gt;();<br>        set4.add(1);<br>        set4.add(2);<br>    }<br>}</pre><blockquote><strong><em>2. LinkedHashSet:</em></strong></blockquote><p>LinkedHashSet is a Set implementation that combines:</p><ul><li><strong>HashSet</strong> (for O(1) performance)</li><li><strong>LinkedList-like order tracking</strong> (for maintaining insertion order)</li></ul><p>So it is basically:</p><pre>LinkedHashSet = HashSet + Doubly LinkedList (for order)<br><br>Set&lt;String&gt; set = new LinkedHashSet&lt;&gt;();</pre><blockquote><strong><em>3. TreeSet:</em></strong></blockquote><p>TreeSet is a Set implementation that:</p><ul><li>Stores <strong>unique elements, </strong>Maintains <strong>sorted order</strong></li><li>Uses a <strong>Red-Black Tree</strong> internally, Gives <strong>O(log n)</strong> performance for add, remove, search</li></ul><pre>public class A03_TreeSet {<br>    public static void main(String[] args) {<br>        SortedSet&lt;Integer&gt; sortedSet = new TreeSet&lt;&gt;();<br><br>        sortedSet.add(2);<br>        sortedSet.add(1);<br>        sortedSet.add(12);<br>        sortedSet.add(-1);<br>        sortedSet.add(7);<br><br>        System.out.println(sortedSet);<br><br>        System.out.println(sortedSet.first());//lowest<br>        System.out.println(sortedSet.last());//highest<br><br>        // All elements less then highest<br>        System.out.println(sortedSet.headSet(sortedSet.last()));<br><br>        // Returns subset between range<br>        List&lt;Integer&gt; list = new ArrayList&lt;&gt;(sortedSet.subSet(1, 12));<br>        System.out.println(list);<br>    }<br>}</pre><h3>E. Queue (Interface)</h3><p>Queue in Java represents a <strong>First-In-First-Out (FIFO)</strong> data structure.<br> It is used when elements must be processed <strong>in the order they arrive</strong>.</p><p>Queue is part of the <strong>java.util</strong> package and extends the <strong>Collection</strong> interface.</p><p>The Queue interface provides two sets of methods:</p><p><strong>A. Methods that throw exceptions</strong></p><pre>| Operation            | Method    | Throws Exception?            |<br>| -------------------- | --------- | ---------------------------- |<br>| Insert               | add(e)    | Yes (IllegalStateException)  |<br>| Remove               | remove()  | Yes (NoSuchElementException) |<br>| Peek (front element) | element() | Yes                          |</pre><p><strong>B. Methods that return special values (recommended)</strong></p><pre>| Operation | Method   | Returns         |<br>| --------- | -------- | --------------- |<br>| Insert    | offer(e) | true/false      |<br>| Remove    | poll()   | element or null |<br>| Peek      | peek()   | element or null |</pre><blockquote><strong><em>Implementations of Queue:</em></strong></blockquote><p>Common classes that implement Queue:</p><ol><li><strong>LinkedList (most common):</strong> FIFO + also supports List &amp; Deque features.</li></ol><p><strong>2. PriorityQueue (elements sorted by priority, NOT FIFO):</strong> Uses a binary heap internally.</p><p><strong>3. ArrayDeque (most efficient):</strong> Fastest queue implementation, no capacity restrictions (unlike array-based queues).</p><p><strong>4. BlockingQueue (for multithreading)</strong></p><pre>public class A01_Queue_Interface {<br>    public static void main(String[] args) {<br>        Queue&lt;String&gt; queue = new LinkedList&lt;&gt;();<br><br>        // InQueue return boolean better then add<br>        queue.offer(&quot;A&quot;);<br>        queue.offer(&quot;B&quot;);<br>        queue.offer(&quot;C&quot;);<br><br>        System.out.println(&quot;Queue: &quot; + queue);<br><br>        // See the first element better<br>        System.out.println(&quot;Peek: &quot; + queue.peek());<br><br>        // Return and remove the first element else throws null<br>        System.out.println(&quot;Poll: &quot; + queue.poll());<br><br>        System.out.println(queue.isEmpty());<br>        System.out.println(queue.size());<br>    }<br>}</pre><h3>F. Map (Interface)</h3><p>Map is a core interface in Java used to store <strong>key–value pairs</strong>. Map lives in java.util package and is one of the most important data structures.</p><p>It’s not a subtype of collection interface and no duplicate keys are allowed.</p><p><strong>Key Characteristics of Map:</strong></p><ol><li><strong>Unique Keys:</strong> Two keys cannot be the same. If you insert a duplicate key, the <strong>old value is replaced</strong>.</li><li><strong>Allows Duplicate Values:</strong> Values can be anything, including duplicates.</li><li><strong>Allows One Null Key (depends on implementation): </strong>HashMap and LinkedHashMap allow 1 null key while TreeMap no null key (sorted structure)</li><li>Fast Lookup Finding a value using a key is very fast, usually <strong>O(1)</strong> for HashMap.</li></ol><p><strong>Map Hierarchy:</strong></p><pre>Map (not a child of Collection)<br>   ├── HashMap<br>   ├── LinkedHashMap<br>   ├── TreeMap<br>   └── Hashtable</pre><ol><li><strong>HashMap:</strong></li></ol><p>HashMap is one of the most important data structures in Java.<br>It stores <strong>key–value pairs</strong>, allows <strong>one null key</strong>, multiple null values, and gives <strong>O(1)</strong> average performance. It is part of <strong>java.util</strong> package.</p><blockquote><strong>How HashMap Works (Simple as already discussed)</strong></blockquote><p>When you call:</p><pre>map.put(&quot;A&quot;, 100);</pre><p>HashMap:</p><ol><li>Calls &quot;A&quot;.hashCode()</li><li>Spreads the hash bits (hash ^ (hash &gt;&gt;&gt; 16))</li><li>Calculates bucket index index = (capacity - 1) &amp; hash</li><li>Stores the key–value pair in that bucket</li><li>If the bucket is already filled → collision handling</li><li>Checks duplicates using equals(key)</li><li>Resizes when 75% full.</li></ol><p><strong>HashMap Methods:</strong></p><pre>import java.util.HashMap;<br>import java.util.Map;<br><br>public class A02_Hashmap {<br>    public static void main(String[] args) {<br>        // Create HashMap with String keys, Number values<br>        HashMap&lt;String, Number&gt; maps = new HashMap&lt;&gt;(); <br><br>        maps.put(&quot;A&quot;, 0); // Insert key-value pair (if exist replace)<br>        maps.put(&quot;B&quot;, 1);<br>        maps.put(&quot;C&quot;, 2);<br>        maps.put(&quot;D&quot;, 3);<br>        System.out.println(maps); // Print full map<br><br>        maps.putIfAbsent(&quot;A&quot;, 4); // Insert only if key is NOT present<br>        System.out.println(maps); // &quot;A&quot; exists, so value remains unchanged<br><br>        System.out.println(maps.getOrDefault(&quot;E&quot;, 4)); // Return value if exists, else return default (4)<br>        System.out.println(maps.containsKey(&quot;E&quot;));     // Check if key exists<br>        System.out.println(maps.containsValue(0));     // Check if any value equals 0<br>        maps.remove(&quot;D&quot;);                              // Remove key &quot;D&quot;<br><br>        System.out.println(maps.keySet());    // Print all keys<br>        System.out.println(maps.values());    // Print all values<br>        System.out.println(maps.entrySet());  // Print all key-value pairs<br><br>        // Iterate through entries<br>        for (Map.Entry&lt;String, Number&gt; entry : maps.entrySet()) { <br>            System.out.println(entry.getKey() + &quot; : &quot; + entry.getValue());<br>        }<br><br>        // Iterate through keys<br>        for (String key : maps.keySet()) { <br>            System.out.println(maps.get(key));<br>        }<br><br>        // Iterate through values<br>        for (Number value : maps.values()) { <br>            System.out.println(value);<br>        }<br>    }<br>}</pre><p>2. <strong>TreeMap:</strong></p><p>TreeMap is a Map implementation that <strong>stores key–value pairs in sorted order</strong>. It uses a <strong>Red-Black Tree</strong> internally, so all operations take <strong>O(log n)</strong> time. It stores sorted keys.</p><p>TreeMap throws NullPointerException for null keys but null values are allowed.</p><pre>TreeMap&lt;Integer, String&gt; map = new TreeMap&lt;&gt;();<br><br>// TreeMap stores keys in sorted (ascending) order.<br>// Insertion order does NOT matter; sorting is automatic.<br><br>map.put(2, &quot;Apple&quot;);   // Insert key 2<br>map.put(1, &quot;Banana&quot;);  // Insert key 1<br>map.put(12, &quot;Orange&quot;); // Insert key 12<br><br>System.out.println(map);  <br>// Output: {1=Banana, 2=Apple, 12=Orange}<br>// Keys appear in sorted order, not the order they were inserted.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=665e15a7a78d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive: Exception Handling]]></title>
            <link>https://medium.com/@himanshupapola/deep-dive-exception-handling-565a9cab06b4?source=rss-3f8413f87d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/565a9cab06b4</guid>
            <dc:creator><![CDATA[Himanshu Papola]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 17:41:48 GMT</pubDate>
            <atom:updated>2025-11-20T17:41:48.237Z</atom:updated>
            <content:encoded><![CDATA[<p>Exception Handling in Java allows developers to manage runtime errors effectively using mechanism like try-catch block, finally block, throwing exception, custom exception.</p><p>An exception is unwanted event that occur during execution of program and distrupt the normal program execution.</p><h4>Java Exceptions Hierarchy:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0i5hFSNueV5G24m6o744Q.png" /><figcaption>Overview: GeekForGeek</figcaption></figure><p>Everything starts from the top-most class:</p><blockquote><strong><em>1. Throwable</em></strong></blockquote><p>Throwable is the <strong>root of all errors and exceptions</strong> in Java.<br> It has two major children:</p><pre>java.lang.Throwable</pre><p>Error — problems we should not try to recover from.<br>Exception — problems our application should usually handle</p><blockquote><strong><em>1.1. Error (Serious system issues — Not handled in code)</em></strong></blockquote><p>Errors represent problems in the JVM or system. We don’t catch them because the system is already unstable.</p><p><strong>Common types: </strong>VirtualMachineError, OutOfMemoryError, StackOverflowError, AssertionError</p><p>We rarely catch these. Instead, we <strong>fix the root cause</strong> (memory leak, infinite recursion, classpath issues).</p><blockquote><strong><em>1.2 Exception (Things we should handle)</em></strong></blockquote><p>An <strong>Exception</strong> is an <strong>unexpected event</strong> that happens <strong>while the program is running</strong>, which <strong>disrupts the normal flow</strong> of your code.</p><p>It represents a <strong>problem that your program <em>can</em> and <em>should</em> handle</strong>.</p><p>In Java, every exception is actually an <strong>object</strong>, created from some subclass of Exception.</p><p><strong>What happens when an Exception occurs?</strong></p><p><strong>Steps:</strong></p><ol><li>Code hits a problem</li><li>Java creates an Exception object</li><li>It is <strong>thrown</strong> (propagates up the call stack)</li><li>If we don’t catch it → program <strong>terminates</strong> with a stack trace</li><li>If we catch it → we handle and recover from it.</li></ol><h4><strong>Two Types of Exceptions:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXms8vNHcuTAx7wCFupjzA.png" /></figure><p><strong>A. Built In Exception:</strong></p><p>They are pre-defined exception classes provided by Java to handle common error during program execution.</p><ol><li><strong>Checked Exception:</strong></li></ol><p>Checked Exception are called compile time exception becuase these exception are checked at compile time by the compiler.</p><p>These exception must be handled using try, catch block or declared using throws. Simply checked exceptions are <strong>exceptions that the compiler forces us to handle</strong>.</p><p>Meaning, at compile time Java <em>checks</em> whether:</p><ul><li>If a method can throw a checked exception,</li><li>We must either <strong>handle it</strong> using try/catch</li><li>Or <strong>declare it</strong> using throws</li></ul><p>Internall all checked exception, extends exception thus they need to be handled.</p><pre>import java.io.FileNotFoundException;<br>import java.io.FileReader;<br>import java.io.IOException;<br>import java.sql.Connection;<br>import java.sql.DriverManager;<br>import java.sql.SQLException;<br><br>//Exception Common Cause<br>//IOException             Input/output failures<br>//FileNotFoundException   File not found during file operations<br>//SQLException            DB query issues<br>//ClassNotFoundException  Dynamic class loading fails<br>//InstantiationException  Trying to create an object of abstract/interface<br>//InterruptedException    Thread interrupted<br>//NoSuchMethodException   Reflection: method not found<br>//ParseException          Date parsing fails<br><br>class FileRead {<br>    public void readFile() throws IOException {<br>        FileReader fr = new FileReader(&quot;file.txt&quot;);<br>        int data = fr.read();<br>        fr.close();<br>    }<br>}<br><br>class SQLStart {<br>    public static void startDriver() throws SQLException {<br>        Connection conn = DriverManager.getConnection(&quot;dsfds&quot;, &quot;dsfs&quot;, &quot;fdsf&quot;);<br>    }<br>}<br><br>public class A01_Checked_Exception {<br>    public static void main(String[] args) {<br>        try {<br>            FileRead f = new FileRead();<br>            f.readFile();<br>            Class.forName(&quot;com.mysql.jdbc.Driver&quot;);<br>            SQLStart.startDriver();<br><br>        } catch (FileNotFoundException | ClassNotFoundException | SQLException e) {<br>            System.out.println(&quot;Either file not found or SQL error: &quot; + e.getMessage());<br>        }<br>        catch (IOException e) {<br>            e.printStackTrace();<br>        }<br><br>    }<br>}</pre><p><strong>2. Unchecked Exception: (Runtime Exception)</strong></p><p>These are exception not checked at compile time. In Java exception under Error and runtime class are unchecked exception.</p><p>These occur due to <strong>programming errors and bugs in our code</strong>.They extends RuntimeException.</p><p>Java assumes:</p><ul><li>If there is a bug, fix the bug, don’t try to handle it everywhere.</li><li>We should prevent them, not force-handle them.</li><li><strong>But we still handle unchecked exceptions at higher levels (like validation or global exception handlers) so the application doesn’t crash.</strong></li></ul><pre>class Unchecked_Examples {<br>    public static void uncheck() {<br><br>        // 1. ArithmeticException - divide by zero<br>        try {<br>            int result = 10 / 0;<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;ArithmeticException&quot;);<br>        }<br><br>        // 2. NullPointerException<br>        try {<br>            String str = null;<br>            System.out.println(str.length());<br>        } catch (NullPointerException e) {<br>            System.out.println(e.getMessage());<br>        }<br><br>        // 3. ArrayIndexOutOfBoundsException<br>        try {<br>            int[] arr = {1, 2, 3};<br>            System.out.println(arr[5]);<br>        } catch (ArrayIndexOutOfBoundsException e) {<br>            System.out.println(&quot;ArrayIndexOutOfBoundsException caught: &quot; + e.getMessage());<br>        }<br><br>        // 4. IllegalArgumentException<br>        try {<br>            setAge(-5);<br>        } catch (IllegalArgumentException e) {<br>            System.out.println(&quot;IllegalArgumentException &quot; + e.getMessage());<br>        }<br><br>    }<br>    static void setAge(int age) {<br>        if (age &lt; 0) {<br>            throw new IllegalArgumentException(&quot;Age cannot be negative&quot;);<br>        }<br>        System.out.println(&quot;Age set to &quot; + age);<br>    }<br>}<br><br>public class A02_Unchecked_Exception {<br>    public static void main(String[] args) {<br>        Unchecked_Examples.uncheck();<br>    }<br>}</pre><blockquote><strong><em>Try–Catch–Finally</em></strong></blockquote><ol><li><strong>try</strong></li></ol><ul><li>Put risky code here.</li><li>If exception occurs → jump to catch (or finally if no catch).</li></ul><p><strong>2. catch</strong></p><ul><li>Runs <strong>only</strong> when the matching exception occurs.</li><li>You can have multiple catches.</li><li>Most specific catch should come first.</li></ul><p><strong>3. finally</strong></p><ul><li><strong>It always runs even if, </strong>exception occurs, no exception, catch exists or not, even if we return inside try/catch</li><li>Used for <strong>cleanup</strong>: closing files, DB, streams, releasing resources.</li></ul><pre>public class A03_tryCatchFinally {<br>    public static void main(String[] args) {<br>        try {<br>            int x = 10 / 0;<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Caught exception&quot;);<br>        } finally {<br>            System.out.println(&quot;Cleanup always runs&quot;);<br>        }<br><br>        try {<br>            int x = 10 / 0;<br>        } finally {<br>            System.out.println(&quot;Cleanup code here&quot;);<br>        }<br><br>    }<br>}   </pre><h4><strong>Throws vs Throw:</strong></h4><p><strong>1. throw (We use it to actually throw an exception)</strong></p><ul><li>We use <strong>throw</strong> <em>inside a method</em> to create and throw an exception manually.</li><li>Only <strong>one</strong> exception is thrown at a time.</li><li>It is used for <strong>custom / manual exceptions</strong>.</li></ul><pre>throw new IOException(&quot;File missing&quot;);</pre><p>This immediately stops method execution and jumps to the nearest catch.</p><p><strong>2. </strong><strong>throws (We use it to <em>declare</em> that a method may throw an exception)</strong></p><ul><li>We write <strong>throws</strong> in the <em>method signature</em>.</li><li>It tells the <strong>caller</strong>: “This method may throw this exception. We must handle it.”</li><li>Used mostly for <strong>checked exceptions</strong>.</li></ul><pre>// Using Throws and Throw<br>class Throws_Uses {<br>    // IOException<br>    static void triggerIOException() throws IOException {<br>        throw new IOException();<br>    }<br><br>    // ClassNotFoundException<br>    static void triggerClassNotFoundException() throws ClassNotFoundException {<br>        Class.forName(&quot;com.example.DoesNotExist&quot;);<br>    }<br><br>}<br><br>public class Throw_key {<br>    public static void main(String[] args) {<br><br>        // 1. IOException<br>        try {<br>            Throws_Uses.triggerIOException();<br>        } catch (IOException ex) {<br>            System.out.println(ex.getMessage());<br>        }<br><br>        // 2. ClassNotFoundException<br>        try {<br>            Throws_Uses.triggerClassNotFoundException();<br>        } catch (ClassNotFoundException ex) {<br>            System.out.println(ex.getMessage());<br>        }<br>    }<br>}</pre><h4>Custom Exception:</h4><p>Java provides us with the facility to create our own exception by exteding the exception or Runtime exception class.</p><p><strong>a) Extend Exception: (For Checked) (Must be handled)</strong></p><pre>class InvalidAge extends Exception {<br>    public InvalidAge(String message) {<br>        super(message);<br>    }<br>}<br><br>class LessAge extends Exception {<br>    public LessAge(String message) {<br>        super(message);<br>    }<br>}<br>// We must use throws in method or catch block in checked exception<br>public class Custom_Checked_Exception {<br>    public static void main(String[] args) {<br>        int age = 22;<br>        try {<br>            if (age&lt;18) {<br>                throw new InvalidAge(&quot;Age less&quot;);<br>            } else  {<br>                throw new LessAge(&quot;Age greater&quot;);<br>            }<br>        } catch (InvalidAge | LessAge e) {<br>            System.out.println(e.getMessage());<br>        }<br>    }<br>}</pre><p><strong>b) Extend Runtime Exception: (For Unchecked)</strong></p><pre>class DivideByZero extends RuntimeException {<br>    public DivideByZero(String message) {<br>        super(message);<br>    }<br>}<br>// No need to use throws or catch block just thorw erorr manully<br>public class Custom_Unchcked_Exception {<br>    public static  int divide(int a,int b) {<br>        if (b==0) {<br>            throw new DivideByZero(&quot;divide by zero&quot;);<br>        }<br>        return a/b;<br>    }<br><br>    public static void main(String[] args)  {<br>        try {<br>           divide(5,0);<br>        } catch (DivideByZero e) {<br>            System.out.println(e.getMessage());<br>        }<br><br>    }<br>}</pre><h4>Try-with-Resources in Java</h4><p><strong>try-with-resources</strong> is a special try block that <strong>automatically closes resources</strong> (files, streams, DB connections) after use — even if an exception occurs.</p><p>We don’t need a finally block to close them manually.</p><pre>public class TrywithResource {<br>    public static void main(String[] args) {<br>        String data = &quot;Hello, try-with-resources with FileWriter!&quot;;<br><br>        try (FileWriter fw = new FileWriter(&quot;D://test.txt&quot;)) {<br>            fw.write(data);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }}<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=565a9cab06b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive: OOPS in JAVA]]></title>
            <link>https://medium.com/@himanshupapola/deep-dive-oops-in-java-80e84a1db308?source=rss-3f8413f87d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/80e84a1db308</guid>
            <dc:creator><![CDATA[Himanshu Papola]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 01:38:49 GMT</pubDate>
            <atom:updated>2026-03-30T07:05:00.274Z</atom:updated>
            <content:encoded><![CDATA[<p>Java’s object-oriented programming (OOP) model is the foundation of writing robust, maintainable applications.</p><p>Java is built around objects — everything from small utilities to large enterprise systems uses classes, objects and the OOP principles.</p><p>OOP helps structure code for reusability, extensibility and easier maintenance.</p><p>Mastering OOPS is not just about knowing four OOPS properties. It about knowing below things in detail:</p><pre>A01_Classes (Types)<br>  - Packages ✔️<br>  - Top-level classes ✔️<br>  - Inner classes ✔️<br>  - Abstract classes and Interface ✔️ (In Abstraction)<br>  - Final classes ✔️<br>  - Enums (Covered in Data type: special type of class) ✔️<br>  - Record classes ✔️<br>  - Sealed classes1. Encapsulation (Data Hiding)<br><br>A02_Abstraction <br>  - Abstract classes ✔️<br>  - Interfaces ✔️<br><br>A03_Inheritance<br>  - Single ✔️<br>  - Multilevel ✔️<br>  - Hierarchial ✔️<br>  - Multiple ✔️<br>  - Hybrid ✔️<br><br>A04_Encapsulation<br>  - Encapsulation ✔️<br><br>A05_Polymorphism<br>  - Compile-time polymorphism (Method Overloading) ✔️<br>  - Runtime polymorphism (Method Overriding) ✔️<br><br>A06_Methods<br>  - Method signatures &amp; overloading ✔️<br>  - Varargs ✔️<br>  - Lambdas &amp; method references ✔️<br>  - Exception handling in methods ✔️<br><br>A07_Constructors<br>  - Constructor overloading &amp; chaining ✔️<br>  - Static factory methods ✔️<br>  - Builder pattern ✔️<br><br>A08_Reflection<br>  - Class inspection<br>  - Runtime instantiation &amp; invocation<br>  - Object mapping<br><br>Modifiers &amp; ModifiersHelper<br>  - Access modifiers (public / protected / package-private / private)<br>  - static, final, abstract, transient, volatile, synchronized<br></pre><h3>A01_Classes (Types)</h3><p>A <strong>class in Java</strong> is a blueprint/template that defines the <strong>properties (fields)</strong> and <strong>behaviors (methods)</strong> of objects.</p><blockquote><strong><em>A. Packages:</em></strong></blockquote><p>A package is a namespace that groups related classes and interfaces. It helps organize code, avoid name collisions, control access, and map to directory structure.<br>Declared at the top of a .java file with the package keyword.</p><p><strong>Base package (root package):</strong></p><ul><li>Here base package is one which have some method or properties to import.</li></ul><pre>package A02_OOPS_in_JAVA.A01_Classes.packages.base;<br><br>public class BaseUtility {<br><br>    public static void showMessage() {<br>        System.out.println(&quot;This is the Base Utility class inside the base package.&quot;);<br>    }<br><br>    public void printInstanceMessage() {<br>        System.out.println(&quot;Instance method inside BaseUtility.&quot;);<br>    }<br>}</pre><p><strong>Importing packages / classes:</strong></p><ul><li>Any class in a different package must be imported.</li><li>This class:</li></ul><pre>package A02_OOPS_in_JAVA.A01_Classes.packages.app;<br><br>// Normal import → for creating objects<br>import A02_OOPS_in_JAVA.A01_Classes.packages.base.BaseUtility;<br><br>// Static import → for calling static methods directly<br>import static A02_OOPS_in_JAVA.A01_Classes.packages.base.BaseUtility.showMessage;<br><br>public class MainApp {<br>    public static void main(String[] args) {<br><br>        // 1️⃣ Using static import (no class name needed)<br>        showMessage();<br><br>        // 2️⃣ Using normal import (create object)<br>        BaseUtility util = new BaseUtility();<br>        util.printInstanceMessage();<br>    }<br>}</pre><p>A <strong>normal import</strong> lets you import a <em>class </em>we much create object.</p><p>A <strong>static import</strong> lets you import a <em>static member</em> (method/variable) of a class directly.</p><blockquote><strong><em>B. Top Level Class:</em></strong></blockquote><p>A <strong>top-level class</strong> is a class that is <strong>not inside another class</strong>.<br>It is declared directly inside a <strong>.java file</strong>.</p><p>Java allows <strong>2 types of top-level classes</strong>:</p><ol><li><strong>Public Top-Level Class</strong></li></ol><ul><li>Must match the <strong>file name </strong>and can be accessed <strong>from anywhere</strong> (any package).</li><li>Only <strong>one public top-level class</strong> is allowed per file.</li></ul><p>In your code:</p><pre>// This is a public top-level class <br>package A02_OOPS_in_JAVA.A01_Classes.Types.A01_Top_Level;<br><br>public class A1_Top_Level {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Inside A1_Top_Level (public class)&quot;);<br><br>        PackagePrivateClass obj = new PackagePrivateClass();<br>        obj.displayMessage();<br>    }<br>}</pre><p>2. <strong>Default (package-private) Top-Level Class</strong></p><ul><li>Declared <strong>without</strong> any access modifier.</li><li>Accessible <strong>ONLY within the same package</strong>.</li><li>Unlimited package-private top-level classes can exist in a file.</li></ul><p>In your code:</p><pre>// This is a package-private top-level class<br>package A02_OOPS_in_JAVA.A01_Classes.Types.A01_Top_Level;<br><br>class PackagePrivateClass {<br>    void displayMessage() {<br>        System.out.println(&quot;Hello from PackagePrivateClass (package-private)&quot;);<br>    }<br>}</pre><p>This class <strong>cannot be accessed outside the package.</strong></p><blockquote><strong><em>B. Inner Class:</em></strong></blockquote><p>An <strong>inner class</strong> is a class defined <strong>inside another class </strong>usually Top Level class but not necessarily. It’s used to logically group code and access the outer class’s members more easily.</p><ol><li><strong>Static Inner Class</strong></li></ol><p>A <strong>static inner class</strong> is a class declared inside another class with the static keyword, and <strong>it does not need an object of the outer class</strong> to be created.</p><p>It can directly access <strong>only static members</strong> of the outer class.</p><pre>Outer outer = new Outer();<br>Outer.Inner inner = new Outer().Inner;</pre><pre>public class A01_Static_Nested_Class {<br><br>    // Static variable of the outer class<br>    static int x = 10;<br><br>    // Static nested class<br>    static class innerClass {<br><br>        // Non-static method of static nested class<br>        void display(int m) {<br>           System.out.println(x + m);<br>        }<br><br>        // Static method of static nested class<br>        static void show() {<br>            System.out.println(&quot;This is a static method inside static class&quot;);<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        // Calling static method of static nested class directly using class names<br>        A01_Static_Nested_Class.innerClass.show();<br><br>        innerClass innerClass1 = new innerClass();<br>        innerClass1.display(2);<br><br>        // Creating object of static nested class (no need of outer class object)<br>        A01_Static_Nested_Class.innerClass innerClass = new A01_Static_Nested_Class.innerClass();<br>        innerClass.display(10);<br><br>    }<br>}</pre><p><strong>2. Non Static Inner Class</strong></p><p>Non-static inner classes always need an <strong>object of the outer class</strong> because they are tied to that object.</p><p><strong>a. Member Inner Class</strong></p><p>It’s declared inside the outer class → <strong>directly as a member</strong> (like a variable or method).</p><ul><li>Has access to <strong>all members</strong> of the outer class (including private).</li><li>Needs <strong>outer object</strong> to create inner object.</li></ul><pre>Outer outer = new Outer();<br>Outer.Inner inner = outer.new Inner();</pre><pre>// Member inner class is just a normal class inside top level class, its associated with the object of outer class<br>public class A01_Member_Inner_Class {<br><br>    private int data = 20;<br>    private static int num = 30;<br><br>    class Inner {<br>        void show() {<br>            System.out.println(data + &quot; &quot; + num + &quot; is from member inner class&quot;);<br>        }<br>    }<br><br><br>    public static void main(String[] args) {<br>        // Non-static class outer class kay object kay sath associated hoti hay<br>        A01_Member_Inner_Class outerObj = new  A01_Member_Inner_Class();<br>        A01_Member_Inner_Class.Inner innerObj = outerObj.new Inner();<br>        innerObj.show();<br><br>        A01_Member_Inner_Class.Inner innerObj2 = new A01_Member_Inner_Class().new Inner();<br>        innerObj2.show();<br>    }<br>}</pre><p><strong>b. Local Inner Class</strong></p><p>It’s declared inside a <strong>method</strong>, like a local variable.</p><ul><li>Visible <strong>only inside that method</strong>.</li><li>Can only be <strong>used inside the method</strong> where it’s created.</li><li>Cannot be accessed outside the method.</li></ul><pre>// Local Inner class is defined inside the method of the top level class we can create its object and access methods inside it only.<br><br>public class A02_Local_Inner_Class {<br><br>    int a = 10;<br><br>    public void show() {<br>        class LocalInnerClass {<br>            void display() {<br>                System.out.println(a + &quot; is value from local inner non-static class&quot;);<br>            }<br>        }<br>        LocalInnerClass localInnerClass = new LocalInnerClass();<br>        localInnerClass.display();<br>    }<br><br>    public static void main(String[] args) {<br>        A02_Local_Inner_Class obj = new A02_Local_Inner_Class();<br>        obj.show();<br>    }<br>}</pre><p><strong>3. Anonymous Class</strong></p><p>An anonymous class in Java is a special type of local inner class without a name. It’s a way to declare and instantiate a class at the same time, usually used when you need a one-time implementation of <strong>an interface or an abstract class, or to override methods of a class.</strong></p><p>It’s used when we want to suppose extend a class, or implmenet a Interface or abstract class just to override a method without actually doing it in traditional way.</p><pre>// Let&#39;s say we have a class, interface, abstract class with some method<br>// I want override it&#39;s method without extending or implementing it manually<br><br>class A {<br>    public void show() {<br>        System.out.println(&quot;A&quot;);<br>    }<br>}<br><br>abstract class C {<br>    abstract void special();<br>}<br><br>@FunctionalInterface<br>interface  Greetings {<br>    void sayHello();<br>}<br><br>// Anonymous class extends a class and overrides its methods.<br>public class A01_Anonymous_Class_Extending_Class {<br>    public static void main(String[] args) {<br>        A obj  = new A();<br>        obj.show(); // Prints A (Normal Working)<br><br>        // Using another class without extending it.<br>        A obj2 = new A() {<br>            @Override<br>            public void show() {<br>                System.out.println(&quot;B&quot;);<br>            }<br>        };<br>        obj2.show();<br><br>        // Using abstract class without extending it.<br>        C obj3 = new C() {<br>            @Override<br>            public void special() {<br>                System.out.println(&quot;C&quot;);<br>            }<br>        };<br>        obj3.special();<br><br>        // Using interface without implementing it.<br>        Greetings g = new Greetings() {<br>                        @Override<br>                        public void sayHello() {<br>                            System.out.println(&quot;Hello&quot;);<br>                        }<br>                       };<br>         g.sayHello();<br>    }<br>}</pre><blockquote><strong><em>C. Final Class:</em></strong></blockquote><p>A <strong>final class</strong> is a class that <strong>cannot be inherited (extended)</strong> by any other class.</p><ul><li>You <strong>cannot create a subclass</strong> of a final class.</li><li>All methods inside a final class are <strong>implicitly final</strong> (cannot be overridden), but you don’t need to write final before each method.</li><li>You <strong>can still create objects</strong> of a final class inside or in different package too</li><li>It is used for <strong>security</strong>, <strong>immutability</strong>, or to prevent <strong>modification</strong> of important logic.</li></ul><pre>// Here no class can modify Vehicle start behaviour but they can call it.<br>final class Vehicle {<br>    void start() {<br>        System.out.println(&quot;Vehicle started&quot;);<br>    }<br>}<br><br>public class Final_Class {<br>    public static void main(String[] args) {<br>        Vehicle vehicle = new Vehicle();<br>        vehicle.start();<br>    }<br>}</pre><blockquote><strong><em>D. Record Class:</em></strong></blockquote><p>A record class is meant for <strong>data carrying classes</strong> , classes whose main job is to <strong>store data</strong> and <strong>not contain complex behavior</strong>.</p><p><strong>Record Automatically creates:</strong></p><ul><li>private final fields</li><li>A constructor</li><li>Getters (as methods with field names)</li><li>toString(), equals(), hashCode()</li><li>Is <strong>immutable by default</strong></li><li>Is best for <strong>DTOs , configuration models, API responses, value objects</strong>.</li></ul><pre>record Person(String name, int age) {<br> <br>}<br><br>public class Record_Class {<br>    public static void main(String[] args) {<br>     Person p1 =  new Person(&quot;John&quot;, 25);<br>     System.out.println(p1.toString()+ &quot; &quot; + p1.age();<br>    }<br>}</pre><p>Lombok @Value can achieve almost the same functionality as a record, but not 100%.</p><blockquote><strong><em>E. Sealed Class:</em></strong></blockquote><p><strong>Sealed classes</strong> were introduced in <strong>Java 17</strong> to give developers <em>explicit control</em> over which classes are allowed to extend a class or implement an interface.</p><p>They are used for strong control over inheritance, enforcing domain models, better safety for polymorphism, preventing unexpected subclassing.</p><p>Simply, a <strong>sealed class</strong> is a class that <strong>restricts</strong> which other classes can extend it.</p><p>We define this using:</p><pre>sealed class Parent permits Child1, Child2 {<br>    void show() {<br>        System.out.println(&quot;This is Parent class&quot;);<br>    }<br>}</pre><p>This means:</p><p>Only Child1 and Child2 can extend Parent<br>No other class in the entire project can extend it<br>You cannot add more children without modifying the permits list but there is a catch.</p><p><strong>Every permitted subclass must specify its own modifier</strong></p><p>Any class listed in permits must be exactly one of the following:</p><p><strong>A. final</strong></p><pre>// Final subclass of Parent can&#39;t be extended further<br>final class Child1 extends Parent {<br>    void display() {<br>        System.out.println(&quot;This is Child1 - final class&quot;);<br>    }<br>}</pre><p><strong>B. sealed</strong></p><pre>// Sealed subclass of Parent and permits Child3<br>sealed class Child2 extends Parent permits Child3 {<br>    void display() {<br>        System.out.println(&quot;This is Child2 - sealed class&quot;);<br>    }<br>}</pre><p><strong>C. non-sealed</strong></p><pre>// Non-sealed subclass of Child2 can be further subclassed<br>non-sealed class Child3 extends Child2 {<br>    void display() {<br>        System.out.println(&quot;This is Child3 - non-sealed class&quot;);<br>    }<br>}</pre><p><strong>Using Sealed class:</strong></p><pre>public class Sealed_Class {<br>    public static void main(String[] args) {<br>        Parent obj1 = new Child1();<br>        obj1.show();<br>        ((Child1) obj1).display();<br><br>        // Parent reference to Child2<br>        Parent obj2 = new Child2();<br>        obj2.show();<br>        ((Child2) obj2).display();<br><br>        // Parent reference to Child3<br>        Parent obj3 = new Child3();<br>        obj3.show();<br>        ((Child3) obj3).display();<br>    }<br>}</pre><h3>Object-Oriented Programming (OOP) in Java:</h3><p>Java is a <strong>pure object-oriented language</strong> (except for primitive types).<br>OOP means designing your application using <strong>objects</strong> (real-world entities) and <strong>classes</strong> (their blueprints).</p><p>Java follows <strong>four core OOP principles</strong>:</p><h4><strong>1. Encapsulation (Data Hiding)</strong></h4><p>The process of wrapping data(variable) and methods that operate on data into a single unit i.e a class.</p><p>It’s used to hide the internal implmentation details of class. This technique ensures data protection, security and flexiblity.</p><p>It involves:</p><p>a. Hiding data fields (making it private)<br>b. Controlling access to that data (by exposiing public method like getter and setter)</p><pre><br>// Encapsulated class <br>class Person {<br><br>    private String name;  // data hiding<br><br>    public void setName(String name) {<br>        this.name = name;  // controlled write access<br>    }<br><br>    public String getName() {<br>        return name;       // controlled read access<br>    }<br>}<br><br>public class EncapsulationDemo {<br>    public static void main(String[] args) {<br>        Person person = new Person();<br>        person.setName(&quot;Himanshu&quot;);<br>        System.out.println(person.getName());<br>    }<br>}</pre><h4>2. Abstraction</h4><p>It is the process of hiding the implementaton details and only showing essential details for features to users.</p><blockquote><strong><em>In Java Abstraction can be achieved in two ways:</em></strong></blockquote><p>a. Abstract Class (Partiall Abstraction)<br>b. Interface (100% Abstraction)</p><p><strong>A. Abstract Class</strong></p><p>In Java abstract class is declared with the abstract keyword. It may have both abstract and non-abstract methods. Abstract is applicable for class and methods not variables.</p><p>If a class contain at least one abstract method then compulsory to delcare a class as abtract.</p><p>If child is not able to provide implementation to all abstract method of Parent class then we should mark that child class abtract too so next level child should provide implementation.</p><p><strong>Use abtract class when:</strong><br><strong>1. </strong>You want a common base class for all subclasses.<br><strong>2. </strong>You want certain method to be implmeneted in subclass.</p><pre>// Abstract class with abtract method and a implmented method.<br>abstract class Appliance {<br>    abstract void start();<br>    abstract void stop();<br><br>    void plugIn() {<br>        System.out.println(&quot;Plugged in&quot;);<br>    }<br>}<br><br>class Fan extends Appliance {<br>    @Override<br>    void start() {<br>        System.out.println(&quot;Fan started&quot;);<br>    }<br><br>    @Override<br>    void stop() {<br>        System.out.println(&quot;Fan stopped&quot;);<br>    }<br><br>    void boost() {<br>        System.out.println(&quot;Fan boosted&quot;);<br>    }<br>}<br><br>public class AbstractClass {<br>    public static void main(String[] args) {<br>        Appliance obj = new Fan();<br>        obj.plugIn();<br>        obj.start();<br>        obj.stop();<br><br>    }<br>}</pre><p><strong>B. Interface</strong></p><p>An Interface in Java is like a contract. It defines waht a class must do, but not how it does it. In interface method are abstract by default.</p><p>A class can implement multiple interfaces (It supports multiple Inheritance).</p><p>All variable inside interface are public static final by deafult.</p><pre>interface A {<br>    int age = 44;<br>    String area = &quot;Mumbai&quot;;<br><br>    void show();<br>    void config();<br>}<br><br>interface B extends A {<br>    void run();<br>}<br><br>class C implements B {<br>    @Override<br>    public void show() {<br>        System.out.println(&quot;I am B2&quot;);<br>    }<br><br>    @Override<br>    public void config() {<br>        System.out.println(&quot;I am B2&quot;);<br>    }<br><br>    @Override<br>    public void run() {<br>        System.out.println(&quot;I am B - run()&quot;);<br>    }<br><br>    // Extra method only in C<br>    public void fanSpecificMethod() {<br>        System.out.println(&quot;Fan specific method&quot;);<br>    }<br>}<br><br>public class Interfaces {<br>    public static void main(String[] args) {<br>        B b = new C();<br>        b.show();<br>        b.config();<br>        b.run();<br><br>        System.out.println(b.age);<br><br>        // calling C method while maintain abstraction<br>        ((C)b).fanSpecificMethod();<br><br>    }<br>}</pre><p>In Java, you will often see code like this:</p><pre>B b = new C();</pre><p>At first glance, this feels strange. Why are we creating an object of class C but storing it inside a reference of interface type B?</p><p>To understand this, we need to break the statement into its two parts:<br> <strong>object creation (right side)</strong> and <strong>reference type (left side).</strong></p><p><strong>1. Object Creation Happens on the Right Side</strong></p><p>The expression:</p><pre>new C();</pre><p><strong>always creates a real object of class </strong><strong>C in memory.</strong></p><p>Java cannot create an object of an interface because Interfaces have <strong>no constructors, i</strong>nterfaces only define <strong>method signatures</strong>, not actual behavior/ So the only possible object created here is:</p><pre>Object type: C</pre><p><strong>2. The Reference Type is on the Left Side</strong></p><p>The left side:</p><pre>B b</pre><p>declares a <strong>reference variable</strong> of type B.</p><p>A reference variable decides what methods are visible, what behavior the compiler allows you to call, how you interact with the object. It does <strong>not</strong> decide what object is created — only what the variable can “see.”</p><p>When you write:</p><pre>B b = new C();</pre><p>you are telling Java:</p><blockquote><strong><em>“Create a C object, but treat it as something that follows the rules of interface B.”</em></strong></blockquote><p>This means:</p><ul><li>You <strong>can only call methods that exist in interface B</strong></li><li>Even though the actual object is C, the reference hides C-specific features</li></ul><p><strong>Why Would We Do This? (The Real Meaning)</strong></p><p><strong>✔ Abstraction<br></strong>You hide unnecessary details.<br> The user only sees the methods defined in interface B.</p><p><strong>✔ Loose Coupling<br></strong>Your code depends on the interface, not on the concrete class.</p><p><strong>Example: In Real SpringBoot App</strong></p><pre>// ============================================================================<br>// SERVICE LAYER INTERFACE (CONTRACT)<br>// ============================================================================<br>public interface PostService {<br>    Post addPost(Post post);<br>    Post getPost(int id);<br>    List&lt;Post&gt; getAllPosts();<br>    void deletePost(int id);<br>}<br><br><br><br>// ============================================================================<br>// IMPLEMENTATION 1 – IN-MEMORY (Dummy / DEV)<br>// ============================================================================<br>@Service<br>@Qualifier(&quot;inMemoryService&quot;)<br>public class PostServiceImplForInMemoryDB implements PostService {<br><br>    @Override<br>    public Post addPost(Post post) {<br>        return null;<br>    }<br><br>    @Override<br>    public Post getPost(int id) {<br>        return null;<br>    }<br><br>    @Override<br>    public List&lt;Post&gt; getAllPosts() {<br>        return null;<br>    }<br><br>    @Override<br>    public void deletePost(int id) {<br>    }<br>}<br><br><br><br>// ============================================================================<br>// IMPLEMENTATION 2 – PRODUCTION (Real DB: JPA, Mongo, etc.)<br>// ============================================================================<br>@Service<br>@Qualifier(&quot;prodService&quot;)<br>@Primary   // This implementation will be injected by default<br>public class PostServiceImplForProDB implements PostService {<br><br>    @Override<br>    public Post addPost(Post post) {<br>        return null;<br>    }<br><br>    @Override<br>    public Post getPost(int id) {<br>        return null;<br>    }<br><br>    @Override<br>    public List&lt;Post&gt; getAllPosts() {<br>        return null;<br>    }<br><br>    @Override<br>    public void deletePost(int id) {<br>    }<br>}<br><br><br><br>// ============================================================================<br>// CONTROLLER — DOES NOT CHANGE (Loose Coupling)<br>// ============================================================================<br>@RestController<br>@RequestMapping(&quot;/posts&quot;)<br>@RequiredArgsConstructor<br>public class PostController {<br><br>    // OPTION 1 — Use whatever implementation is marked @Primary<br>    private final PostService postService;<br><br>    // OPTION 2 — Manual: explicitly choose the implementation<br>    // @Qualifier(&quot;inMemoryService&quot;)<br>    // private final PostService postService;<br><br>    // @Qualifier(&quot;prodService&quot;)<br>    // private final PostService postService;<br><br><br>    @PostMapping(&quot;/add&quot;)<br>    public Post add(@RequestBody Post post) {<br>        return postService.addPost(post);<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public Post getOne(@PathVariable int id) {<br>        return postService.getPost(id);<br>    }<br><br>    @GetMapping(&quot;/all&quot;)<br>    public List&lt;Post&gt; getAll() {<br>        return postService.getAllPosts();<br>    }<br><br>    @DeleteMapping(&quot;/{id}&quot;)<br>    public String delete(@PathVariable int id) {<br>        postService.deletePost(id);<br>        return &quot;Deleted Post &quot; + id;<br>    }<br>}</pre><p>We achieved loose coupling between the Controller and Service by introducing a PostService interface and offering multiple implementations (in-memory and production DB).</p><p>Since the controller depends only on the interface not the concrete classes we can freely swap or add new service logic using @Primary or @Qualifier without touching the controller. This keeps the system flexible, extensible, and future-proof.</p><h4>3. Inheritance</h4><p>Inheritance in Java allows one class to inherit the features of another class.</p><p>In Java Inheritance means creating new calsses based on existing one. A class that can inherit from another calss and can resuse method and filed of parent class.</p><p>The class that inherit is called the <strong>SubClass/Child</strong></p><p>The class being inherited is caleed <strong>SuperClass/Parent</strong></p><blockquote><strong><em>Type of Inheritance:</em></strong></blockquote><ol><li><strong>Single Inheritance:<br></strong>In Single Inheritance, one child class inherits from one parent class only. No multiple parents, no complex hierarchy.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*wVXpQjy7vB4es1MH5uCtJA.png" /></figure><pre>class A{<br>    public void print_geek() {<br>        System.out.println(&quot;One Geek&quot;);<br>    }<br>}<br><br>class B extends A{<br>    public void print_for() {<br>        System.out.println(&quot;Two Geek&quot;);<br>    }<br><br>    @Override<br>    public void print_geek() {<br>        super.print_geek();<br>        System.out.println(&quot;Two Geek&quot;);<br>    }<br>}<br><br>public class Singles {<br>    public static void main(String[] args) {<br>      B b= new B();<br>      b.print_geek();<br>      b.print_for();<br>    }<br>}</pre><p><strong>2. Multilevel Inheritance:<br></strong>In it, a derived class will be inherting a base class, and the same dervied class acts as a base class for other classe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*nGwOMoFTgn_TXWTY8zI3Lg.png" /></figure><pre>package A02_OOPS_in_JAVA.A03_Inheritance.A02_Multilevel;<br><br>class A {<br>    void show() {<br>        System.out.println(&quot;One&#39;s show&quot;);<br>    }<br>}<br><br>class B extends A {<br>    @Override<br>    void show() {<br>        super.show();<br>        System.out.println(&quot;Two&#39;s show&quot;);<br>    }<br><br>    void display() {<br>        System.out.println(&quot;Two&#39;s display&quot;);<br>    }<br>}<br><br>class C extends B {<br>    @Override<br>    void show() {<br>        this.display();   // Calls Three&#39;s display()<br>        super.show();     // Calls Two&#39;s show()<br>        System.out.println(&quot;Three&#39;s show&quot;);<br>    }<br><br>    @Override<br>    void display() {<br>        System.out.println(&quot;Three&#39;s display&quot;);<br>    }<br>}<br><br>public class MultiLevels {<br>    public static void main(String[] args) {<br>        C c = new C();<br>        c.show();<br>    }<br>}</pre><p><strong>3. Hierarchial Inheritance:<br></strong>In it, there a one class that serves as Superclass for more then one Subclass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*i84l32tTHmdv6Q_AQFgkPA.png" /></figure><pre>class A {<br>    public void print_A() {<br>        System.out.println(&quot;I am Super A&quot;);<br>    }<br>}<br><br>class B extends A {<br>    public void print_B() {<br>        System.out.println(&quot;I am Sub B&quot;);<br>    }<br><br>}<br><br>class C extends A {<br>    public void print_C() {<br>        System.out.println(&quot;I am Sub C&quot;);<br>    }<br><br>}<br>public class Hierarchical {<br>    public static void main(String[] args) {<br>        B b = new B();<br>        C c = new C();<br><br>        b.print_B();<br>        b.print_A();<br><br>        c.print_C();<br>        c.print_A();<br>    }<br>}</pre><p><strong>4. Multiple Inheritance:</strong></p><p>In Multiple Inheritance, one class can have more then one Superclass and inherit feature from all parent class.</p><p>Java does not support multiple inheritance, we can achieve it through Interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*EBRrnm4Kcfr7_3kyq1TjkA.png" /></figure><pre>// Parent 1<br>interface Developers{<br>    void develop();<br>}<br><br>// Parent 2<br>interface Testers {<br>    void tests();<br>}<br><br>// Child Inherit two classes (not extend)<br>class Devops_Engineer implements Testers, Developers {<br><br><br>    @Override<br>    public void develop() {<br>        System.out.println(&quot;Develop&quot;);<br>    }<br><br>    @Override<br>    public void tests() {<br>        System.out.println(&quot;testCode&quot;);<br>    }<br>}<br><br>public class Multiple_Inheritance  {<br>    public static void main(String[] args) {<br>        // Using class<br>        Devops_Engineer engineer = new Devops_Engineer();<br>        engineer.develop();<br>        engineer.tests();<br><br>        // Using Anonymous Class<br>        Developers obj2 = new Developers() {<br>            @Override<br>            public void develop() {<br>                System.out.println(&quot;Develop&quot;);<br>            }<br>        };<br>        obj2.develop();<br><br>        // Using Lambda Function<br>        Testers obj3 = () -&gt; {<br>            System.out.println(&quot;test&quot;);<br>        };<br>        obj3.tests();<br>    }<br>}</pre><p><strong>❌ Why Java Does NOT Allow Multiple Class Inheritance?</strong><br>Because of the <strong>Diamond Problem</strong> — it creates <em>ambiguity</em>.</p><pre>      A<br>     / \<br>    B   C<br>     \ /<br>      D</pre><ul><li>A has a method show()</li><li>B overrides show()</li><li>C also overrides show()</li><li>D extends both B and C</li></ul><p><strong>💥 Problem</strong></p><p>When we call:</p><pre>D obj = new D();<br>obj.show(); // Which version should run? B&#39;s show() or C&#39;s show()?</pre><p><strong>5. Hybrid Inheritance:</strong></p><p>It’s just mix of two or more type of inheritiance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*5ccx38z76NpuhSfcdDju3w.png" /></figure><pre>interface Super1 {<br>    void print_super1();<br>}<br><br>interface Super2 {<br>    void print_super2();<br>}<br><br>class AB implements Super1, Super2 {<br>    @Override<br>    public void print_super1() {<br>        System.out.println(&quot;super1&quot;);<br>    }<br><br>    @Override<br>    public void print_super2() {<br>        System.out.println(&quot;super2&quot;);<br>    }<br>}<br><br>class D extends AB {<br>    public void displayD() {<br>        System.out.println(&quot;I am D&quot;);<br>    }<br>}<br><br>class E extends AB {<br>    public void displayE() {<br>        System.out.println(&quot;I am E&quot;);<br>    }<br>}<br><br>public class Hybrids {<br>    public static void main(String[] args) {<br>        D d = new D();<br>        d.displayD();<br>        d.print_super1();<br>        d.print_super1();<br><br>        E e = new E();<br>        e.displayE();<br>        e.print_super2();<br>        e.print_super2();<br>    }<br>}</pre><pre>       ** Hybrid Inheritance **<br>          +---------+        +---------+<br>          | Super1  |        | Super2  |<br>          +----+----+        +----+----+<br>                   \         /<br>                    \       /<br>                     +-----+<br>                     | AB  | (Multiple)<br>                     +--+--+<br>                       /  \<br>                      /    \<br>               +----+        +----+<br>               |  D |        |  E | (Hierarchical)<br>               +----+        +----+</pre><h4>4. Polymorphism</h4><p>Polymorphism means <strong>“many forms”</strong>. In Java, <strong>one action behaves differently based on the object that performs it.</strong></p><blockquote><strong><em>1. Compile-Time Polymorphism (Method Overloading)</em></strong></blockquote><p>JVM decides <strong>which method to call at compile time</strong>.</p><p>Same method name, <strong>different parameters </strong>(different number, different type, or different order).</p><pre>public class Method_Overloading {<br>    void display(int a) {<br>        System.out.println(&quot;Displaying int: &quot; + a);<br>    }<br><br>    void display(int a, int b) {<br>        System.out.println(&quot;Displaying two ints: &quot; + a + &quot;, &quot; + b);<br>    }<br><br>    void display(String s) {<br>        System.out.println(&quot;Displaying String: &quot; + s);<br>    }<br><br>    public static void main(String[] args) {<br>        Method_Overloading obj = new Method_Overloading();<br><br>        obj.display(1);<br>        obj.display(2,3);<br>        obj.display(&quot;Hello&quot;);<br>    }<br>}</pre><pre>obj.display(1);         // calls display(int)<br>obj.display(2, 3);      // calls display(int, int)<br>obj.display(&quot;Hello&quot;);   // calls display(String)</pre><p>We get <strong>different behavior</strong>, but the compiler knows exactly which method to run.</p><h4>2. Runtime Polymorphism (Method Overriding)</h4><p>JVM decides <strong>which method to call at runtime</strong>.</p><p>Parent reference → Child object<br>Method overridden → always run the <strong>child’s method</strong>, not parent’s.</p><pre>package A02_OOPS_in_JAVA.A05_Polymorphism;<br><br>class Animal {<br>    void sound() {<br>        System.out.println(&quot;Animal sound&quot;);<br>    }<br>}<br><br>class Dog extends Animal {<br>    @Override<br>    void sound() {<br>        System.out.println(&quot;Dog sound&quot;);<br>    }<br>}<br><br>public class Method_Overriding {<br>    public static void main(String[] args) {<br><br>        // Reference variable is of type Animal (parent class)<br>        // Object is of type Dog (subclass)<br>        Animal animal = new Dog();<br>        animal.sound();<br><br>        Animal animal2 = new Animal();<br>        animal2.sound();<br>    }<br>}</pre><pre>Animal animal = new Dog();<br>animal.sound();   // Dog sound → runtime polymorphism</pre><p>Even though reference type is <strong>Animal</strong>, object type is <strong>Dog</strong>, so Dog’s version runs.</p><h3>Constructors</h3><blockquote><strong><em>1. Constructor Overloading</em></strong></blockquote><p>We create <strong>multiple constructors with different parameter lists</strong> so that an object can be created in different ways.</p><pre>class User {<br>    private String name;<br>    private int age;<br><br>    // 1. No-arg constructor<br>    User() {<br>        this.name = &quot;Unknown&quot;;<br>        this.age = 0;<br>    }<br><br>    // 2. Parameterized constructor<br>    User(String name) {<br>        this.name = name;<br>        this.age = 0;<br>    }<br><br>    // 3. Parameterized constructor<br>    User(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>}</pre><blockquote><strong><em>2. Constructor Chaining:</em></strong></blockquote><p><strong>Constructor Chaining</strong> means one constructor calls another constructor. <strong>Within same class → </strong><strong>this() and cross parent-child → </strong><strong>super()</strong><br>It happens in <strong>two places</strong>:</p><p><strong>1️⃣ Within the Same Class → using this()</strong></p><pre>class Person {<br><br>    Person() {<br>        this(&quot;Himanshu&quot;);<br>        System.out.println(&quot;Person&quot;);<br>    }<br><br>    Person(String name) {<br>        System.out.println(name);<br>    }<br>}</pre><p><strong>2️⃣ Across Parent → Child Classes → using </strong><strong>super()</strong></p><pre>//  Across parent and child classes (using super())<br>class Animal {<br>    Animal() {<br>        System.out.println(&quot;Animal&quot;);<br>    }<br>}<br><br>class Dog extends Animal {<br>    Dog() {<br>        super();<br>        System.out.println(&quot;Dog&quot;);<br>    }<br>}</pre><blockquote><strong><em>3. Builder Pattern:</em></strong></blockquote><p>The <strong>Builder Pattern</strong> is a creational design pattern that helps us create complex objects step-by-step without writing long or confusing constructors.</p><p>Use it when object has: many fields, optional fields, different combinations of fields. Simplify this by using @Builder lombook.</p><pre>// Using constructors becomes messy:<br>new User(&quot;Himanshu&quot;, 25, null, &quot;Delhi&quot;, null);<br><br>// Builder Patter<br>User u = User.builder()<br>        .name(&quot;Himanshu&quot;)<br>        .age(25)<br>        .email(&quot;him@example.com&quot;)<br>        .build();</pre><h3><strong><em>Reflection</em></strong></h3><p><strong>Reflection</strong> is a Java feature that allows us to <strong>inspect and modify classes, methods, fields, and annotations at runtime</strong>, even if we don’t know them at compile time.</p><p>Spring provides utility methods in:</p><pre>import org.springframework.util.ReflectionUtils;</pre><p>This is a helper class built on top of standard Java reflection which makes using Reflection muh simpler.</p><p>Let’s say we have a class like this:</p><pre>class Person {<br>    // With Private fields<br>    private String name;<br>    private int age;<br><br>    // With no args constructor<br>    public Person() {}<br><br>    // With all args constructor<br>    public Person(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br><br>    // With a Public method<br>    public void show() {<br>        System.out.println(&quot;Name: &quot; + name + &quot;, Age: &quot; + age);<br>    }<br><br>    // With a Private method.<br>    private void secretMethod() {<br>        System.out.println(&quot;This is a private method&quot;);<br>    }<br>}</pre><p>Reflection allows us to read a class’s structure and then use that information to access or modify the values inside an object, even if the fields or methods are private. Reflection <strong>does not modify the class itself</strong> <br>it only modifies the <strong>object built from that class</strong>.</p><blockquote><em>In reflection, we use the Class object to get fields, constructors, and methods because these belong to the class structure. But whenever we want to read or modify actual values, we must operate on an object instance because values live only in objects.</em></blockquote><pre>import org.springframework.util.ReflectionUtils;<br>import java.lang.reflect.Constructor;<br>import java.lang.reflect.Field;<br>import java.lang.reflect.Method;<br><br>public class ReflectEx {<br>    public static void main(String[] args) throws ClassNotFoundException {<br>        // Creating a Class Object<br>        Person person = new Person(&quot;Himanshu&quot;, 25);<br><br>        // Getting class bluprint for Using Reflection<br>        Class&lt;?&gt; b = Class.forName(&quot;pkg.B.Person&quot;); // Using full name<br>        Class&lt;?&gt; c = person.getClass(); // Using Object<br>        Class&lt;?&gt; d = Person.class; // Using class literal<br><br>        // Java Inbuilt Reflection<br>        System.out.println(c.getSuperclass().getName()); // Getting Superclass of class which is object<br><br>        // Getting all constructors<br>        Constructor&lt;?&gt;[] constructors = c.getConstructors();<br>        for (Constructor&lt;?&gt; constructor : constructors) {<br>            System.out.println(constructor);<br>        }<br><br>        // Getting all fields name<br>        Field[] fields = c.getDeclaredFields();<br>        for (Field field : fields) {<br>            System.out.println(field.getName());<br>        }<br><br>        // Modify fields<br>        Field field = ReflectionUtils.findField(Person.class, &quot;name&quot;);<br>        if (field == null) return;<br>        field.setAccessible(true);<br>        ReflectionUtils.setField(field, person, &quot;Raju&quot;);<br>        Field field2 = ReflectionUtils.findField(Person.class, &quot;age&quot;);<br>        if (field2 == null) return;<br>        field2.setAccessible(true);<br>        ReflectionUtils.setField(field2, person, 20);<br>        person.show();<br><br>        // Accessing Method<br>        Method secretMethod = ReflectionUtils.findMethod(Person.class, &quot;secretMethod&quot;);<br>        secretMethod.setAccessible(true);<br>        ReflectionUtils.invokeMethod(secretMethod, person);<br>  }<br>}</pre><pre>// Reflection can be used on PATCH Mapping<br>Map&lt;String, Object&gt; updates = Map.of(<br>        &quot;name&quot;, &quot;Saurabh&quot;,<br>        &quot;age&quot;, 35<br>);<br><br>updates.forEach((k, v) -&gt; {<br>    Field f = ReflectionUtils.findField(Person.class, k);<br>    f.setAccessible(true);<br>    ReflectionUtils.setField(f, person, v);<br>});<br>person.show();<br><br>// If incoming PATCH value is usually a String<br>// then reflection cannot convert types automatically<br>// This can cause date issues.  </pre><h3>Modifiers in Java</h3><blockquote><strong><em>Access Modifiers in Java — Class Level Only</em></strong></blockquote><p><strong>A. Top Level Class</strong></p><p>At the <strong>top level</strong> (i.e., when we declare a class directly inside a .java file), <strong>Java allows only two access modifiers:</strong></p><p><strong>1. public</strong></p><ul><li>The class is visible to <strong>all packages</strong>.</li><li>Anyone can create an object of this class from anywhere.</li><li>The .java file name <strong>must match</strong> the public class name.</li><li>Only <strong>one</strong> public class is allowed per .java file.</li></ul><pre>// public access modifier<br>public class AccessModifierClasses { }</pre><p>We can access this class from any package.</p><p><strong>2. default (package-private)</strong></p><p><em>(When we do NOT write any keyword)</em></p><ul><li>The class is visible <strong>only within the same package</strong>.</li><li>No class outside the package can access it.</li><li>File name does <strong>not</strong> have to match this class name.</li></ul><pre>// default access modifier<br>class Dog {<br>    public void bark(){<br>        System.out.println(&quot;Bark!&quot;);<br>    }<br>}<br><br>// public access modifier<br>public class AccessModifierClasses { }<br><br>// Here, We can access Dog only inside its package.</pre><p><strong>B. Inner Class</strong></p><p>Inside inner class, we can use <strong>all 4 modifiers</strong>:</p><pre>public class AccessModifierClasses {    <br>    public class Animal1 {}     // public → accessible everywhere<br>    protected class Animal2 {}  // protected → same pkg + subclasses<br>    class Animal3 {}            // default → same package only<br>    private class Animal4 {}    // private → only inside this outer class<br>}</pre><pre><br>// public access modifier<br>public class AccessModifierClasses {<br><br>    // ===========================================================================================<br>    // ACCESSIBILITY RULES FOR INNER CLASSES (public, protected, default, private)<br><br>    // ----------------------------------------------<br>    // 1. PUBLIC INNER CLASS<br>    // ----------------------------------------------<br>    // ✔ Accessible from:<br>    //    - Same class<br>    //    - Same package<br>    //    - Subclasses (any package)<br>    //    - Any other package<br>    // ✘ Not restricted anywhere.<br>    public class Animal1 {<br>        public String name = &quot;Public Animal 1&quot;;<br>    }<br><br><br>    // ----------------------------------------------<br>    // 2. PROTECTED INNER CLASS<br>    // ----------------------------------------------<br>    // ✔ Accessible from:<br>    //    - Same class<br>    //    - Same package (normal classes)<br>    //    - Subclasses (even in different packages — but only via inheritance)<br>    //<br>    // ✘ Not accessible from a non-subclass in another package.<br>    protected class Animal2 {<br>        public String name = &quot;Protected Animal 2&quot;;<br>    }<br><br><br>    // ----------------------------------------------<br>    // 3. DEFAULT (PACKAGE-PRIVATE) INNER CLASS<br>    // ----------------------------------------------<br>    // ✔ Accessible from:<br>    //    - Same class<br>    //    - Same package<br>    //<br>    // ✘ NOT accessible from:<br>    //    - Subclasses in other packages<br>    //    - Any class in other packages<br>    class Animal3 {<br>        public String name = &quot;Default Animal 3&quot;;<br>    }<br><br><br>    // ----------------------------------------------<br>    // 4. PRIVATE INNER CLASS<br>    // ----------------------------------------------<br>    // ✔ Accessible from:<br>    //    - Only inside this enclosing class (AccessModifierClasses)<br>    //<br>    // ✘ NOT accessible from:<br>    //    - Same package classes<br>    //    - Subclasses<br>    //    - Any other package<br>    private class Animal4 {<br>        private String name = &quot;Private Animal 4&quot;;<br>    }<br><br><br>    public static void main(String[] args) {<br>        Dog dog = new Dog();<br>        dog.bark();<br><br>        AccessModifierClasses outer = new AccessModifierClasses();<br>        AccessModifierClasses.Animal4 a4 = outer.new Animal4();<br>        System.out.println(a4.name);<br>    }<br>}</pre><h3>Relationships in Java</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXRMhdZzvWFSdGNxpVz1RA.png" /></figure><h4>1. IS-A (Inheritance)</h4><ul><li>Uses extends (class to class)</li><li>Uses implements (class to interface)</li><li>Defines a parent–child hierarchy</li><li>Enables polymorphism</li><li>It’s a Strong Relationship.</li></ul><pre>class Vehicle {}<br>class Car extends Vehicle {}   // IS-A</pre><h4>2. HAS-A (Assocation)</h4><p>A <strong>Has-A relationship</strong> means <strong>one class contains another class as a field</strong>.<br>It’s not inheritance. It’s <strong>object ownership</strong>.</p><ul><li>A <strong>Car has an Engine</strong></li><li>A <strong>Student has an Address</strong></li><li>A <strong>Order has a List of Items</strong></li></ul><p>This happens using <strong>fields</strong>, not extends.</p><blockquote><strong><em>✅ Types of Has-A Relationships</em></strong></blockquote><p>Java has <strong>two variations</strong>:</p><p><strong>1. AGGREGATION (Weak HAS-A)<br></strong>A car <strong>has</strong> a MusicPlayer, but it’s removable.<br>You can take it out and use it elsewhere.<br><strong>Meaning:</strong></p><ul><li>Car has it</li><li>But it is NOT owned strongly</li><li>Can exist independently</li><li>Created outside and passed into Car</li></ul><pre>class MusicPlayer {<br>    void play() {<br>        System.out.println(&quot;Playing music...&quot;);<br>    }<br>}<br><br>class Car {<br>    MusicPlayer mp;  // Car has-a MusicPlayer (Aggregation)<br><br>    // Inject (pass) from outside<br>    Car(MusicPlayer mp) {<br>        this.mp = mp;<br>    }<br><br>    void drive() {<br>        System.out.println(&quot;Car is moving...&quot;);<br>        mp.play();<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        MusicPlayer mp = new MusicPlayer(); // created outside → aggregation<br>        Car car = new Car(mp);              // passed into Car<br><br>        car.drive();<br>    }<br>}</pre><p>👉 Car <strong>has</strong> a MusicPlayer, but if Car is destroyed,<br> MusicPlayer can still exist.</p><p>👉 <strong>This is Aggregation.</strong></p><p><strong>2. COMPOSITION (Strong HAS-A)<br></strong>A <strong>Car owns an Engine completely.</strong><br> Engine cannot exist without Car.<br> Engine is created inside Car.</p><p><strong>Meaning:</strong></p><ul><li>Strong ownership</li><li>Lifetime depends on Car</li><li>Created inside the Car</li></ul><pre>class Engine {<br>    void start() {<br>        System.out.println(&quot;Engine started...&quot;);<br>    }<br>}<br><br>class Car {<br>    // Composition: Car *owns* Engine completely<br>    private final Engine engine;<br><br>    Car() {<br>        this.engine = new Engine();  // created inside → strong ownership<br>    }<br><br>    void drive() {<br>        engine.start();<br>        System.out.println(&quot;Car is driving...&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Car car = new Car();  // Engine gets created automatically inside<br>        car.drive();<br>    }<br>}</pre><p>👉 Engine belongs to Car<br>👉 Without car, engine is useless<br>👉 Car controls the engine’s creation + destruction</p><p>👉 <strong>This is Composition.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80e84a1db308" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive: String in Java]]></title>
            <link>https://medium.com/@himanshupapola/deep-dive-string-in-java-c43ed8033c58?source=rss-3f8413f87d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/c43ed8033c58</guid>
            <category><![CDATA[string-in-java]]></category>
            <category><![CDATA[string]]></category>
            <dc:creator><![CDATA[Himanshu Papola]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 13:03:06 GMT</pubDate>
            <atom:updated>2025-11-18T13:09:42.003Z</atom:updated>
            <content:encoded><![CDATA[<p>In almost every Java application — APIs, microservices, backend systems, desktop apps — strings are everywhere:</p><ul><li>URLs, JSON keys, Logs, Database queries, Headers &amp; tokens, User input, Configuration</li></ul><p>Because strings are <em>so</em> frequently used, Java gives them special treatment under the hood. Understanding this deeply will transform the way you think about memory, performance, and immutability in Java.</p><blockquote><strong><em>What Exactly Is a String in Java?</em></strong></blockquote><p>A String in Java is: An object, Immutable, Backed by a char[] (before Java 9) or byte[] + Latin1 flag (after Java 9 Compact Strings) an</p><p>In code:</p><pre>String name = &quot;Himanshu&quot;;</pre><p>We are NOT creating a primitive. We are creating an object which points to an internal character storage, stored in the heap, but optionally reused from the String Pool.</p><blockquote><strong><em>Immutability — Why Java Made the Best Decision Ever</em></strong></blockquote><p><strong>Once created: </strong>You cannot modify a String and any operation returns a NEW String.</p><pre>String s = &quot;Java&quot;;<br>s.concat(&quot; World&quot;);<br><br>System.out.println(s); // &quot;Java&quot;</pre><p>You <em>thought</em> you changed it — but you didn’t.</p><p>Why immutability matters:</p><ul><li><strong>Thread-safety</strong> (no locking required)</li><li><strong>Security</strong> (passwords, URLs, class loading)</li><li><strong>HashCode caching</strong> (fast lookups in HashMap)</li><li><strong>Safe interning in String Pool</strong></li></ul><blockquote><strong><em>String Pool — Java’s Secret Optimization Engine</em></strong></blockquote><p>When you write:</p><pre>String s1 = &quot;Hello&quot;;<br>String s2 = &quot;Hello&quot;;</pre><p>Both point to <strong>one single object</strong> in JVM’s String Pool.</p><p>This saves memory, improves performance and speeds up comparisons.</p><blockquote><strong><em>Literal vs new String()</em></strong></blockquote><p><strong>a. Literal: </strong>Stored in pool (or reused)</p><p>The string pool is a storage area in Java heap memory where all the other objects are created. It reduces memory overhead and increases performance by reducing the number of String objects created in the JVM. Each time a string literal is created, the JVM checks the string pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn’t exist in the pool, a new instance is created and placed in the pool.</p><pre>String s1 = &quot;Hello World&quot;;<br>String s2 = &quot;Hello World&quot;; // same object</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvA0nFrOkQY7q1lbo3Z7tQ.png" /></figure><p>In this example, only one object will be created. The JVM will first create a new object with the value “Hello World”, and then it will find the string with the same value in the pool and return the reference to the same instance instead of creating a new one.</p><p><strong>b. new String(): </strong>Always creates <strong>a new object in heap</strong>, never reused:</p><pre>String s1 = new String(&quot;Hello World!&quot;);<br>String s2 = new String(&quot;Hello Wordl!&quot;); // new object</pre><p>In this example, two objects will be created and two references to those objects will be created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjq7FbPA2dMvtVDvZu0x3A.png" /></figure><blockquote><strong><em>String Interning — Manual Pooling</em></strong></blockquote><pre>String s1 = new String(&quot;Java&quot;);<br>String s2 = s1.intern();<br>String s3 = &quot;Java&quot;;<br><br>System.out.println(s2 == s3); // true</pre><p>.intern() returns the <strong>pooled version</strong>, ensuring fast comparisons.</p><blockquote><strong><em>Important String Methods</em></strong></blockquote><p>In almost 95% of the cases new String object will be created when we apply methods and those 5% of cases are gernally when there is no-op situation.</p><pre>String name = &quot;Himanshu&quot;;<br>String fullName = &quot;Himanshu Papola&quot;;<br>String space = &quot;   Hello World   &quot;;</pre><pre>// 🔹 1. Length and Case<br>System.out.println(name.length());           // → 8<br>System.out.println(name.toUpperCase());      // → HIMANSHU<br>System.out.println(name.toLowerCase());      // → himanshu</pre><pre>// 🔹 2. Comparison<br>System.out.println(name.toLowerCase().equals(&quot;Himanshu&quot;));       // → true<br>System.out.println(name.toLowerCase().equalsIgnoreCase(&quot;himanshu&quot;)); // → true<br>System.out.println(name.toLowerCase().compareTo(&quot;Himanshu&quot;));     // → 0 (lexicographical(dictionary) comparison)<br>System.out.println(name.compareToIgnoreCase(&quot;himanshu&quot;)); // → 0</pre><pre>// 🔹 3. Concatenation<br>System.out.println(name.concat(&quot; Papola&quot;));         // → Himanshu Papola<br>System.out.println(name + &quot; Papola&quot;);               // same as concat()</pre><pre>// 🔹 4. Character Operations<br>System.out.println(name.charAt(0));                 // → H<br>System.out.println(name.indexOf(&quot;h&quot;));              // → 6 (case-sensitive)<br>System.out.println(name.lastIndexOf(&quot;h&quot;));          // → 7<br>System.out.println(name.toLowerCase().contains(&quot;man&quot;));           // → true<br>System.out.println(name.toLowerCase().startsWith(&quot;Hi&quot;));          // → true<br>System.out.println(name.toLowerCase().endsWith(&quot;shu&quot;));           // → true</pre><pre>// 🔹 5. Substring<br>System.out.println(fullName.substring(0, 8));       // → Himanshu<br>System.out.println(fullName.substring(9));          // → Papola</pre><pre>// 🔹 6. Replace and Remove<br>System.out.println(fullName.replace(&quot;Papola&quot;, &quot;Singh&quot;));  // → Himanshu Singh<br>System.out.println(fullName.replaceAll(&quot;a&quot;, &quot;@&quot;));        // → Him@nshu P@pol@<br>System.out.println(fullName.replaceFirst(&quot;a&quot;, &quot;@&quot;));      // → Him@nshu Papola</pre><pre>// 🔹 7. Trim and Strip (remove spaces)<br>System.out.println(space.trim());          // &quot;Hello World&quot; (removes edges)<br>System.out.println(space.strip());           // same as trim (Unicode safe)<br>System.out.println(space.stripLeading());    // removes left spaces only<br>System.out.println(space.stripTrailing());   // removes right spaces only</pre><pre>// 🔹 8. Split and Join<br>String[] words = fullName.split(&quot; &quot;);  // split into [&quot;Himanshu&quot;, &quot;Papola&quot;]<br>for (String w : words) System.out.println(w);<br><br>String joined = String.join(&quot;-&quot;, &quot;Java&quot;, &quot;Spring&quot;, &quot;Boot&quot;);<br>System.out.println(joined);            // → Java-Spring-Boot</pre><pre>// 🔹 9. isEmpty / isBlank<br>System.out.println(&quot;&quot;.isEmpty());        // → true (no characters)<br>System.out.println(&quot;   &quot;.isBlank());     // → true (only whitespace)</pre><pre>// 🔹 10. Convert to Array and Bytes<br>char[] chars = name.toCharArray();  // → [&#39;H&#39;,&#39;i&#39;,&#39;m&#39;,&#39;a&#39;,&#39;n&#39;,&#39;s&#39;,&#39;h&#39;,&#39;u&#39;]<br>for (char c : chars) System.out.print(c + &quot; &quot;);<br>System.out.println();<br><br>byte[] bytes = name.getBytes();<br>System.out.println(Arrays.toString(bytes));</pre><pre>// 🔹 11. Format Strings<br>String formatted = String.format(&quot;Hello %s, you have %d new messages.&quot;, &quot;Himanshu&quot;, 5);<br>System.out.println(formatted);</pre><blockquote><strong><em>🚨 Limitations of </em></strong><strong><em>String in Java</em></strong></blockquote><p>The biggest limitation is: String is immutable</p><p>Meaning: <strong>Every modification creates a NEW String object.</strong></p><p>Example:</p><pre>String s = &quot;Hello&quot;;<br>s = s + &quot; World&quot;;</pre><p>What actually happens internally:<br>&quot;Hello&quot; exists &quot; World&quot; exists.<br>Java creates <strong>a new object</strong> &quot;Hello World&quot; <br>The old &quot;Hello&quot; is abandoned (goes for garbage collection)</p><blockquote><strong><em>Why is this bad? (Real-world problems)</em></strong></blockquote><p><strong>Problem 1: </strong>Performance issue inside loops</p><pre>String s = &quot;&quot;;<br>for (int i = 0; i &lt; 1000; i++) {<br>    s += i;<br>}</pre><p>This creates <strong>1000 new String objects</strong>.</p><p>Result is slow, Heavy CPU, Heavy memory usage and GC pressure</p><p><strong>Problem 2:</strong> Concatenation uses StringBuilder internally anyway</p><p>Even simple operations:</p><pre>String s = &quot;A&quot; + &quot;B&quot;;</pre><p>Compiler turns this into:</p><pre>new StringBuilder().append(&quot;A&quot;).append(&quot;B&quot;).toString();</pre><p>So if you write many + operations → <strong>you create unnecessary builders</strong> repeatedly.</p><p><strong>Problem 3:</strong> Repeated replacements are expensive</p><p>replace, substring, concat, toUpperCase → all create new objects.</p><h4>StringBuilder Fixes These Limitations</h4><p>StringBuilder is mutable and stores characters in a resizable array.<br>Methods like append, insert, replace, and reverse modify the same object, avoiding unnecessary memory creation and improving performance drastically.</p><p>StringBuilder is mutable, efficient, faster for repeated operations, dynamically grows its internal array, does not create new objects for every change</p><blockquote><strong>Internal structure:</strong></blockquote><p>Inside StringBuilder (simplified):</p><pre>char[] value = new char[16]; // Stores the characters with default capacity<br>int count;     // Number of characters currently used</pre><p><strong>A. value</strong></p><ul><li>Think of this as a <strong>big char array</strong> (like a bag).</li><li>It has <strong>extra empty space</strong> so new characters can be added without creating new arrays.</li></ul><p><strong>B. count</strong></p><ul><li>Tracks <strong>how many characters are currently inside</strong>.</li><li>Example: &quot;Hello&quot; → count = 5</li></ul><p><strong>C. Capacity</strong></p><pre>newCapacity = oldCapacity * 2 + 2</pre><p>StringBuilder keeps a char[] whose size is called capacity<br>When we append, characters are written directly into this array.<br>As long as the new content fits within capacity, no new array or object is created. Only when content &gt; capacity does the buffer expand.</p><blockquote><strong><em>Why is StringBuilder Faster?</em></strong></blockquote><p>Because operations like:append(), insert(), replace(), reverse()</p><p>All modify the <strong>same object in memory</strong>.</p><p>No object creation → <strong>no GC</strong> → <strong>big performance gain</strong></p><blockquote><strong><em>Important StringBuilder Methods</em></strong></blockquote><pre>StringBuilder sb = new StringBuilder(&quot;Hello&quot;);<br><br>// sb now contains: &quot;Hello&quot;<br><br>// length() (count) = 5<br><br>// capacity = 16 (default) + 5 (string length) = 21 //for constructor it work diff<br><br>// internal char[] = [H e l l o _ _ _ _ _ _ _ _ _ _ _ _ _ _]</pre><pre>sb.append(&#39;!&#39;); // Append adds a character at the end<br><br>sb.insert(sb.length(), &quot; World&quot;); // Insert adds &quot; World&quot; at the end<br><br>sb.replace(sb.length() - 1, sb.length(), &quot;!&quot;); // Replace overwrites characters in-place<br><br>sb.reverse(); // Reverse reverses the internal char array<br><br>System.out.println(sb.capacity()); // Print Capacity</pre><h4>StringBuffer For Thread-Safety &amp; Multithreading</h4><p>When working with strings in Java, developers often compare String, StringBuilder, and StringBuffer.<br> This article explains <strong>StringBuffer&#39;s thread-safe behavior</strong>, capacity handling, and how it behaves in a multithreading environment — using a complete runnable program.</p><blockquote><strong><em>What is StringBuffer?</em></strong></blockquote><p>StringBuffer is a mutable string class that is <strong>synchronized</strong> — meaning <strong>multiple threads can safely modify it</strong> without corrupting the data.</p><ul><li><strong>Thread-safe</strong> (every method is synchronized)</li><li>Safe for multi-threaded environments</li><li>Slightly slower than StringBuilder due to locking</li></ul><blockquote><strong><em>Default Capacity of StringBuffer</em></strong></blockquote><p>new StringBuffer() creates an internal array with <strong>default capacity 16</strong>.<br> When you append or insert beyond this capacity, it automatically expands based on:</p><pre>newCapacity = oldCapacity * 2 + 2</pre><blockquote><strong><em>Multithreading Demo with StringBuffer</em></strong></blockquote><p>Below is a full example where two threads (t1 and t2) append characters to the same StringBuffer.<br> Since StringBuffer is synchronized, the final string will always have the <strong>correct length</strong>.</p><pre>public class A03_StringBuffers_waitforthread {<br>    public static void main(String[] args) throws InterruptedException {<br><br>        // StringBuffer is thread-safe and synchronized (unlike StringBuilder)<br>        long startTime, endTime;<br><br>        // Measure start time<br>        startTime = System.currentTimeMillis();<br><br>        // Create a new StringBuffer object<br>        StringBuffer sb1 = new StringBuffer();<br><br>        // Append a character<br>        sb1.append(&#39;a&#39;);<br><br>        // Insert a string at index 0<br>        sb1.insert(0, &quot;bdddd&quot;);<br><br>        // Print current capacity (default 16 + inserted length)<br>        System.out.println(&quot;Capacity: &quot; + sb1.capacity());<br>        System.out.println(&quot;Value: &quot; + sb1);<br><br>        // Create another StringBuffer for multithreaded testing<br>        StringBuffer sb = new StringBuffer();<br><br>        // 🧵 Thread 1: Appends &quot;A&quot; 1000 times<br>        Thread t1 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 1000; i++) {<br>                sb.append(&quot;A&quot;);<br>            }<br>        });<br>        endTime = System.currentTimeMillis();<br>        System.out.println(&quot;Time taken (setup): &quot; + (endTime - startTime) + &quot; ms&quot;);<br>        <br>        // 🧵 Thread 2: Appends &quot;B&quot; 1000 times<br>        Thread t2 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 1000; i++) {<br>                sb.append(&quot;B&quot;);<br>            }<br>        });<br><br>        // Start both threads<br>        t1.start();<br>        t2.start();<br><br>        // Wait for both threads to finish<br>        t1.join();<br>        t2.join();<br><br>        // Final length = 2000 (1000 A&#39;s + 1000 B&#39;s)<br>        System.out.println(&quot;Final length: &quot; + sb.length());<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c43ed8033c58" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>