<?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 Aishu Reddy on Medium]]></title>
        <description><![CDATA[Stories by Aishu Reddy on Medium]]></description>
        <link>https://medium.com/@aishureddy?source=rss-04ef0daaee11------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*v8lIXChTjv3nUnlv</url>
            <title>Stories by Aishu Reddy on Medium</title>
            <link>https://medium.com/@aishureddy?source=rss-04ef0daaee11------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:05:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aishureddy/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[JUnit: A Complete Guide from Beginner to Advanced in Java]]></title>
            <link>https://medium.com/@aishureddy/junit-a-complete-guide-from-beginner-to-advanced-in-java-402483bfc4c0?source=rss-04ef0daaee11------2</link>
            <guid isPermaLink="false">https://medium.com/p/402483bfc4c0</guid>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[mockito]]></category>
            <dc:creator><![CDATA[Aishu Reddy]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 10:15:58 GMT</pubDate>
            <atom:updated>2026-10-16T10:15:58.152Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As Java developers, we write code to solve problems. But how do we know that our code works correctly? How can we make sure that a small change in one method does not break another part of the application?</p><p>We could run the application manually, enter different inputs, and check the output. This works for small programs, but as an application grows, manually testing every scenario becomes time-consuming and error-prone.</p><p>This is where <strong>JUnit</strong> comes into the picture.</p><p>JUnit is a popular, open-source testing framework for Java that allows developers to write and execute automated tests. It helps us verify that individual pieces of code behave as expected and quickly identify problems when the code changes.</p><p>In this blog, we will explore JUnit from the basics to advanced concepts, with practical examples, Maven configuration, annotations, assertions, exception testing, parameterized tests, Mockito, Spring Boot integration, and industry best practices.</p><h3>1. What Is Software Testing?</h3><p>Software testing is the process of checking whether an application behaves as expected.</p><p>Imagine that we are developing a calculator application. We have written a method to add two numbers:</p><pre>public int add(int a, int b) {<br>    return a + b;<br>}</pre><p>We expect add(10, 20) to return 30.</p><p>We can run the application, call the method, and check the result manually. However, we must repeat this process whenever we modify the code.</p><p>Instead, we can write a test that checks the expected result automatically.</p><pre>int result = add(10, 20);<br>System.out.println(result);</pre><p>This displays the result, but it does not automatically tell us whether the result is correct. We would still have to inspect it.</p><p>A testing framework allows us to express the expected behavior as an assertion and reports whether the test passes or fails.</p><h3>2. What Is Unit Testing?</h3><p>Unit testing is a type of software testing in which we verify a small, isolated unit of code, usually a method or a class.</p><p>For example, suppose our application contains:</p><ul><li>A calculator for arithmetic operations.</li><li>A service for calculating loan interest.</li><li>A utility for validating email addresses.</li><li>A service for calculating discounts.</li></ul><p>We can write individual tests for each unit.</p><p>For a loan-interest calculation, we might verify that the method returns the correct interest for a given principal, rate, and duration.</p><p>The purpose of unit testing is to detect defects early, verify expected behavior, and make future code changes safer.</p><h3>Unit testing versus manual testing</h3><p>Manual testing requires a person to execute steps and inspect results. Automated unit testing allows the computer to repeat those checks consistently.</p><p>Automated tests are particularly useful when a method has many possible inputs and when the application changes frequently.</p><h3>What makes a good unit test?</h3><p>A good unit test should be:</p><ul><li><strong>Independent:</strong> One test should not rely on another test’s execution.</li><li><strong>Repeatable:</strong> Running the same test under the same conditions should produce the same result.</li><li><strong>Fast:</strong> Unit tests should usually execute quickly.</li><li><strong>Readable:</strong> Developers should easily understand what is being tested.</li><li><strong>Focused:</strong> A test should verify a specific behavior rather than many unrelated behaviors.</li></ul><h3>3. Why Do We Need JUnit?</h3><p>Before using a testing framework, developers might write separate main() methods to test their application logic.</p><p>For example:</p><pre>public class TestCalculator {</pre><pre>    public static void main(String[] args) {<br>        Calculator calculator = new Calculator();</pre><pre>        int result = calculator.add(10, 20);</pre><pre>        if (result == 30) {<br>            System.out.println(&quot;Test passed&quot;);<br>        } else {<br>            System.out.println(&quot;Test failed&quot;);<br>        }<br>    }<br>}</pre><p>This approach works for a small example, but it becomes difficult to manage when an application contains hundreds or thousands of test cases.</p><p>JUnit provides a structured way to write, organize, execute, and report test results.</p><p>Its advantages include:</p><ol><li>Automated execution of test cases.</li><li>Assertions for comparing actual and expected results.</li><li>Lifecycle methods for preparing and cleaning up test resources.</li><li>Integration with IDEs such as IntelliJ IDEA and Eclipse.</li><li>Integration with Maven and Gradle.</li><li>Support for parameterized and repeated tests.</li><li>Integration with continuous integration and continuous delivery pipelines.</li><li>Easier detection of regressions after code changes.</li></ol><h3>4. What Is JUnit?</h3><p>JUnit is a testing framework for Java that provides annotations, assertions, and test execution infrastructure.</p><p>Developers write test methods, mark them with JUnit annotations, and use assertions to verify the results.</p><p>For example:</p><pre>import org.junit.jupiter.api.Test;</pre><pre>import static org.junit.jupiter.api.Assertions.assertEquals;</pre><pre>class CalculatorTest {</pre><pre>    @Test<br>    void shouldAddTwoNumbers() {<br>        Calculator calculator = new Calculator();</pre><pre>        int result = calculator.add(10, 20);</pre><pre>        assertEquals(30, result);<br>    }<br>}</pre><p>Here:</p><ul><li>@Test tells JUnit that the method is a test.</li><li>calculator.add(10, 20) executes the application logic.</li><li>assertEquals(30, result) checks whether the actual result equals the expected result.</li><li>If the assertion succeeds, the test passes. If it fails, JUnit reports a failure.</li></ul><p>Notice that we do not need a main() method in our test class. JUnit discovers and executes the test method.</p><h3>5. Understanding JUnit Versions</h3><p>JUnit has evolved through several versions.</p><h3>JUnit 3</h3><p>JUnit 3 used naming conventions and inheritance. Test classes commonly extended TestCase, and test methods started with test.</p><h3>JUnit 4</h3><p>JUnit 4 introduced annotations such as @Test, @Before, and @After, making tests more flexible and readable.</p><p>Example:</p><pre>import org.junit.Test;</pre><pre>import static org.junit.Assert.assertEquals;</pre><pre>public class CalculatorTest {</pre><pre>    @Test<br>    public void testAddition() {<br>        assertEquals(30, 10 + 20);<br>    }<br>}</pre><h3>JUnit 5</h3><p>JUnit 5 introduced a more modular architecture, a new programming model, and an extension model.</p><p>It provides annotations such as:</p><ul><li>@Test</li><li>@BeforeEach</li><li>@AfterEach</li><li>@BeforeAll</li><li>@AfterAll</li><li>@ParameterizedTest</li><li>@RepeatedTest</li><li>@Nested</li><li>@Tag</li><li>@Disabled</li></ul><p>JUnit 5 is commonly used with the <strong>Jupiter programming model</strong> in modern Java applications.</p><h3>Understanding JUnit 5’s architecture</h3><p>JUnit 5 is not simply one library. It consists of three major components:</p><p><strong>1. JUnit Platform</strong></p><p>The platform provides the <strong>infrastructure</strong> for discovering and launching tests. IDEs and build tools use it to execute tests.</p><p><strong>2. JUnit Jupiter</strong></p><p>Jupiter provides the <strong>programming model </strong>used to write JUnit 5 tests, including its annotations, assertions, lifecycle methods, and extension model.</p><p><strong>3. JUnit Vintage</strong></p><p>Vintage enables older JUnit 3 and JUnit 4 tests to run on the JUnit Platform when the relevant engine and dependencies are present.</p><p>A simple way to remember the architecture is:</p><ul><li>Platform = runs and coordinates tests.</li><li>Jupiter = lets us write modern JUnit tests.</li><li>Vintage = supports legacy JUnit tests.</li></ul><h3>6. Setting Up a JUnit Project</h3><p>Let’s create a Maven project and add JUnit 5.</p><h3>Step 1: Create a Maven project</h3><p>Create a standard Java Maven project in your IDE.</p><p>The project structure can look like this:</p><pre>junit-demo/<br>├── pom.xml<br>└── src/<br>    ├── main/<br>    │   └── java/<br>    │       └── Calculator.java<br>    └── test/<br>        └── java/<br>            └── CalculatorTest.java</pre><p>The src/main/java directory contains application code.</p><p>The src/test/java directory contains test code.</p><p>This separation helps us keep testing code separate from the production application.</p><h3>Step 2: Add the JUnit dependency</h3><p>Add the following dependency inside the &lt;dependencies&gt; element of your pom.xml:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;<br>    &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;<br>    &lt;version&gt;5.10.2&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>This is a pinned JUnit 5 example version, not a claim that it is the latest release. In a new project, choose a compatible version from the official JUnit documentation or your project’s dependency-management configuration.</p><p>The test scope means Maven makes the dependency available for compiling and running tests, without including it as a normal production dependency.</p><h3>Step 3: Configure Maven Surefire</h3><p>Maven Surefire is a Maven plugin responsible for running tests during the test phase.</p><p>For an explicitly configured JUnit 5 example, add the following inside &lt;build&gt;&lt;plugins&gt;:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>    &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;3.2.5&lt;/version&gt;<br>&lt;/plugin&gt;</pre><p>Modern Surefire versions support the JUnit Platform. Older plugin versions may need additional configuration, so make sure the plugin version is compatible with your chosen JUnit version.</p><h3>Step 4: Create the Calculator class</h3><p>Create Calculator.java inside src/main/java.</p><pre>public class Calculator {</pre><pre>    public int add(int a, int b) {<br>        return a + b;<br>    }</pre><pre>    public int subtract(int a, int b) {<br>        return a - b;<br>    }</pre><pre>    public int multiply(int a, int b) {<br>        return a * b;<br>    }</pre><pre>    public int divide(int a, int b) {<br>        if (b == 0) {<br>            throw new IllegalArgumentException(<br>                &quot;Divisor cannot be zero&quot;<br>            );<br>        }</pre><pre>        return a / b;<br>    }<br>}</pre><h3>Step 5: Create the first test class</h3><p>Create CalculatorTest.java inside src/test/java.</p><pre>import org.junit.jupiter.api.Test;</pre><pre>import static org.junit.jupiter.api.Assertions.assertEquals;</pre><pre>class CalculatorTest {</pre><pre>    @Test<br>    void shouldAddTwoNumbers() {<br>        Calculator calculator = new Calculator();</pre><pre>        int result = calculator.add(10, 20);</pre><pre>        assertEquals(30, result);<br>    }<br>}</pre><p>Run the test using your IDE’s test runner.</p><p>Alternatively, run:</p><pre>mvn test</pre><p>Maven compiles the production and test code, discovers supported tests, executes them, and reports the results.</p><p>If the actual result is 30, the assertion succeeds. If the actual result is different, the test fails and reports the mismatch.</p><h3>7. Writing Your First JUnit Test</h3><p>Let’s understand the test step by step.</p><pre>@Test<br>void shouldAddTwoNumbers() {<br>    Calculator calculator = new Calculator();</pre><pre>    int result = calculator.add(10, 20);</pre><pre>    assertEquals(30, result);<br>}</pre><p><strong>@Test</strong></p><p>This annotation marks a method as a test method recognized by JUnit Jupiter.</p><p><strong>shouldAddTwoNumbers()</strong></p><p>This is the name of our test method. A descriptive name explains the behavior being tested.</p><p><strong>Calculator calculator = new Calculator();</strong></p><p>We create the object that contains the logic we want to test.</p><p><strong>int result = calculator.add(10, 20);</strong></p><p>We execute the behavior under test.</p><p><strong>assertEquals(30, result);</strong></p><p>We verify the expected outcome.</p><h3>The Arrange–Act–Assert pattern</h3><p>A useful pattern for writing tests is AAA:</p><ul><li><strong>Arrange:</strong> Prepare the objects and input.</li><li><strong>Act:</strong> Execute the method being tested.</li><li><strong>Assert:</strong> Verify the result.</li></ul><p>For example:</p><pre>@Test<br>void shouldSubtractTwoNumbers() {</pre><pre>    // Arrange<br>    Calculator calculator = new Calculator();</pre><pre>    // Act<br>    int result = calculator.subtract(20, 10);</pre><pre>    // Assert<br>    assertEquals(10, result);<br>}</pre><p>Following this structure makes tests easier to read and maintain.</p><h3>8. Understanding Assertions in JUnit</h3><p>Assertions are the core of testing. They compare the actual behavior of our application with the expected behavior.</p><p>JUnit Jupiter provides many assertion methods through org.junit.jupiter.api.Assertions.</p><h3>8.1 assertEquals()</h3><p>Checks whether the expected value equals the actual value.</p><pre>assertEquals(30, calculator.add(10, 20));</pre><p>It can also accept a message:</p><pre>assertEquals(<br>    30,<br>    calculator.add(10, 20),<br>    &quot;Addition result should be 30&quot;<br>);</pre><h3>8.2 assertNotEquals()</h3><p>Checks that two values are not equal.</p><pre>assertNotEquals(100, calculator.add(10, 20));</pre><h3>8.3 assertTrue()</h3><p>Checks whether a condition is true.</p><pre>assertTrue(calculator.add(10, 20) &gt; 0);</pre><h3>8.4 assertFalse()</h3><p>Checks whether a condition is false.</p><pre>assertFalse(calculator.subtract(10, 20) &gt; 0);</pre><h3>8.5 assertNull()</h3><p>Checks whether a reference is null.</p><pre>String value = null;</pre><pre>assertNull(value);</pre><h3>8.6 assertNotNull()</h3><p>Checks that a reference is not null.</p><pre>String value = &quot;JUnit&quot;;</pre><pre>assertNotNull(value);</pre><h3>8.7 assertSame()</h3><p>Checks whether two references point to the same object.</p><pre>Object first = new Object();<br>Object second = first;</pre><pre>assertSame(first, second);</pre><h3>8.8 assertNotSame()</h3><p>Checks whether two references point to different objects.</p><pre>Object first = new Object();<br>Object second = new Object();</pre><pre>assertNotSame(first, second);</pre><p>Remember that assertSame() checks object identity, not whether two objects have equal contents.</p><h3>8.9 assertArrayEquals()</h3><p>Checks whether two arrays contain equal elements in the corresponding positions.</p><pre>int[] expected = {1, 2, 3};<br>int[] actual = {1, 2, 3};</pre><pre>assertArrayEquals(expected, actual);</pre><h3>8.10 assertIterableEquals()</h3><p>Checks whether two iterables contain corresponding equal elements in the same order.</p><pre>List&lt;Integer&gt; expected = Arrays.asList(1, 2, 3);<br>List&lt;Integer&gt; actual = Arrays.asList(1, 2, 3);</pre><pre>assertIterableEquals(expected, actual);</pre><h3>8.11 assertAll()</h3><p>Groups several assertions so that JUnit executes all of them and reports the failures together.</p><pre>import static org.junit.jupiter.api.Assertions.assertAll;<br>import static org.junit.jupiter.api.Assertions.assertEquals;</pre><pre>@Test<br>void shouldVerifyCalculatorResults() {</pre><pre>    Calculator calculator = new Calculator();</pre><pre>    assertAll(<br>        () -&gt; assertEquals(30, calculator.add(10, 20)),<br>        () -&gt; assertEquals(10, calculator.subtract(20, 10)),<br>        () -&gt; assertEquals(200, calculator.multiply(10, 20))<br>    );<br>}</pre><p>This is useful when several independent properties of the same result or object should be checked together.</p><h3>8.12 assertThrows()</h3><p>Checks that an operation throws the expected exception.</p><pre>import static org.junit.jupiter.api.Assertions.assertThrows;</pre><pre>@Test<br>void shouldThrowExceptionWhenDividingByZero() {</pre><pre>    Calculator calculator = new Calculator();</pre><pre>    assertThrows(<br>        IllegalArgumentException.class,<br>        () -&gt; calculator.divide(10, 0)<br>    );<br>}</pre><p>This test passes when the expected exception type, or a subtype of it, is thrown.</p><p>If the operation does not throw an exception, or throws an incompatible exception, the test fails.</p><h3>8.13 assertDoesNotThrow()</h3><p>Checks that an operation completes without throwing an exception.</p><pre>import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;</pre><pre>@Test<br>void shouldDivideValidNumbers() {</pre><pre>    Calculator calculator = new Calculator();</pre><pre>    assertDoesNotThrow(() -&gt; calculator.divide(10, 2));<br>}</pre><p>Use this when the absence of an exception is part of the behavior you want to verify.</p><h3>8.14 assertTimeout()</h3><p>Checks whether an operation completes within a specified duration.</p><pre>import java.time.Duration;</pre><pre>import static org.junit.jupiter.api.Assertions.assertTimeout;</pre><pre>@Test<br>void shouldCompleteWithinOneSecond() {</pre><pre>    assertTimeout(Duration.ofSeconds(1), () -&gt; {<br>        int result = 10 + 20;<br>        assertEquals(30, result);<br>    });<br>}</pre><p>assertTimeout() executes the supplied operation in the calling thread and checks the elapsed time after it finishes. It does not interrupt an operation simply because the duration has expired.</p><h3>8.15 assertTimeoutPreemptively()</h3><p>This assertion runs the operation in a separate thread and attempts to stop it when the timeout is exceeded.</p><p>It can be useful for operations that might otherwise block indefinitely. However, it should be used carefully because executing code on another thread can affect thread-local state, transaction behavior, and frameworks such as Spring.</p><h3>Choosing the right assertion</h3><p>MethodPurpose</p><p>assertEquals()Expected and actual values are equal</p><p>assertNotEquals()Values differ</p><p>assertTrue()Condition is true</p><p>assertFalse()Condition is false</p><p>assertNull()Reference is null</p><p>assertNotNull()Reference is not null</p><p>assertSame()References point to the same object</p><p>assertArrayEquals()Arrays contain matching elements</p><p>assertAll()Execute a group of assertions</p><p>assertThrows()Expected exception is thrown</p><p>assertDoesNotThrow()Operation completes without an exception</p><p>assertTimeout()Operation completes within a duration</p><h3>9. Testing Arrays and Collections</h3><p>JUnit can test arrays, lists, sets, maps, and other collection-based results.</p><p>For example, suppose a method returns a list of numbers.</p><pre>public List&lt;Integer&gt; getNumbers() {<br>    return Arrays.asList(1, 2, 3);<br>}</pre><p>We can test it using:</p><pre>@Test<br>void shouldReturnExpectedNumbers() {</pre><pre>    List&lt;Integer&gt; expected = Arrays.asList(1, 2, 3);<br>    List&lt;Integer&gt; actual = calculatorService.getNumbers();</pre><pre>    assertEquals(expected, actual);<br>}</pre><p>For lists, assertEquals() works when the expected and actual lists compare equal using their equals() implementations. For standard lists, this means the elements must match in order.</p><p>For arrays, use assertArrayEquals().</p><p>For maps, verify the expected keys and values, and consider checking whether unexpected entries are present.</p><p>The important point is to choose assertions that reflect the actual contract of the method.</p><h3>10. Test-Driven Development (TDD)</h3><p>Test-driven development is a software development approach in which we write a test before implementing the corresponding functionality.</p><p>It follows the <strong>Red–Green–Refactor</strong> cycle.</p><h3>Red: Write a failing test</h3><p>Suppose we want to implement addition.</p><p>First, write a test:</p><pre>@Test<br>void shouldAddTwoNumbers() {</pre><pre>    Calculator calculator = new Calculator();</pre><pre>    assertEquals(30, calculator.add(10, 20));<br>}</pre><p>If the method does not exist yet, the project will not compile. Once the method exists but does not implement the expected behavior, the test can fail.</p><h3>Green: Write the simplest implementation</h3><p>Implement the required behavior:</p><pre>public int add(int a, int b) {<br>    return a + b;<br>}</pre><p>Run the test again. It should now pass.</p><h3>Refactor: Improve the code</h3><p>Improve the implementation or test readability without changing the expected behavior. Then rerun the tests to make sure nothing has broken.</p><p>TDD encourages developers to think about expected behavior before implementation. It can also help reveal unclear requirements early.</p><h3>11. Testing Exceptions</h3><p>Applications often need to handle invalid inputs and exceptional situations.</p><p>For example, dividing by zero should produce a meaningful exception rather than an incorrect result.</p><p>We can verify that behavior with assertThrows():</p><pre>@Test<br>void shouldRejectDivisionByZero() {</pre><pre>    Calculator calculator = new Calculator();</pre><pre>    IllegalArgumentException exception = assertThrows(<br>        IllegalArgumentException.class,<br>        () -&gt; calculator.divide(10, 0)<br>    );</pre><pre>    assertEquals(&quot;Divisor cannot be zero&quot;, exception.getMessage());<br>}</pre><p>This test checks both the exception type and its message.</p><p>We should not catch the exception and simply print a message, because the test must fail if the expected exception is not thrown.</p><p>Test exception behavior deliberately, especially when methods validate user input, process financial amounts, or enforce business rules.</p><h3>12. JUnit Lifecycle Annotations</h3><p>Sometimes tests require setup before execution and cleanup afterward. JUnit provides lifecycle annotations to handle these tasks.</p><h3>12.1 @BeforeEach</h3><p>Runs before every test method in the test instance.</p><pre>@BeforeEach<br>void setUp() {<br>    calculator = new Calculator();<br>}</pre><p>It is useful for creating fresh objects or resetting test state.</p><h3>12.2 @AfterEach</h3><p>Runs after every test method in the test instance, including when a test fails.</p><pre>@AfterEach<br>void tearDown() {<br>    calculator = null;<br>}</pre><p>It is commonly used to release resources created during a test.</p><h3>12.3 @BeforeAll</h3><p>Runs once before all test methods in the class, subject to the lifecycle configuration.</p><pre>@BeforeAll<br>static void beforeAll() {<br>    System.out.println(&quot;Starting calculator tests&quot;);<br>}</pre><p>With the default test-instance lifecycle, the method must be static.</p><h3>12.4 @AfterAll</h3><p>Runs once after all test methods in the class.</p><pre>@AfterAll<br>static void afterAll() {<br>    System.out.println(&quot;Finished calculator tests&quot;);<br>}</pre><p>With the default lifecycle, this method must also be static.</p><h3>Complete lifecycle example</h3><pre>import org.junit.jupiter.api.*;</pre><pre>import static org.junit.jupiter.api.Assertions.assertEquals;</pre><pre>class CalculatorTest {</pre><pre>    private Calculator calculator;</pre><pre>    @BeforeAll<br>    static void beforeAll() {<br>        System.out.println(&quot;Test class started&quot;);<br>    }</pre><pre>    @BeforeEach<br>    void setUp() {<br>        calculator = new Calculator();<br>        System.out.println(&quot;Preparing test&quot;);<br>    }</pre><pre>    @Test<br>    void shouldAddNumbers() {<br>        assertEquals(30, calculator.add(10, 20));<br>    }</pre><pre>    @Test<br>    void shouldSubtractNumbers() {<br>        assertEquals(10, calculator.subtract(20, 10));<br>    }</pre><pre>    @AfterEach<br>    void tearDown() {<br>        calculator = null;<br>        System.out.println(&quot;Cleaning up test&quot;);<br>    }</pre><pre>    @AfterAll<br>    static void afterAll() {<br>        System.out.println(&quot;Test class finished&quot;);<br>    }<br>}</pre><h3>Typical lifecycle order</h3><p>For a class with two test methods, the lifecycle is generally:</p><ol><li>@BeforeAll</li><li>@BeforeEach</li><li>First test method</li><li>@AfterEach</li><li>@BeforeEach</li><li>Second test method</li><li>@AfterEach</li><li>@AfterAll</li></ol><p>The order of the two test methods is not guaranteed by default. Tests should not depend on a particular execution order.</p><h3>13. Test Instance Lifecycle</h3><p>JUnit Jupiter supports two principal test-instance lifecycle modes.</p><h3>PER_METHOD</h3><p>This is the default.</p><p>JUnit creates a new test-class instance for each test method.</p><p>This helps isolate instance fields between tests.</p><h3>PER_CLASS</h3><p>JUnit creates one test-class instance for all test methods in the class.</p><p>You can enable it with:</p><pre>@TestInstance(TestInstance.Lifecycle.PER_CLASS)<br>class CalculatorTest {<br>    // Tests and lifecycle methods<br>}</pre><p>With PER_CLASS, non-static @BeforeAll and @AfterAll methods are permitted.</p><p>However, instance fields are shared across test methods, so mutable state can cause tests to influence each other.</p><p><strong>Best practice:</strong> Prefer independent tests and avoid shared mutable state unless it is intentional and carefully managed.</p><h3>14. Naming and Organizing Test Methods</h3><p>A good test name explains the behavior and the expected outcome.</p><p>Examples:</p><pre>shouldAddTwoPositiveNumbers()<br>shouldReturnZeroWhenSubtractingEqualNumbers()<br>shouldRejectDivisionByZero()<br>shouldReturnEmptyListWhenNoRecordsExist()</pre><p>Another common naming convention is:</p><p>methodName_condition_expectedResult</p><p>For example:</p><p>divide_byZero_throwsIllegalArgumentException()</p><p>Choose one convention and apply it consistently across the project.</p><h3>15. Disabling and Grouping Tests</h3><h3>@Disabled</h3><p>Temporarily disables a test or test class.</p><pre>@Disabled(&quot;Waiting for the dependent feature&quot;)<br>@Test<br>void shouldVerifyUpcomingFeature() {<br>    // Test implementation<br>}</pre><p>Disabled tests are not executed. Avoid leaving tests disabled indefinitely, especially when they cover important behavior.</p><h3>@DisplayName</h3><p>Provides a readable name for a test.</p><pre>@Test<br>@DisplayName(&quot;Should add two positive numbers&quot;)<br>void shouldAddTwoNumbers() {<br>    assertEquals(30, 10 + 20);<br>}</pre><p>This can improve the test reports produced by IDEs and build tools.</p><h3>@Tag</h3><p>Groups tests by category.</p><pre>@Test<br>@Tag(&quot;fast&quot;)<br>void shouldAddNumbers() {<br>    assertEquals(30, 10 + 20);<br>}</pre><p>Tags can be used to select or exclude groups of tests through build-tool configuration.</p><p>For example, a project might group tests into fast, integration, and slow. The exact tag names are project conventions.</p><h3>16. Parameterized Tests</h3><p>Suppose we want to test addition for ten different pairs of numbers.</p><p>Writing ten nearly identical test methods would create unnecessary duplication.</p><p><strong>Parameterized tests let us execute one test method with several sets of inputs</strong>.</p><p>JUnit Jupiter provides @ParameterizedTest and several argument-source annotations.</p><p>JUnit also accepts a lambda expression that supplies the message.</p><pre>assertTrue(<br>    actual &gt; 0,<br>    () -&gt; &quot;Expected a positive result, but got: &quot; + actual<br>);</pre><p>The message is generated only if the assertion fails. This is called lazy evaluation and can improve performance when generating the message is expensive.</p><h3>16.1 @ValueSource</h3><p>Suitable when each invocation needs a single value.</p><pre>import org.junit.jupiter.params.ParameterizedTest;<br>import org.junit.jupiter.params.provider.ValueSource;</pre><pre>import static org.junit.jupiter.api.Assertions.assertTrue;</pre><pre>class NumberTest {</pre><pre>    @ParameterizedTest<br>    @ValueSource(ints = {2, 4, 6, 8, 10})<br>    void shouldIdentifyEvenNumbers(int number) {<br>        assertTrue(number % 2 == 0);<br>    }<br>}</pre><p>JUnit executes the test separately for each supplied integer.</p><h3>16.2 @CsvSource</h3><p>Useful when each test invocation requires multiple values.</p><pre>import org.junit.jupiter.params.ParameterizedTest;<br>import org.junit.jupiter.params.provider.CsvSource;</pre><pre>import static org.junit.jupiter.api.Assertions.assertEquals;</pre><pre>class CalculatorTest {</pre><pre>    private final Calculator calculator = new Calculator();</pre><pre>    @ParameterizedTest<br>    @CsvSource({<br>        &quot;10, 20, 30&quot;,<br>        &quot;5,  5,  10&quot;,<br>        &quot;-2, 3,  1&quot;,<br>        &quot;0,  0,  0&quot;<br>    })<br>    void shouldAddDifferentNumbers(<br>            int a, int b, int expected) {</pre><pre>        assertEquals(expected, calculator.add(a, b));<br>    }<br>}</pre><p>Each row contains two input values and one expected result.</p><h3>16.3 @CsvFileSource</h3><p>Useful when test data is stored in a CSV file.</p><pre>@ParameterizedTest<br>@CsvFileSource(<br>    resources = &quot;/calculator-data.csv&quot;,<br>    numLinesToSkip = 1<br>)<br>void shouldAddNumbersFromFile(<br>        int a, int b, int expected) {</pre><pre>    assertEquals(expected, calculator.add(a, b));<br>}</pre><p>The file can be stored at src/test/resources/calculator-data.csv.</p><h3>16.4 @MethodSource</h3><p>Useful when test data requires objects, more complex values, or programmatically generated arguments.</p><pre>import java.util.stream.Stream;</pre><pre>import org.junit.jupiter.params.ParameterizedTest;<br>import org.junit.jupiter.params.provider.MethodSource;</pre><pre>import static org.junit.jupiter.api.Assertions.assertEquals;</pre><pre>class CalculatorTest {</pre><pre>    static Stream&lt;org.junit.jupiter.params.provider.Arguments&gt;<br>            additionCases() {</pre><pre>        return Stream.of(<br>            org.junit.jupiter.params.provider.Arguments.of(1, 2, 3),<br>            org.junit.jupiter.params.provider.Arguments.of(5, 5, 10),<br>            org.junit.jupiter.params.provider.Arguments.of(-1, 1, 0)<br>        );<br>    }</pre><pre>    @ParameterizedTest<br>    @MethodSource(&quot;additionCases&quot;)<br>    void shouldAddNumbers(<br>            int a, int b, int expected) {</pre><pre>        assertEquals(expected, new Calculator().add(a, b));<br>    }<br>}</pre><h3>16.5 @NullSource, @EmptySource, and @NullAndEmptySource</h3><p>These annotations help test methods that accept strings and other supported types.</p><pre>@ParameterizedTest<br>@NullAndEmptySource<br>@ValueSource(strings = {&quot; &quot;, &quot;\t&quot;})<br>void shouldRejectBlankInput(String input) {<br>    // Assert the behavior of your input validator.<br>}</pre><p>The test body should contain the assertion appropriate to the validator being tested.</p><h3>16.6 @EnumSource</h3><p>Useful when testing behavior across enum values.</p><pre>@ParameterizedTest<br>@EnumSource(value = DayOfWeek.class, names = {&quot;MONDAY&quot;, &quot;FRIDAY&quot;})<br>void shouldHandleSelectedDays(DayOfWeek day) {<br>    assertNotNull(day);<br>}</pre><h3>Why use parameterized tests?</h3><p>They reduce duplication, make it easier to cover boundary cases, and help verify that the same behavior holds for different inputs.</p><p>Use them when the cases share the same logic. If two scenarios have substantially different behavior or setup, separate test methods may be clearer.</p><h3>17. Repeated Tests</h3><p>JUnit provides @RepeatedTest when you want to run a test a specified number of times.</p><pre>import org.junit.jupiter.api.RepeatedTest;</pre><pre>import static org.junit.jupiter.api.Assertions.assertEquals;</pre><pre>class CalculatorTest {</pre><pre>    @RepeatedTest(5)<br>    void shouldAddNumbersRepeatedly() {<br>        assertEquals(30, new Calculator().add(10, 20));<br>    }<br>}</pre><p>This runs the test five times.</p><p>Repeated tests can help exercise behavior across repeated invocations, but they do not automatically prove that concurrent code is thread-safe or that a flaky test is correct.</p><h3>18. Nested Tests</h3><p>@Nested allows related test cases to be grouped inside nested test classes.</p><p>For example, a service might behave differently for valid and invalid inputs.</p><pre>import org.junit.jupiter.api.Nested;<br>import org.junit.jupiter.api.Test;</pre><pre>import static org.junit.jupiter.api.Assertions.*;</pre><pre>class CalculatorTest {</pre><pre>    private final Calculator calculator = new Calculator();</pre><pre>    @Nested<br>    class AdditionTests {</pre><pre>        @Test<br>        void shouldAddPositiveNumbers() {<br>            assertEquals(30, calculator.add(10, 20));<br>        }</pre><pre>        @Test<br>        void shouldAddNegativeNumbers() {<br>            assertEquals(-30, calculator.add(-10, -20));<br>        }<br>    }</pre><pre>    @Nested<br>    class DivisionTests {</pre><pre>        @Test<br>        void shouldDivideNumbers() {<br>            assertEquals(5, calculator.divide(10, 2));<br>        }</pre><pre>        @Test<br>        void shouldRejectZeroDivisor() {<br>            assertThrows(<br>                IllegalArgumentException.class,<br>                () -&gt; calculator.divide(10, 0)<br>            );<br>        }<br>    }<br>}</pre><p>Nested classes help organize tests around behaviors or scenarios. They are especially useful when the test suite grows.</p><h3>19. Test Information and Reporting</h3><p>JUnit can provide information about the currently executing test.</p><p>For example, TestInfo can supply the test&#39;s display name, method, class, and tags.</p><pre>import org.junit.jupiter.api.Test;<br>import org.junit.jupiter.api.TestInfo;</pre><pre>class ExampleTest {</pre><pre>    @Test<br>    void shouldReadTestInformation(TestInfo testInfo) {<br>        System.out.println(testInfo.getDisplayName());<br>    }<br>}</pre><p>JUnit also provides TestReporter, which allows tests to publish additional information to the test execution report.</p><p>These facilities are useful for diagnostics, but they should not replace assertions or be used to make tests depend on their names or execution order.</p><h3>20. Running JUnit Tests Without Maven</h3><p>JUnit does not require Maven as a concept. Maven is a build tool that can download dependencies and execute tests.</p><p>Tests can also be run using an IDE, Gradle, or the JUnit Platform Console Launcher.</p><p>Running a JUnit test without a build tool requires the correct JUnit libraries and their compatible dependencies on the classpath.</p><p>For a beginner, Maven or Gradle is usually the simplest choice because it manages dependencies and provides a repeatable test command.</p><h3>21. JUnit and Maven Build Lifecycle</h3><p>Maven defines several build lifecycle phases. The ones commonly used when testing Java applications include:</p><ul><li>mvn test: Compiles the code and runs tests in the test phase.</li><li>mvn package: Runs the earlier required phases and packages the application.</li><li>mvn verify: Runs the required earlier phases and verification checks configured in the build.</li></ul><p>For a normal Java project, mvn test is the common starting point.</p><p>In a larger project, you may configure Surefire for unit tests and Maven Failsafe for integration tests that run during the integration-test and verify phases.</p><p>A test that is not discovered by the configured test engine or plugin will not run merely because its source file exists. If a test is missing from reports, check its annotations, naming patterns, dependencies, and plugin configuration.</p><h3>22. Introduction to Mockito</h3><p>JUnit provides the structure for writing and running tests. But real applications often depend on databases, external APIs, email services, message queues, and other components.</p><p>For a unit test, we usually want to focus on the behavior of the class under test without requiring every external dependency to be available.</p><p><strong>Mockito</strong> is a Java mocking framework that lets us create test doubles for dependencies, define their behavior, and verify interactions with them.</p><p>JUnit and Mockito solve different problems and are commonly used together.</p><h3>Example: Testing a service with a dependency</h3><p>Suppose we have a repository interface:</p><pre>public interface UserRepository {<br>    String findUserNameById(int id);<br>}</pre><p>And a service:</p><pre>public class UserService {</pre><pre>    private final UserRepository repository;</pre><pre>    public UserService(UserRepository repository) {<br>        this.repository = repository;<br>    }</pre><pre>    public String getUserName(int id) {<br>        return repository.findUserNameById(id);<br>    }<br>}</pre><p>We want to test UserService without connecting to a real database.</p><p>Using Mockito:</p><pre>import org.junit.jupiter.api.Test;<br>import org.junit.jupiter.api.extension.ExtendWith;</pre><pre>import org.mockito.InjectMocks;<br>import org.mockito.Mock;<br>import org.mockito.junit.jupiter.MockitoExtension;</pre><pre>import static org.junit.jupiter.api.Assertions.assertEquals;<br>import static org.mockito.Mockito.when;</pre><pre>@ExtendWith(MockitoExtension.class)<br>class UserServiceTest {</pre><pre>    @Mock<br>    private UserRepository repository;</pre><pre>    @InjectMocks<br>    private UserService userService;</pre><pre>    @Test<br>    void shouldReturnUserName() {</pre><pre>        when(repository.findUserNameById(1))<br>            .thenReturn(&quot;Asha&quot;);</pre><pre>        String result = userService.getUserName(1);</pre><pre>        assertEquals(&quot;Asha&quot;, result);<br>    }<br>}</pre><p>The test uses a mocked repository that returns a predefined value. No real database is required.</p><p>For this example, add a compatible mockito-junit-jupiter test dependency to your Maven project.</p><h3>Important Mockito concepts</h3><ul><li>@Mock: Creates a mock dependency.</li><li>@InjectMocks: Creates the object under test and attempts to inject its mocks.</li><li>when(...).thenReturn(...): Defines a mock&#39;s behavior.</li><li>verify(...): Verifies that an interaction occurred.</li><li>@ExtendWith(MockitoExtension.class): Integrates Mockito with JUnit Jupiter.</li></ul><p>Mocks are useful when a class collaborates with other components. However, mocking every object can make tests brittle. Prefer real objects for simple value objects and straightforward business logic.</p><h3>23. Stubbing and Verifying Interactions</h3><p>Sometimes, checking the returned result is not enough. We may also need to verify that the service called a dependency correctly.</p><p>Mockito’s verify() method supports this.</p><pre>import static org.mockito.Mockito.verify;</pre><pre>@Test<br>void shouldCallRepositoryWithCorrectId() {</pre><pre>    when(repository.findUserNameById(1))<br>        .thenReturn(&quot;Asha&quot;);</pre><pre>    String result = userService.getUserName(1);</pre><pre>    assertEquals(&quot;Asha&quot;, result);<br>    verify(repository).findUserNameById(1);<br>}</pre><p>This checks that the repository method was called with ID 1.</p><p>Interaction verification is valuable when the interaction itself is part of the expected behavior, such as publishing a required event or calling a payment gateway.</p><p>Avoid verifying every internal method call without a reason. Tests should primarily describe observable behavior rather than implementation details.</p><h3>24. JUnit in Spring Boot Applications</h3><p>In real Java projects, especially backend services, JUnit is often used to test Spring components.</p><p>Spring Boot provides testing support through spring-boot-starter-test, which commonly includes JUnit Jupiter, Mockito, and other testing libraries.</p><p>For projects managed by Spring Boot, it is generally best to use the version of spring-boot-starter-test managed by the project&#39;s Spring Boot dependency management rather than manually mixing incompatible versions.</p><h3>Unit test for a service</h3><p>A service containing ordinary business logic can often be tested without starting the Spring application context.</p><pre>class DiscountService {</pre><pre>    public double calculateDiscount(double amount) {<br>        if (amount &lt; 1000) {<br>            return 0;<br>        }</pre><pre>        return amount * 0.10;<br>    }<br>}</pre><p>Test:</p><pre>import org.junit.jupiter.api.Test;</pre><pre>import static org.junit.jupiter.api.Assertions.assertEquals;</pre><pre>class DiscountServiceTest {</pre><pre>    private final DiscountService service = new DiscountService();</pre><pre>    @Test<br>    void shouldCalculateDiscountForEligibleAmount() {<br>        assertEquals(<br>            200.0,<br>            service.calculateDiscount(2000),<br>            0.001<br>        );<br>    }<br>}</pre><p>The third argument to assertEquals() specifies a tolerance for floating-point comparison.</p><p>For financial calculations, prefer BigDecimal with explicit rounding rules rather than using double for monetary values.</p><h3>Testing a Spring component with @SpringBootTest</h3><p>@SpringBootTest loads a Spring application context for integration-style testing.</p><pre>@SpringBootTest<br>class ApplicationContextTest {</pre><pre>    @Test<br>    void shouldLoadApplicationContext() {<br>        // If the test executes successfully,<br>        // the application context loaded.<br>    }<br>}</pre><p>This test verifies that the application context can start successfully. It does not by itself prove that every service or endpoint behaves correctly.</p><p>Because context startup can be relatively expensive, use it when Spring configuration or bean integration is part of the behavior being tested, rather than for every simple business-logic test.</p><h3>Testing MVC controllers with @WebMvcTest</h3><p>@WebMvcTest focuses on Spring MVC components. It is useful for testing controller behavior, request handling, validation, and HTTP responses <strong>without loading the entire application context</strong>.</p><p>A controller test typically uses MockMvc and mocks the controller&#39;s service dependencies.</p><h3>Testing repositories with @DataJpaTest</h3><p>@DataJpaTest focuses on JPA-related components, such as repositories and entity mappings.</p><p>It is useful for checking repository queries, persistence behavior, and entity relationships. Depending on configuration, it may use an embedded database or another configured test database.</p><h3>Testing REST APIs</h3><p>Spring Boot applications commonly use MockMvc or WebTestClient to test HTTP behavior.</p><p>These tools can verify:</p><ul><li>HTTP status codes.</li><li>Response bodies.</li><li>Request validation.</li><li>Headers.</li><li>Error handling.</li><li>Controller-to-service interactions.</li></ul><p>For example, a REST endpoint that retrieves a user should be tested for both successful requests and appropriate error responses when the user does not exist.</p><h3>25. JUnit Extensions</h3><p>JUnit Jupiter supports extensions that integrate additional behavior into the test lifecycle.</p><p>Extensions can participate in test execution, manage resources, resolve parameters, and provide other reusable functionality.</p><p>Examples include:</p><ul><li>MockitoExtension for Mockito integration.</li><li>Spring’s testing extensions for application-context integration.</li><li>Custom extensions for reusable setup or test infrastructure.</li></ul><p>An extension is a way to add reusable testing behavior without repeating the same setup code in every test class.</p><p>Use extensions when the behavior is genuinely shared across tests and an extension makes the tests easier to understand.</p><h3>26. Test Suites</h3><p>A test suite groups selected tests so that they can be executed together.</p><p>JUnit Platform supports suites through its suite API and suite engine. This can be useful when a project has separate groups of tests for particular modules or workflows.</p><p>For example, a project might maintain a suite for fast unit tests and another for selected integration tests.</p><p>Test suites are especially useful when the test suite becomes large and teams need controlled ways to execute specific subsets of tests.</p><h3>27. JUnit and Continuous Integration</h3><p>JUnit tests are not limited to a developer’s local machine.</p><p>They can run automatically in a continuous integration pipeline whenever code is pushed or a pull request is created.</p><p>A typical workflow is:</p><ol><li>A developer pushes code.</li><li>The build pipeline compiles the application.</li><li>Automated tests run.</li><li>The pipeline collects test reports.</li><li>The team reviews failures before merging or deploying the change.</li></ol><p>For a Maven project, the test command is commonly:</p><pre>mvn test</pre><p>Build systems can use the resulting reports to identify failed tests and prevent broken changes from progressing through the pipeline.</p><p>A passing unit-test suite is valuable, but it does not guarantee that an application is free of bugs. Integration, security, performance, and other relevant tests may still be required.</p><h3>29. Best Practices for Writing JUnit Tests</h3><h3>1. Test behavior, not implementation details</h3><p>Tests should describe what the application is expected to do. Avoid tying them unnecessarily to private methods or internal implementation choices.</p><h3>2. Keep tests independent</h3><p>One test should not require another test to run first. Avoid shared mutable state that can cause order-dependent failures.</p><h3>3. Test positive and negative scenarios</h3><p>For each important behavior, consider valid inputs, invalid inputs, boundary values, and exceptional conditions.</p><h3>4. Use meaningful test names</h3><p>A test name should communicate the scenario and expected behavior.</p><h3>5. Avoid excessive mocking</h3><p>Mocks are useful for dependencies, but over-mocking can make tests difficult to understand and sensitive to implementation changes.</p><h3>6. Keep unit tests fast</h3><p>Use unit tests for logic that does not need a database, web server, or complete Spring context. Reserve heavier tests for scenarios that genuinely need them.</p><h3>7. Use assertions that match the requirement</h3><p>Do not merely check that a method executes. Verify the output, state change, exception, or interaction that matters.</p><h3>8. Avoid unnecessary sleeps</h3><p>Tests that call Thread.sleep() to wait for an event can be slow and unreliable. Prefer deterministic synchronization or suitable testing utilities.</p><h3>9. Test boundary cases</h3><p>For example, a discount rule that applies at an amount of 1000 should be tested just below, exactly at, and just above that threshold.</p><h3>10. Maintain tests as the application evolves</h3><p>When expected behavior changes, update the tests deliberately. Do not remove a failing assertion simply to make the build pass.</p><h3>30. Common JUnit Mistakes</h3><p><strong>Mistake 1: Using the wrong </strong><strong>@Test import</strong></p><p>JUnit 4 and JUnit Jupiter use different packages.</p><p>JUnit 4:</p><pre>import org.junit.Test;</pre><p>JUnit Jupiter:</p><pre>import org.junit.jupiter.api.Test;</pre><p>Make sure your imports match the JUnit version and test engine configured in the project.</p><p><strong>Mistake 2: Forgetting the test dependency</strong></p><p>If JUnit is missing from the test classpath, imports will fail or the tests will not compile.</p><p><strong>Mistake 3: Using an incompatible Maven Surefire version</strong></p><p>An old plugin configuration may not discover or execute Jupiter tests as expected.</p><p><strong>Mistake 4: Writing tests that depend on execution order</strong></p><p>JUnit does not guarantee a useful default order for ordinary tests. Each test should prepare the state it needs.</p><p><strong>Mistake 5: Checking only the happy path</strong></p><p>A method can work for normal input but fail for empty input, null, boundary values, or invalid parameters.</p><p><strong>Mistake 6: Writing assertions that do not test the intended behavior</strong></p><p>A test that only checks that a variable is not null may miss an incorrect result. Assertions should reflect the actual requirement.</p><h3>How do we run JUnit tests in parallel?</h3><p>By default, JUnit Jupiter runs tests sequentially. Parallel execution is an opt-in feature that can reduce execution time when a project has many independent tests.</p><p>For example, imagine you have:</p><ul><li>Test A — takes 3 seconds</li><li>Test B — takes 3 seconds</li><li>Test C — takes 3 seconds</li></ul><p>If they run sequentially, the total is approximately 9 seconds. If they run concurrently, the total could be closer to 3 seconds, depending on available resources and overhead.</p><h3>Step 1: Create the configuration file</h3><p>Create this file in your test resources directory:</p><p>src/test/resources/junit-platform.properties</p><p>Add the following properties:</p><pre>junit.jupiter.execution.parallel.enabled=true<br>junit.jupiter.execution.parallel.mode.default=concurrent</pre><p>What do they mean?</p><p>Property</p><p>Purpose</p><p>parallel.enabled=true</p><p>Enables parallel execution support</p><p>mode.default=concurrent</p><p>Allows tests to execute concurrently by default</p><p>Both settings matter: enabling parallel execution alone does not automatically make every test run concurrently.</p><p>Step 2: Write independent tests</p><pre>import org.junit.jupiter.api.Test;</pre><pre>import static org.junit.jupiter.api.Assertions.assertEquals;</pre><pre>class CalculatorTest {</pre><pre>    @Test<br>    void testAddition() throws InterruptedException {<br>        Thread.sleep(2000);<br>        assertEquals(30, 10 + 20);<br>        System.out.println(&quot;Addition: &quot; +<br>                Thread.currentThread().getName());<br>    }</pre><pre>    @Test<br>    void testSubtraction() throws InterruptedException {<br>        Thread.sleep(2000);<br>        assertEquals(10, 20 - 10);<br>        System.out.println(&quot;Subtraction: &quot; +<br>                Thread.currentThread().getName());<br>    }</pre><pre>    @Test<br>    void testMultiplication() throws InterruptedException {<br>        Thread.sleep(2000);<br>        assertEquals(200, 10 * 20);<br>        System.out.println(&quot;Multiplication: &quot; +<br>                Thread.currentThread().getName());<br>    }<br>}</pre><p>The Thread.sleep() calls are only to demonstrate the difference in execution time. Avoid using sleeps in real unit tests when possible.</p><p>Run the tests normally through your IDE or with Maven:</p><pre>mvn test</pre><p>If the configuration is loaded and the execution environment has enough resources, the tests can overlap rather than waiting for each other.</p><h3>Step 3: Configure the number of concurrent tests</h3><p>If you want to control the desired parallelism, add these properties instead:</p><pre>junit.jupiter.execution.parallel.enabled=true<br>junit.jupiter.execution.parallel.mode.default=concurrent<br>junit.jupiter.execution.parallel.config.strategy=fixed<br>junit.jupiter.execution.parallel.config.fixed.parallelism=4</pre><p>This requests a fixed parallelism of four. It does not necessarily guarantee that no more than four threads will ever be active, since JUnit’s concurrency and thread-pool behavior depend on its execution configuration.</p><h3>31. A Complete Calculator Test Class</h3><p>Let’s bring together the main concepts in one example.</p><pre>import org.junit.jupiter.api.BeforeEach;<br>import org.junit.jupiter.api.Test;<br>import org.junit.jupiter.api.DisplayName;</pre><pre>import static org.junit.jupiter.api.Assertions.*;</pre><pre>class CalculatorTest {</pre><pre>    private Calculator calculator;</pre><pre>    @BeforeEach<br>    void setUp() {<br>        calculator = new Calculator();<br>    }</pre><pre>    @Test<br>    @DisplayName(&quot;Should add two numbers&quot;)<br>    void shouldAddNumbers() {<br>        assertEquals(30, calculator.add(10, 20));<br>    }</pre><pre>    @Test<br>    void shouldSubtractNumbers() {<br>        assertEquals(10, calculator.subtract(20, 10));<br>    }</pre><pre>    @Test<br>    void shouldMultiplyNumbers() {<br>        assertEquals(200, calculator.multiply(10, 20));<br>    }</pre><pre>    @Test<br>    void shouldDivideNumbers() {<br>        assertEquals(5, calculator.divide(10, 2));<br>    }</pre><pre>    @Test<br>    void shouldRejectDivisionByZero() {<br>        IllegalArgumentException exception = assertThrows(<br>            IllegalArgumentException.class,<br>            () -&gt; calculator.divide(10, 0)<br>        );</pre><pre>        assertEquals(<br>            &quot;Divisor cannot be zero&quot;,<br>            exception.getMessage()<br>        );<br>    }</pre><pre>    @Test<br>    void shouldAddNegativeNumbers() {<br>        assertEquals(-30, calculator.add(-10, -20));<br>    }</pre><pre>    @Test<br>    void shouldAddZero() {<br>        assertEquals(10, calculator.add(10, 0));<br>    }<br>}</pre><p>This test class demonstrates lifecycle setup, descriptive test names, assertions, and exception testing.</p><p>As the project grows, parameterized tests can reduce repetition in cases where several inputs follow the same behavior.</p><h3>32. Interview Questions on JUnit</h3><p><strong>1. What is JUnit?</strong></p><p>JUnit is a Java testing framework used to write and execute automated tests.</p><p><strong>2. What is unit testing?</strong></p><p>Unit testing verifies a small, isolated part of an application, usually a method or class.</p><p><strong>3. What is the difference between JUnit 4 and JUnit 5?</strong></p><p>JUnit 5 introduced the Platform, Jupiter, and Vintage architecture, along with a new programming and extension model. It also uses different annotation packages and provides modern features such as parameterized tests.</p><p><strong>4. What is the purpose of </strong><strong>@Test?</strong></p><p>It identifies a test method for JUnit to discover and execute.</p><p><strong>5. What is the difference between </strong><strong>@BeforeEach and </strong><strong>@BeforeAll?</strong></p><p>@BeforeEach runs before each test method, while @BeforeAll runs once before all tests in the class under the configured lifecycle.</p><p><strong>6. What is the difference between </strong><strong>assertEquals() and </strong><strong>assertSame()?</strong></p><p>assertEquals() checks equality, while assertSame() checks whether both references point to the same object.</p><p><strong>7. How do you test exceptions in JUnit 5?</strong></p><p>Use assertThrows() to verify that the expected exception is thrown.</p><p><strong>8. What is a parameterized test?</strong></p><p>It executes the same test logic with multiple sets of input data.</p><p><strong>9. What is TDD?</strong></p><p>Test-driven development follows the Red–Green–Refactor cycle: write a failing test, implement the behavior, and then improve the code while keeping tests passing.</p><p><strong>10. What is Mockito?</strong></p><p>Mockito is a mocking framework used to create test doubles, define dependency behavior, and verify interactions.</p><p><strong>11. What is the difference between a unit test and an integration test?</strong></p><p>A unit test focuses on an isolated unit, while an integration test checks interactions between components.</p><p><strong>12. What is </strong><strong>@SpringBootTest?</strong></p><p>It loads a Spring application context for testing application configuration and integrated components.</p><p><strong>13. What is the purpose of Maven Surefire?</strong></p><p>It executes tests during Maven’s test phase.</p><p><strong>14. What is </strong><strong>@TestInstance?</strong></p><p>It controls whether JUnit creates a new test-class instance for each test method or shares one instance across methods.</p><p><strong>15. Why should unit tests be independent?</strong></p><p>Independent tests are more reliable because their results do not depend on execution order or state left behind by other tests.</p><h3>Conclusion</h3><p>JUnit is an essential tool in Java development because it helps us verify application behavior automatically and detect regressions early.</p><p>We started with software testing and unit testing, created a Maven project, wrote our first test, explored assertions and lifecycle annotations, and then moved into parameterized tests, Mockito, Spring Boot testing, build integration, and best practices.</p><p>The key lesson is that testing is not just about checking whether code runs. It is about verifying whether the code behaves correctly under expected, unexpected, and boundary conditions.</p><p>Start with small tests for simple Java methods. Gradually introduce mocks, integration tests, and advanced JUnit features as your applications become more complex.</p><p><strong>Write code with confidence, test it with care, and let every test make your application a little more reliable.</strong> ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=402483bfc4c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maven vs Gradle in Java: A Beginner-to-Advanced Guide ]]></title>
            <link>https://medium.com/@aishureddy/maven-vs-gradle-in-java-a-beginner-to-advanced-guide-9ded7ab55bd5?source=rss-04ef0daaee11------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ded7ab55bd5</guid>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Aishu Reddy]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 09:18:07 GMT</pubDate>
            <atom:updated>2026-10-15T09:18:07.968Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how a Java project downloads external libraries, compiles your code, runs tests, and generates a JAR file without you doing everything manually?</p><p>Imagine building a Spring Boot application. You need Spring Web to create REST APIs, Spring Data JPA to interact with a database, and perhaps JUnit to test your code.</p><p>Installing and managing every library manually would quickly become a nightmare!</p><p>This is where <strong>Maven and Gradle</strong> come into the picture.</p><p>Both tools help us manage dependencies, build applications, execute tests, and package our code. But they approach these tasks differently.</p><p>Let’s understand everything from the basics to advanced concepts, with practical examples.</p><h3>1. What Is a Build Tool?</h3><p>Before learning Maven and Gradle, we need to understand what a build tool actually does.</p><p>Suppose you write a simple Java program:</p><pre>public class HelloWorld {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello, World!&quot;);<br>    }<br>}</pre><p>To run it manually, you would compile the source code using javac and execute the compiled class using java.</p><p>But real-world applications contain hundreds of Java classes, external libraries, test cases, configuration files, and other resources.</p><p>Managing all these steps manually becomes difficult.</p><p>A <strong>build tool automates the process of turning source code into a usable application.</strong></p><p>A build tool can help us:</p><ul><li>Download and manage external libraries.</li><li>Compile Java source code.</li><li>Run unit and integration tests.</li><li>Package applications into JAR or WAR files.</li><li>Execute custom build tasks.</li><li>Support continuous integration and deployment pipelines.</li></ul><p>Think of a build tool as your project’s personal assistant. You tell it what needs to be done, and it handles the repetitive work.</p><p>Two popular build tools in the Java ecosystem are <strong>Apache Maven and Gradle</strong>.</p><h3>2. What Is Maven?</h3><p>Maven is an open-source<strong> build automation</strong> and <strong>dependency management</strong> tool widely used in Java projects.</p><p>Maven follows a convention-based approach. It provides a standard project structure and a predefined build lifecycle, so developers don’t have to configure every step from scratch.</p><p>Maven primarily uses an XML file called pom.xml to describe the project.</p><h3>Why do we need Maven?</h3><p>Imagine that your application uses Spring Web.</p><p>Without a dependency management tool, you might have to download the required JAR file manually. You would also need to identify and download its dependent libraries.</p><p>If one library requires another library, the process becomes even more complicated.</p><p>Maven solves this problem by downloading the declared dependency and resolving its required transitive dependencies automatically.</p><p>For example, instead of downloading several JAR files manually, you can declare Spring Web in your pom.xml.</p><p>POM stands for Project Object Model.</p><p>Maven takes care of resolving the dependencies from the configured repositories.</p><h3>How does Maven work?</h3><p>At a high level, Maven follows this process:</p><ol><li>You define the project configuration in pom.xml.</li><li>You declare the dependencies and plugins required by your application.</li><li>Maven reads the configuration.</li><li>It resolves dependencies from repositories.</li><li>It executes the requested build lifecycle phases.</li><li>It generates the required output, such as compiled classes or a JAR file.</li></ol><p>Maven uses a Project Object Model, or POM, to describe the project and its build configuration.</p><h3>3. Understanding pom.xml</h3><p>The pom.xml file is the heart of a Maven project.</p><p>Let’s create a simple example.</p><pre>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;&gt;</pre><pre>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;</pre><pre>    &lt;groupId&gt;com.example&lt;/groupId&gt;<br>    &lt;artifactId&gt;my-application&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;</pre><pre>    &lt;properties&gt;<br>        &lt;maven.compiler.source&gt;11&lt;/maven.compiler.source&gt;<br>        &lt;maven.compiler.target&gt;11&lt;/maven.compiler.target&gt;<br>        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;<br>    &lt;/properties&gt;</pre><pre>&lt;/project&gt;</pre><p>Let’s understand the important elements.</p><p><strong>modelVersion</strong></p><p>Specifies the POM model version used by Maven. The commonly used value is 4.0.0.</p><p><strong>groupId</strong></p><p>Identifies the organization or group responsible for the project.</p><p>Example: com.example</p><p><strong>artifactId</strong></p><p>Identifies the specific project or artifact.</p><p>Example: my-application</p><p><strong>version</strong></p><p>Specifies the project’s version.</p><p>Example: 1.0.0</p><p>Together, these coordinates identify a published artifact using the pattern:</p><p>groupId:artifactId:version</p><p>For example:</p><p>com.example:my-application:1.0.0</p><p>This is useful when other projects need to reference your application as a dependency.</p><p><strong>properties</strong></p><p>Stores <strong>reusable configuration values</strong>, such as Java compiler settings and version numbers.</p><ul><li>Dependency: A library your application needs to run or compile.</li><li>Plugin: A tool Maven uses to perform build-related tasks.</li></ul><blockquote>&lt;build&gt;<br> &lt;plugins&gt;<br> &lt;plugin&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br> &lt;/plugin&gt;<br> &lt;/plugins&gt;<br>&lt;/build&gt;</blockquote><p>You can learn more in the <a href="https://maven.apache.org/guides/introduction/introduction-to-the-pom.html">official Maven POM documentation</a>.</p><h3>4. Maven Dependencies: How Does Maven Download Libraries?</h3><p>A dependency is an external library that your project needs.</p><p>For example, a Spring Boot application might need Spring Web to build REST APIs.</p><p>Instead of downloading the library manually, we declare it inside the dependencies section.</p><pre>&lt;dependencies&gt;</pre><pre>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-web&lt;/artifactId&gt;<br>        &lt;version&gt;6.1.0&lt;/version&gt;<br>    &lt;/dependency&gt;</pre><pre>&lt;/dependencies&gt;</pre><p>Here:</p><ul><li>groupId identifies the <strong>library&#39;s group</strong>.</li><li>artifactId identifies the <strong>library</strong>.</li><li>version identifies the version we want.</li></ul><p>When Maven builds the project, it resolves this dependency and downloads the required artifacts if they are not already available locally.</p><p><em>Note: This is a standalone Spring Web dependency example. In a Spring Boot project, it is usually preferable to use the Spring Boot parent or dependency management to keep related library versions compatible.</em></p><h3>What is a repository?</h3><p>A repository is a location where build artifacts, such as JAR files and their metadata, are stored.</p><p>Maven commonly works with three repository types.</p><p><strong>1. Local repository</strong></p><p>This is a cache on your machine and it is hidden, typically located at:</p><pre>~/.m2/repository</pre><p>Maven stores downloaded dependencies here so they can be reused by other local projects.</p><p><strong>2. Remote repository</strong></p><p>A repository hosted on a remote server. Maven Central is a well-known public repository.</p><p><strong>3. Private or internal repository</strong></p><p>Organizations may maintain repositories for internal libraries or approved external dependencies.</p><p>For example, a company might publish its own shared authentication library to an internal repository so that multiple applications can use it.</p><h3>What are transitive dependencies?</h3><p>Suppose your application depends on Library A, and Library A requires Library B.</p><p>Your application may need both libraries even if you never directly declare Library B.</p><p>This is called a <strong>transitive dependency</strong>.</p><p>Maven resolves transitive dependencies automatically, subject to dependency exclusions, version conflict rules, and other configuration.</p><p>This saves developers from manually tracking every library required by their dependencies.</p><h3>5. Maven Build Lifecycle</h3><p>One of Maven’s most important concepts is its build lifecycle.</p><p>A lifecycle is a sequence of predefined phases used to perform tasks such as compiling, testing, and packaging an application.</p><p>Maven has three built-in lifecycles:</p><ul><li>clean — removes files generated by previous builds or it removes the target file.</li><li>default — handles the <strong>main build</strong> and <strong>deployment process</strong>.</li><li>site — generates project documentation and reports.</li></ul><p>Let’s focus on the default lifecycle.</p><p>validateChecks whether the project configuration and structure is valid.</p><p>compileCompiles the main source code.</p><p>testRuns unit tests.</p><p>packagePackages the compiled code into a JAR or another configured format.</p><p>verifyPerforms additional checks to verify the package.</p><p>installInstalls the artifact into the local Maven repository.which mean it puts the jar files and other meta data into the repo</p><p>deployPublishes the artifact to a configured remote repository.</p><p>These phases run in order up to the requested phase.</p><p>For example, when you execute:</p><pre>mvn package</pre><p>Maven runs the preceding phases of the default lifecycle, including compilation and testing, before packaging the application.</p><p>When you execute:</p><pre>mvn install</pre><p>Maven runs the necessary preceding phases and installs the resulting artifact into the local repository.</p><h3>What is the difference between a lifecycle, phase, and goal?</h3><p>These terms are related but not identical.</p><ul><li><strong>Lifecycle:</strong> A predefined sequence of build phases.</li><li><strong>Phase:</strong> A stage in that sequence, such as compile or package.</li><li><strong>Goal:</strong> A specific operation performed by a Maven plugin.</li></ul><p>For example, the Maven Compiler Plugin provides goals that compile Java source code. Maven binds appropriate plugin goals to lifecycle phases.</p><p>Remember this distinction because it is a common interview question.</p><h3>6. Important Maven Commands</h3><p>Here are some commands you will use frequently.</p><pre>mvn clean</pre><p>Removes generated build output, typically the target directory.</p><pre>mvn compile</pre><p>Compiles the main source code.</p><pre>mvn test</pre><p>Compiles and runs the test suite associated with the test phase.</p><pre>mvn package</pre><p>Builds the project and packages the application, commonly as a JAR.</p><pre>mvn install</pre><p>Builds the project and places its artifact in the local Maven repository.</p><pre>mvn clean install</pre><p>Cleans previous build output and performs a fresh build through the install phase.</p><pre>mvn clean package -DskipTests</pre><p>Cleans and packages the project while skipping test execution. Be aware that this can still compile test sources, and skipping tests is not a substitute for a successful test run.</p><pre>mvn dependency:tree</pre><p>Displays the dependency hierarchy, including transitive dependencies.</p><pre>mvn help:effective-pom</pre><p>Displays the effective POM after Maven applies inherited configuration and other applicable settings.</p><p>effective pom is the parent pom, this is the file that is checked first during the build</p><h3>7. What Is Gradle?</h3><p>Gradle is another build automation tool used for Java, Kotlin, Android, and other types of projects.</p><p>Like Maven, Gradle can download dependencies, compile source code, run tests, and package applications.</p><p>However, Gradle uses a different approach to configuring builds.</p><p>Gradle build scripts can be written using:</p><ul><li><strong>Groovy DSL:</strong> Usually build.gradle</li><li><strong>Kotlin DSL:</strong> Usually build.gradle.kts</li></ul><p>DSL stands for Domain-Specific Language. It means a language or syntax designed to express configuration for a particular domain.</p><p>Gradle scripts allow developers to define dependencies, plugins, tasks, and custom build logic.</p><h3>How does Gradle work?</h3><p>At a high level, Gradle follows three major build phases:</p><ol><li><strong>Initialization:</strong> Determines which projects participate in the build.</li><li><strong>Configuration:</strong> Evaluates build scripts and constructs the task graph.</li><li><strong>Execution:</strong> Runs the selected tasks in the required order.</li></ol><p>Unlike Maven’s predefined sequence of lifecycle phases, Gradle organizes its build around tasks and their dependencies.</p><p>You can find more details in the <a href="https://docs.gradle.org/current/userguide/build_lifecycle.html">official Gradle build lifecycle documentation</a>.</p><h3>8. Understanding a Gradle Build File</h3><p>Let’s write a simple Gradle build using Groovy DSL.</p><p><strong>build.gradle</strong></p><pre>plugins {<br>    id &#39;java&#39;<br>}</pre><pre>group = &#39;com.example&#39;<br>version = &#39;1.0.0&#39;</pre><pre>repositories {<br>    mavenCentral()<br>}</pre><pre>dependencies {<br>    implementation &#39;org.springframework:spring-web:6.1.0&#39;<br>    testImplementation &#39;junit:junit:4.13.2&#39;<br>}</pre><p>Let’s understand the important parts.</p><p><strong>plugins</strong></p><p>Declares plugins that add capabilities to the build.</p><p>For example, the Java plugin provides tasks for compiling Java code, running tests, and packaging classes.</p><p><strong>group and </strong><strong>version</strong></p><p>Define the project’s group and version information.</p><p><strong>repositories</strong></p><p>Specifies where Gradle should look for dependencies.</p><p>Here, mavenCentral() adds Maven Central as a repository.</p><p>Notice something interesting: <strong>Gradle can use Maven repositories.</strong> Maven and Gradle are different build tools, but they can use compatible artifact repositories and published dependency metadata.</p><p><strong>dependencies</strong></p><p>Declares the libraries needed by the project and the configurations under which they are used.</p><h3>What if we use Kotlin DSL?</h3><p>The equivalent configuration can be written in build.gradle.kts.</p><pre>plugins {<br>    java<br>}</pre><pre>group = &quot;com.example&quot;<br>version = &quot;1.0.0&quot;</pre><pre>repositories {<br>    mavenCentral()<br>}</pre><pre>dependencies {<br>    implementation(&quot;org.springframework:spring-web:6.1.0&quot;)<br>    testImplementation(&quot;junit:junit:4.13.2&quot;)<br>}</pre><p>Both examples configure a Gradle Java project. They use different languages and syntax, but the underlying purpose is the same.</p><h3>9. Understanding Gradle Dependencies</h3><p>Gradle uses dependency configurations to describe how a dependency should be used.</p><p>Here are some commonly used configurations in Java projects.</p><p>Gradle is based on developing domain-specific language projects.Maven is based on developing pure Java language-based software.</p><p>For example:</p><pre>dependencies {<br>    implementation &#39;org.springframework:spring-web:6.1.0&#39;</pre><pre>    testImplementation &#39;org.junit.jupiter:junit-jupiter:5.10.0&#39;<br>}</pre><p>The first dependency is part of the application’s implementation. The second is intended for testing.</p><p>The exact configurations available depend on the plugins applied to the project.</p><h3>What is the difference between api and implementation?</h3><p>This distinction matters particularly when building reusable libraries.</p><p>Imagine that Library A exposes a class from Library B in its public method signature.</p><p>If consumers of Library A must also see Library B on their compile classpath, an api dependency may be appropriate.</p><p>If Library B is only an internal implementation detail of Library A, implementation is generally more suitable.</p><p>Using implementation where possible helps avoid exposing unnecessary dependencies to consumers and can improve build efficiency.</p><h3>10. Gradle Tasks and the Build Lifecycle</h3><p>A task represents a unit of work in Gradle.</p><p>Examples include compiling Java code, running tests, generating documentation, and creating a JAR file.</p><p>Gradle builds a graph of task dependencies and executes the selected tasks in the required order.</p><p>For example, the Java plugin provides familiar tasks such as:</p><pre>./gradlew clean</pre><p>Cleans generated output.</p><pre>./gradlew classes</pre><p>Builds the main classes and processes resources.</p><pre>./gradlew test</pre><p>Runs tests.</p><pre>./gradlew jar</pre><p>Creates a JAR archive.</p><pre>./gradlew build</pre><p>Runs the tasks associated with building the project, including compilation, tests, and packaging where configured.</p><pre>./gradlew tasks</pre><p>Lists available tasks.</p><pre>./gradlew dependencies</pre><p>Displays dependency information for the selected project and configuration context.</p><p>The ./gradlew command uses the project&#39;s Gradle Wrapper, which we will discuss shortly.</p><h3>Can we create our own Gradle task?</h3><p>Yes! This is one of Gradle’s useful features.</p><p>For example, in a Groovy-based build.gradle file:</p><pre>tasks.register(&#39;hello&#39;) {<br>    doLast {<br>        println &#39;Hello from Gradle!&#39;<br>    }<br>}</pre><p>Run it with:</p><pre>./gradlew hello</pre><p>The task prints:</p><pre>Hello from Gradle!</pre><p>We can create more advanced tasks for generating files, checking project rules, preparing deployment artifacts, or automating other project-specific operations.</p><h3>11. Maven vs Gradle: The Main Differences</h3><p>Now that we understand both tools, let’s compare them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*2c2EASxwInml8RUlKGx0RA.png" /></figure><h3>Which one is faster?</h3><p>Gradle has several features designed to improve build performance, including incremental execution, build caching, and parallel execution.</p><p>However, that does not mean every Gradle build is automatically faster than every Maven build. Performance depends on the project, configuration, plugins, cache state, and build environment.</p><h3>Which one is easier?</h3><p>Maven is often easier for beginners to understand because its standard project structure and lifecycle are predictable.</p><p>Gradle provides greater flexibility for defining build logic, but that flexibility can introduce additional complexity.</p><p>Neither tool is universally better. The right choice depends on the project and the team’s requirements.</p><h3>12. What Is a Wrapper? Maven Wrapper vs Gradle Wrapper</h3><p>Imagine that your project works with one version of Maven or Gradle, but another developer has a different version installed.</p><p>Different tool versions can cause inconsistent build results.</p><p>A <strong>wrapper</strong> helps solve this problem by allowing a project to specify the build-tool version it expects.</p><h3>Maven Wrapper</h3><p>A Maven project may contain:</p><pre>mvnw<br>mvnw.cmd<br>.mvn/<br>pom.xml</pre><p>You can run:</p><pre>./mvnw clean install</pre><h3>Gradle Wrapper</h3><p>A Gradle project may contain:</p><pre>gradlew<br>gradlew.bat<br>gradle/<br>build.gradle</pre><p>You can run:</p><pre>./gradlew build</pre><p>The wrapper uses the configured tool version and can download it if it is not already available.</p><p>The important benefit is consistency: developers and CI systems can use the project’s configured build-tool version instead of relying on whatever happens to be installed globally.</p><h3>13. Where Do Maven and Gradle Store Build Output?</h3><p>When a Java project is built, the tools generate output such as compiled classes, test reports, and packaged artifacts.</p><p>Maven typically stores generated build output in:</p><pre>target/</pre><p>Gradle typically stores generated build output in:</p><pre>build/</pre><p>For example, after a successful Maven build, you might find:</p><pre>target/<br>├── classes/<br>├── test-classes/<br>└── my-application-1.0.0.jar</pre><p>A Gradle build may produce:</p><pre>build/<br>├── classes/<br>├── reports/<br>├── test-results/<br>└── libs/<br>    └── my-application-1.0.0.jar</pre><p>These are illustrative structures; the exact files depend on the plugins and configuration used by the project.</p><p>The important point is that the source code and generated build output are separate.</p><p>If you clean the project, generated output can be removed and recreated during the next build.</p><h3>14. How Do Maven and Gradle Work With Spring Boot?</h3><p>If you work with Spring Boot, you will commonly encounter both Maven and Gradle.</p><p>Spring Boot provides build plugins that help package and run applications.</p><h3>Maven with Spring Boot</h3><p>A typical Spring Boot Maven project uses the Spring Boot parent or dependency management along with the Spring Boot Maven Plugin.</p><p>Example:</p><pre>&lt;parent&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>    &lt;version&gt;2.7.18&lt;/version&gt;<br>    &lt;relativePath/&gt;<br>&lt;/parent&gt;</pre><pre>&lt;groupId&gt;com.example&lt;/groupId&gt;<br>&lt;artifactId&gt;demo&lt;/artifactId&gt;<br>&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;</pre><pre>&lt;properties&gt;<br>    &lt;java.version&gt;11&lt;/java.version&gt;<br>&lt;/properties&gt;</pre><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>The parent manages compatible dependency versions and provides useful defaults. A separate plugin declaration is commonly used to create an executable Spring Boot JAR.</p><p>For a project configured with the Spring Boot Maven Plugin, you can run:</p><pre>./mvnw spring-boot:run</pre><p>To package the application:</p><pre>./mvnw clean package</pre><h3>Gradle with Spring Boot</h3><p>A typical Gradle configuration uses the Java and Spring Boot plugins.</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;2.7.18&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.0.15.RELEASE&#39;<br>}</pre><pre>group = &#39;com.example&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;</pre><pre>java {<br>    sourceCompatibility = &#39;11&#39;<br>}</pre><pre>repositories {<br>    mavenCentral()<br>}</pre><pre>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>}</pre><p>You can run the application using:</p><pre>./gradlew bootRun</pre><p>Or package it using:</p><pre>./gradlew clean build</pre><p>These examples use Spring Boot 2.7.x to demonstrate Java 11 compatibility. When creating a new application, select a supported Spring Boot version that matches your Java version and project requirements.</p><h3>15. Advanced Concepts You Should Know</h3><h3>A. Incremental builds</h3><p>An incremental build avoids repeating work when relevant inputs have not changed.</p><p>For example, if you modify one source file, a properly configured build may not need to redo every unrelated task.</p><p>Gradle supports incremental task execution, but the benefits depend on task configuration and whether tasks correctly declare their inputs and outputs.</p><h3>B. Build caching</h3><p>Build caching allows eligible task outputs to be reused when the same task inputs are encountered again.</p><p>This can reduce build time, particularly in larger projects and CI environments.</p><p>Gradle supports local and remote build caches. Remote caching needs to be configured and used appropriately.</p><h3>C. Multi-module projects</h3><p>Large applications are often divided into multiple modules.</p><p>For example:</p><pre>finzy-application/<br>├── user-service/<br>├── loan-service/<br>├── notification-service/<br>└── common-library/</pre><p>Each module can have its own dependencies and responsibilities while participating in a larger build.</p><p>Maven supports multi-module projects through parent POMs and module declarations.</p><p>Gradle supports multi-project builds through its settings and project configuration.</p><p>This approach helps teams organize code, reuse common functionality, and manage larger applications.</p><h3>D. Plugins</h3><p>Plugins extend the capabilities of a build tool.</p><p>For example, a Java project might use plugins for compilation, code quality checks, test reporting, packaging, or publishing.</p><p>Maven plugins expose goals that can be connected to lifecycle phases.</p><p>Gradle plugins add tasks, configurations, and other build capabilities.</p><h3>E. Continuous integration</h3><p>Build tools are important in CI/CD pipelines.</p><p>Whenever code is pushed or a pull request is created, a CI system can execute the project’s build command.</p><p>For example:</p><pre>./mvnw clean verify</pre><p>Or:</p><pre>./gradlew build</pre><p>These commands help automate compilation, testing, and verification before code is merged or deployed.</p><p>A successful build does not guarantee that an application is free from bugs, but it provides an important automated quality check.</p><h3>16. Common Mistakes Beginners Make</h3><p><strong>Mistake 1: Thinking Maven and Gradle are programming languages.</strong></p><p>They are build automation tools. Gradle scripts use Groovy or Kotlin DSL, but Gradle itself is the build system.</p><p><strong>Mistake 2: Thinking Maven Central belongs only to Maven.</strong></p><p>Maven Central is an artifact repository. Gradle can also download dependencies from it.</p><p><strong>Mistake 3: Confusing dependencies with plugins.</strong></p><p>Dependencies provide libraries that your application uses. Build plugins add build capabilities and tasks.</p><p><strong>Mistake 4: Assuming </strong><strong>package and </strong><strong>install mean the same thing in Maven.</strong></p><p>package creates the distributable artifact. install also places that artifact in the local Maven repository after running the required earlier phases.</p><p><strong>Mistake 5: Assuming </strong><strong>build and </strong><strong>bootRun do the same thing in Gradle.</strong></p><p>build performs the tasks needed to build the project. bootRun, when provided by the Spring Boot plugin, runs the application.</p><p><strong>Mistake 6: Ignoring the wrapper.</strong></p><p>Using the project’s wrapper helps developers and CI systems use a consistent build-tool version.</p><h3>17. Interview Questions and Answers</h3><p><strong>Q1. What is Maven?</strong></p><p>Maven is a Java build automation and dependency management tool that uses a POM file to describe project configuration.</p><p><strong>Q2. What is Gradle?</strong></p><p>Gradle is a build automation tool that uses build scripts, tasks, and a task dependency graph to build and manage projects.</p><p><strong>Q3. What is the difference between Maven and Gradle?</strong></p><p>Maven primarily uses XML and predefined build lifecycle phases, whereas Gradle uses Groovy or Kotlin DSL and a task-based build model.</p><p><strong>Q4. What is </strong><strong>pom.xml?</strong></p><p>It is the Project Object Model file that defines Maven project information, dependencies, plugins, and other build configuration.</p><p><strong>Q5. What is a transitive dependency?</strong></p><p>A transitive dependency is a library required by one of the dependencies declared by your project.</p><p><strong>Q6. What is the difference between </strong><strong>mvn package and </strong><strong>mvn install?</strong></p><p>package creates the distributable artifact. install runs the required preceding phases and stores the resulting artifact in the local Maven repository.</p><p><strong>Q7. What is the difference between </strong><strong>implementation and </strong><strong>api in Gradle?</strong></p><p>implementation is intended for dependencies needed by a module&#39;s implementation. api exposes a dependency to consumers of a library&#39;s public API.</p><p><strong>Q8. Why do we use Maven or Gradle wrappers?</strong></p><p>They help ensure that developers and CI environments use the build-tool version configured for the project.</p><p><strong>Q9. Can Gradle use Maven repositories?</strong></p><p>Yes. Gradle can resolve dependencies from Maven-compatible repositories, including Maven Central.</p><p><strong>Q10. Is Gradle always faster than Maven?</strong></p><p>No. Gradle has performance features such as incremental execution and caching, but actual performance depends on the project and build configuration.</p><p><strong>Q11. Can a Spring Boot project use either Maven or Gradle?</strong></p><p>Yes. Spring Boot provides plugins and dependency-management support for both build tools.</p><p><strong>Q12. What happens when a build fails?</strong></p><p>The build tool reports the failed task or phase and relevant error information. Developers should inspect the first meaningful failure, identify the underlying cause, and rerun the appropriate build or tests after fixing it.</p><h3>18. Final Thoughts</h3><p>Maven and Gradle solve the same fundamental problem: they automate the work required to build, test, and package applications.</p><p>Maven is an excellent starting point if you want a conventional and predictable build process. Gradle is especially useful when you need flexible build logic and features that can optimize complex builds.</p><p>The most important thing is not to memorize every command. Instead, understand what happens when you run a build:</p><ul><li>Where do dependencies come from?</li><li>How is source code compiled?</li><li>When do tests execute?</li><li>How is the final artifact generated?</li><li>How does the build tool know which tasks to run?</li></ul><p>Once you understand these concepts, working with Maven or Gradle in a real Java or Spring Boot project becomes much easier.</p><p><strong>Keep learning, keep building, and keep exploring — one concept at a time! ✨</strong></p><h3>Official references</h3><ul><li><a href="https://maven.apache.org/guides/introduction/introduction-to-the-pom.html">Apache Maven — Introduction to the POM</a></li><li><a href="https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html">Apache Maven — Build Lifecycle</a></li><li><a href="https://docs.gradle.org/current/userguide/build_lifecycle.html">Gradle — Build Lifecycle</a></li><li><a href="https://docs.gradle.org/current/userguide/writing_build_scripts_intermediate.html">Gradle — Writing Build Scripts</a></li><li><a href="https://docs.gradle.org/current/userguide/migrating_from_maven.html">Gradle — Migrating Builds From Maven</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ded7ab55bd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Collections Framework: From Beginner to Advanced ☕]]></title>
            <link>https://medium.com/@aishureddy/java-collections-framework-from-beginner-to-advanced-7e2579d16e35?source=rss-04ef0daaee11------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e2579d16e35</guid>
            <category><![CDATA[java8-streams]]></category>
            <category><![CDATA[collection]]></category>
            <dc:creator><![CDATA[Aishu Reddy]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 06:28:17 GMT</pubDate>
            <atom:updated>2026-10-13T06:28:17.753Z</atom:updated>
            <content:encoded><![CDATA[<h3>A complete guide to Lists, Sets, Maps, Queues, internal working, sorting, and more</h3><p>When we start learning Java, we usually begin with variables, arrays, classes, and objects. But as we start building real applications, we encounter a common problem: <strong>How do we store and manage a large amount of data efficiently?</strong></p><p>Imagine we are developing a banking application. We need to store customer details, maintain transaction histories, prevent duplicate transaction IDs, map account IDs to account details, and process transactions in a particular order.</p><p>We could use arrays for some of these tasks. But arrays have limitations, and managing all this data manually would make our code complicated.</p><p>Java provides a solution called the <strong>Java Collections Framework</strong>.</p><p>In this blog, we will start with the basics and gradually move towards advanced concepts, including how collections work internally and how to choose the right collection for real-world applications.</p><h3>1. What is a Collection in Java?</h3><p>A collection is an object that groups multiple objects into a single unit.</p><p>For example, instead of creating separate variables for every student:</p><pre>String student1 = &quot;Rahul&quot;;<br>String student2 = &quot;Priya&quot;;<br>String student3 = &quot;Aman&quot;;</pre><p>We can store them together:</p><pre>ArrayList&lt;String&gt; students = new ArrayList&lt;&gt;();</pre><pre>students.add(&quot;Rahul&quot;);<br>students.add(&quot;Priya&quot;);<br>students.add(&quot;Aman&quot;);</pre><pre>System.out.println(students);</pre><p>Output:</p><pre>[Rahul, Priya, Aman]</pre><p>Now we can add, remove, search, and process students using a single collection.</p><h3>Why do we need collections?</h3><p>Arrays are useful, but they have some limitations:</p><ul><li>Their length is fixed after creation.</li><li>Inserting and removing elements can require manual shifting.</li><li>They do not directly provide higher-level operations such as removing duplicates or maintaining sorted data.</li><li>We may need to write additional code for searching, sorting, and managing elements.</li></ul><p>Collections provide reusable data structures and algorithms that make these operations easier.</p><p><strong>Important:</strong> Collections generally store objects, not primitive values directly. Java’s wrapper classes, such as Integer, Double, and Character, allow primitive values to be represented as objects.</p><pre>ArrayList&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();</pre><pre>numbers.add(10); // int is automatically boxed into Integer<br>numbers.add(20);</pre><p>This automatic conversion is called <em>autoboxing</em>.</p><h3>2. What is the Java Collections Framework?</h3><p>The Java Collections Framework is a unified architecture for storing, organizing, accessing, and manipulating groups of objects.</p><p>It consists of three major parts:</p><ol><li><strong>Interfaces:</strong> Define what operations a data structure supports since we cannot directly create the object of the interface we can use a class that implements the interface.</li><li><strong>Implementations:</strong> Provide the actual data structures.</li><li><strong>Algorithms:</strong> Provide reusable operations such as sorting and searching.</li></ol><p>For example:</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><p>Here:</p><ul><li>List is an interface.</li><li>ArrayList is an implementation of that interface.</li><li>Methods such as Collections.sort() provide reusable algorithms.</li></ul><p>Why is this useful?</p><p>We can replace ArrayList with another suitable List implementation without changing all the code that uses the List interface.</p><p>This is an example of programming to an interface rather than depending unnecessarily on a particular implementation.</p><h3>3. Understanding the Collections Framework hierarchy</h3><p>Before learning the individual collection types, we need to understand their hierarchy.</p><pre>Iterable<br>                       |<br>                   Collection<br>                 /     |      \<br>               List   Set    Queue<br>                |      |       |<br>           ArrayList   |      Deque<br>           LinkedList  |        |<br>           Vector      |    ArrayDeque<br>              |        |<br>            Stack      |<br>                    HashSet<br>                    LinkedHashSet<br>                    TreeSet</pre><p>There is another important hierarchy for key-value storage:</p><pre>Map<br>                       |<br>          ---------------------------<br>          |             |           |<br>       HashMap      TreeMap     Hashtable<br>          |<br>      LinkedHashMap</pre><pre>Other important implementation:<br>ConcurrentHashMap</pre><p>This is a simplified view, not the complete inheritance tree.</p><p><strong>One important interview point:</strong> Map is part of the Collections Framework, but it does not extend the Collection interface. A List, Set, and Queue are collections; a Map stores key-value mappings.</p><h3>4. The Collection interface</h3><p>The Collection interface is the root interface for the main collection types.</p><p>It defines common operations that many collections support.</p><p>MethodPurposeadd()Adds an elementaddAll()Adds elements from another collectionremove()Removes an elementcontains()Checks whether an element existssize()Returns the number of elementsisEmpty()Checks whether the collection is emptyclear()Removes all elementsiterator()Returns an iteratortoArray()Converts the collection into an array</p><p>Example:</p><pre>Collection&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><pre>names.add(&quot;Rahul&quot;);<br>names.add(&quot;Priya&quot;);<br>names.add(&quot;Aman&quot;);</pre><pre>System.out.println(names.size());       // 3<br>System.out.println(names.contains(&quot;Priya&quot;)); // true</pre><pre>names.remove(&quot;Rahul&quot;);</pre><pre>System.out.println(names);</pre><p>Output:</p><pre>3<br>true<br>[Priya, Aman]</pre><p>The exact behavior of some operations depends on the implementation. For example, some collections permit duplicates, while others do not.</p><p>Now let’s explore the most commonly used collection types.</p><h3>Part 1: List</h3><h3>5. What is a List?</h3><p>A List is an ordered collection that allows elements to be accessed using their index.</p><p>A List generally allows duplicate elements.</p><p>For example:</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><pre>names.add(&quot;Rahul&quot;);<br>names.add(&quot;Priya&quot;);<br>names.add(&quot;Rahul&quot;);</pre><pre>System.out.println(names);</pre><p>Output:</p><pre>[Rahul, Priya, Rahul]</pre><p>The duplicate &quot;Rahul&quot; is allowed.</p><p>A List also maintains positional order. The first element is at index 0, the second at index 1, and so on.</p><pre>System.out.println(names.get(0)); // Rahul<br>System.out.println(names.get(1)); // Priya</pre><h3>Important List methods</h3><pre>names.add(&quot;Aman&quot;);<br>names.add(1, &quot;Sneha&quot;);  // Insert at index 1</pre><pre>names.set(0, &quot;Arjun&quot;);  // Replace element at index 0</pre><pre>names.remove(2);        // Remove element at index 2</pre><pre>System.out.println(names.get(0));</pre><p>Be careful when using remove() with an ArrayList&lt;Integer&gt;:</p><pre>List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();</pre><pre>numbers.add(10);<br>numbers.add(20);<br>numbers.add(30);</pre><pre>numbers.remove(1); // Removes the element at index 1: 20<br>numbers.remove(Integer.valueOf(30)); // Removes the value 30</pre><p>This distinction exists because List provides both remove(int index) and remove(Object value).</p><h3>6. ArrayList</h3><p>ArrayList is one of the most commonly used collection implementations in Java.</p><p>Internally, it uses a resizable array.</p><p>Unlike a regular array, an ArrayList can grow as elements are added.</p><pre>ArrayList&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();</pre><pre>numbers.add(10);<br>numbers.add(20);<br>numbers.add(30);<br>numbers.add(40);</pre><pre>System.out.println(numbers);</pre><h3>How does ArrayList work internally?</h3><p>Imagine the internal array has a capacity of four elements.</p><pre>Index:      0    1    2    3<br>           -------------------<br>Values:    | 10 | 20 | 30 | 40 |<br>           -------------------</pre><p>When we add another element and the backing array has no free capacity, Java creates a larger array and copies the existing elements into it.</p><p>The exact growth policy is an implementation detail, so we should not rely on a particular capacity increase as part of application logic.</p><h3>Time complexity of ArrayList</h3><p>OperationTypical complexityAccess by indexO(1)Add at the endAmortized O(1)Insert in the middleO(n)Remove from the middleO(n)Search by valueO(n)</p><p>Why is insertion in the middle O(n)?</p><p>Because elements after the insertion position may need to be shifted to make space.</p><h3>When should we use ArrayList?</h3><p>Use ArrayList when:</p><ul><li>You frequently access elements by index.</li><li>You need a resizable sequence.</li><li>You frequently add elements at the end.</li><li>You do not need efficient insertion and removal at arbitrary positions.</li></ul><p>For most ordinary list use cases, ArrayList is a good default choice.</p><h3>7. LinkedList</h3><p>LinkedList uses a doubly linked list internally.</p><p>Each node stores an element and references to the previous and next nodes.</p><p>Conceptually:</p><pre>null &lt;- [10] &lt;-&gt; [20] &lt;-&gt; [30] -&gt; null</pre><p>Each node is connected to its neighbors.</p><pre>LinkedList&lt;Integer&gt; numbers = new LinkedList&lt;&gt;();</pre><pre>numbers.add(10);<br>numbers.add(20);<br>numbers.add(30);</pre><pre>numbers.addFirst(5);<br>numbers.addLast(40);</pre><pre>System.out.println(numbers);</pre><p>Output:</p><pre>[5, 10, 20, 30, 40]</pre><h3>When should we use LinkedList?</h3><p>It can be useful when operations at both ends are important, but ArrayDeque is often a better choice for queue and stack behavior.</p><p>For ordinary indexed lists, ArrayList is usually the preferred starting point.</p><h3>8. Vector and Stack</h3><p>Before the modern collection implementations became common, Java provided classes such as Vector and Stack.</p><h3>Vector</h3><p>Vector is a resizable array similar to ArrayList, but its individual methods are synchronized.</p><pre>Vector&lt;Integer&gt; numbers = new Vector&lt;&gt;();</pre><pre>numbers.add(10);<br>numbers.add(20);</pre><p>It is a legacy class. Synchronizing individual methods does not automatically make a multi-step operation atomic.</p><p>For most modern applications, ArrayList is preferred when synchronization is not needed.</p><h3>Stack</h3><p>Stack extends Vector and provides last-in, first-out behavior.</p><pre>Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();</pre><pre>stack.push(10);<br>stack.push(20);<br>stack.push(30);</pre><pre>System.out.println(stack.pop());  // 30<br>System.out.println(stack.peek()); // 20</pre><p>The last element inserted is the first one removed.</p><p>For modern Java code, ArrayDeque is generally preferred for stack operations.</p><h3>Part 2: Set</h3><h3>9. What is a Set?</h3><p>A Set is a collection that does not allow duplicate elements.</p><p>Imagine a system that stores unique customer IDs. If the same ID is added twice, the Set will retain only one equal element.</p><pre>Set&lt;Integer&gt; ids = new HashSet&lt;&gt;();</pre><pre>ids.add(101);<br>ids.add(102);<br>ids.add(101);</pre><pre>System.out.println(ids);</pre><p>Output contains 101 and 102, but only one occurrence of each.</p><p>The exact iteration order of a HashSet is not guaranteed.</p><p>A Set is useful for:</p><ul><li>Removing duplicate values.</li><li>Tracking unique IDs.</li><li>Checking membership.</li><li>Performing mathematical set operations.</li></ul><h3>10. HashSet</h3><p>HashSet is backed by a hash table, implemented using a HashMap in standard OpenJDK implementations.</p><p>It uses an element’s hashCode() to help determine where to store the element and equals() to determine whether elements are equal.</p><pre>Set&lt;String&gt; languages = new HashSet&lt;&gt;();</pre><pre>languages.add(&quot;Java&quot;);<br>languages.add(&quot;Python&quot;);<br>languages.add(&quot;Java&quot;);</pre><pre>System.out.println(languages.contains(&quot;Java&quot;)); // true<br>System.out.println(languages.size());           // 2</pre><h3>How does HashSet work internally?</h3><p>When we add an element:</p><ol><li>Java obtains its <strong>hash code</strong>.</li><li>The hash helps determine a <strong>bucket</strong> in the underlying <strong>hash table</strong>.</li><li>Java checks for an equal element in the <strong>relevant bucket</strong>.</li><li>If an equal element already exists, the Set does not add a duplicate.</li><li>Otherwise, the new element is stored.</li></ol><p>Hash collisions can occur when different objects have the same hash code. A correct implementation must still distinguish unequal objects using equality checks.</p><p>Under normal hashing conditions, HashSet offers average constant-time basic operations. Poor hash distribution can affect performance.</p><h3>11. LinkedHashSet</h3><p>LinkedHashSet prevents duplicates like HashSet, but also preserves insertion order during iteration.</p><pre>Set&lt;String&gt; names = new LinkedHashSet&lt;&gt;();</pre><pre>names.add(&quot;Rahul&quot;);<br>names.add(&quot;Priya&quot;);<br>names.add(&quot;Aman&quot;);<br>names.add(&quot;Rahul&quot;);</pre><pre>System.out.println(names);</pre><p>Output:</p><pre>[Rahul, Priya, Aman]</pre><p>Use LinkedHashSet when you want unique elements while retaining the order in which they were inserted.</p><h3>12. TreeSet</h3><p>TreeSet stores unique elements in sorted order.</p><pre>Set&lt;Integer&gt; numbers = new TreeSet&lt;&gt;();</pre><pre>numbers.add(50);<br>numbers.add(10);<br>numbers.add(30);<br>numbers.add(20);</pre><pre>System.out.println(numbers);</pre><p>Output:</p><pre>[10, 20, 30, 50]</pre><p>Internally, TreeSet is backed by a TreeMap in standard OpenJDK implementations, which uses a balanced search tree.</p><p>Basic operations such as insertion, removal, and lookup typically take O(log n).</p><p><strong>Important:</strong> TreeSet normally uses natural ordering or a supplied Comparator. Its notion of equality for maintaining uniqueness is based on comparison returning zero. This should be consistent with equals() to avoid surprising behavior.</p><h3>Part 3: Map</h3><h3>13. What is a Map?</h3><p>A Map stores data in key-value pairs.</p><p>For example, imagine storing employee IDs and employee names.</p><pre>101 -&gt; Rahul<br>102 -&gt; Priya<br>103 -&gt; Aman</pre><p>Instead of searching through a list to find an employee’s name, we can retrieve the value using the employee ID.</p><pre>Map&lt;Integer, String&gt; employees = new HashMap&lt;&gt;();</pre><pre>employees.put(101, &quot;Rahul&quot;);<br>employees.put(102, &quot;Priya&quot;);<br>employees.put(103, &quot;Aman&quot;);</pre><pre>System.out.println(employees.get(102));</pre><p>Output:</p><pre>Priya</pre><p>A Map does not permit duplicate keys. If we insert a value using an existing key, the previous value is replaced.</p><pre>employees.put(101, &quot;Arjun&quot;);</pre><pre>System.out.println(employees.get(101)); // Arjun</pre><p>A Map can contain duplicate values, but each key can map to at most one value.</p><h3>14. HashMap</h3><p>HashMap is one of the most commonly used Map implementations.</p><p>It stores key-value pairs using hashing.</p><pre>Map&lt;String, Integer&gt; marks = new HashMap&lt;&gt;();</pre><pre>marks.put(&quot;Rahul&quot;, 85);<br>marks.put(&quot;Priya&quot;, 92);<br>marks.put(&quot;Aman&quot;, 78);</pre><pre>System.out.println(marks.get(&quot;Priya&quot;)); // 92</pre><h3>How does HashMap work internally?</h3><p>Let’s understand the basic process.</p><p>When we execute:</p><pre>marks.put(&quot;Rahul&quot;, 85);</pre><p>Java uses the key’s hash code to help determine a bucket in the internal hash table.</p><p>The entry stores the key and value, along with the information needed to manage the bucket.</p><p>When we execute:</p><pre>marks.get(&quot;Rahul&quot;);</pre><p>Java calculates the key’s hash again, identifies the appropriate bucket, and checks keys for a match.</p><p>If multiple keys land in the same bucket, Java handles the collision. In modern OpenJDK implementations, heavily populated buckets can be converted into tree structures under specific conditions, improving worst-case lookup behavior in those buckets.</p><p>The exact thresholds and internal details are implementation-specific.</p><h3>Important HashMap characteristics</h3><ul><li>It does not guarantee iteration order.</li><li>It allows one null key and multiple null values.</li><li>It is not thread-safe for concurrent structural modifications.</li><li>Basic lookup and insertion are generally O(1) on average with suitable hashing.</li><li>It uses hashCode() and equals() to manage key identity and equality.</li></ul><h3>Why are equals() and hashCode() important?</h3><p>Suppose we create a custom Employee class and use its objects as keys in a HashMap.</p><p>If two employees should be considered equal, we must implement equals() and hashCode() consistently.</p><p>The general contract is:</p><ul><li>Equal objects must have equal hash codes.</li><li>Unequal objects may have the same hash code.</li><li>equals() determines whether two keys are equal.</li></ul><p>If a key’s fields used for hashing or equality change after it has been inserted into a map, retrieval may fail because the object may no longer be found in the bucket where it was originally stored.</p><p>Prefer immutable keys or avoid modifying equality-relevant state while an object is being used as a key.</p><h3>15. LinkedHashMap</h3><p>LinkedHashMap combines hash-table lookup with a linked structure that maintains iteration order.</p><p>By default, it preserves insertion order.</p><pre>Map&lt;Integer, String&gt; students = new LinkedHashMap&lt;&gt;();</pre><pre>students.put(3, &quot;Aman&quot;);<br>students.put(1, &quot;Rahul&quot;);<br>students.put(2, &quot;Priya&quot;);</pre><pre>System.out.println(students);</pre><p>Iteration follows insertion order:</p><pre>{3=Aman, 1=Rahul, 2=Priya}</pre><p>It can also be configured to maintain access order, which is useful for implementing certain cache strategies, including least-recently-used cache designs.</p><h3>16. TreeMap</h3><p>TreeMap stores entries sorted by their keys.</p><pre>Map&lt;Integer, String&gt; students = new TreeMap&lt;&gt;();</pre><pre>students.put(3, &quot;Aman&quot;);<br>students.put(1, &quot;Rahul&quot;);<br>students.put(2, &quot;Priya&quot;);</pre><pre>System.out.println(students);</pre><p>Output:</p><pre>{1=Rahul, 2=Priya, 3=Aman}</pre><p>Internally, TreeMap uses a red-black tree, a self-balancing binary search tree.</p><p>Its basic lookup, insertion, and removal operations typically take O(log n).</p><p>Use it when you need keys to remain sorted or need navigation operations such as finding the nearest key.</p><h3>17. Hashtable</h3><p>Hashtable is a legacy Map implementation.</p><p>Its methods are synchronized, and it does not allow null keys or null values.</p><pre>Hashtable&lt;Integer, String&gt; users = new Hashtable&lt;&gt;();</pre><pre>users.put(1, &quot;Rahul&quot;);<br>users.put(2, &quot;Priya&quot;);</pre><p>For most modern applications:</p><ul><li>Use HashMap when external synchronization is not required.</li><li>Use ConcurrentHashMap when concurrent access and updates are needed.</li></ul><p>Hashtable is mainly important for understanding legacy Java code.</p><h3>Part 4: Queue and Deque</h3><h3>19. What is a Queue?</h3><p>A Queue is designed to hold elements before they are processed.</p><p>A traditional queue follows FIFO: <strong>First In, First Out</strong>.</p><p>Think of a line at a ticket counter. The first person to join the line is normally the first person served.</p><p>Java’s Queue interface provides methods for inserting, retrieving, and removing elements.</p><p>MethodBehavioroffer(e)Attempts to add an elementpoll()Removes and returns the head, or returns null if emptypeek()Returns the head without removing it, or null if emptyremove()Removes the head, throwing an exception if emptyelement()Returns the head, throwing an exception if empty</p><p>For queue insertion, offer() is often preferred over add() because some queue implementations can reject an element without throwing an exception.</p><h3>20. PriorityQueue</h3><p>A PriorityQueue processes elements according to priority rather than insertion order.</p><p>By default, Java orders elements according to their natural ordering, so the smallest element is at the head for numbers.</p><pre>Queue&lt;Integer&gt; numbers = new PriorityQueue&lt;&gt;();</pre><pre>numbers.offer(40);<br>numbers.offer(10);<br>numbers.offer(30);<br>numbers.offer(20);</pre><pre>while (!numbers.isEmpty()) {<br>    System.out.println(numbers.poll());<br>}</pre><p>Output:</p><pre>10<br>20<br>30<br>40</pre><p>Internally, PriorityQueue uses a heap.</p><p>Adding or removing an element generally takes O(log n), while inspecting the head takes O(1).</p><p><strong>Important:</strong> Iterating directly over a PriorityQueue does not guarantee that all elements will appear in sorted order. Repeatedly removing the head retrieves elements in priority order.</p><h3>21. Deque and ArrayDeque</h3><p>Deque stands for double-ended queue.</p><p>It allows insertion and removal at both ends.</p><pre>Deque&lt;Integer&gt; deque = new ArrayDeque&lt;&gt;();</pre><pre>deque.addFirst(20);<br>deque.addFirst(10);<br>deque.addLast(30);</pre><pre>System.out.println(deque);</pre><p>Output:</p><pre>[10, 20, 30]</pre><p>ArrayDeque uses a resizable array internally and is commonly used for both queue and stack behavior.</p><h3>Using ArrayDeque as a stack</h3><pre>Deque&lt;Integer&gt; stack = new ArrayDeque&lt;&gt;();</pre><pre>stack.push(10);<br>stack.push(20);<br>stack.push(30);</pre><pre>System.out.println(stack.pop());  // 30<br>System.out.println(stack.peek()); // 20</pre><h3>Using ArrayDeque as a queue</h3><pre>Queue&lt;String&gt; queue = new ArrayDeque&lt;&gt;();</pre><pre>queue.offer(&quot;First&quot;);<br>queue.offer(&quot;Second&quot;);<br>queue.offer(&quot;Third&quot;);</pre><pre>System.out.println(queue.poll()); // First</pre><p>ArrayDeque does not permit null elements.</p><p>It is generally preferred over the legacy Stack class for stack operations and is often an excellent choice for single-threaded queue operations.</p><h3>Part 5: Iteration</h3><h3>22. What is an Iterator?</h3><p>An iterator provides a standard way to traverse elements in a collection without exposing its internal data structure.</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><pre>names.add(&quot;Rahul&quot;);<br>names.add(&quot;Priya&quot;);<br>names.add(&quot;Aman&quot;);</pre><pre>Iterator&lt;String&gt; iterator = names.iterator();</pre><pre>while (iterator.hasNext()) {<br>    System.out.println(iterator.next());<br>}</pre><p>Output:</p><pre>Rahul<br>Priya<br>Aman</pre><p>Important methods:</p><ul><li>hasNext() checks whether another element exists.</li><li>next() returns the next element.</li><li>remove() removes the last element returned by next(), when supported by the iterator.</li></ul><p>An iterator is useful when we want to traverse a collection without depending on its implementation.</p><h3>23. Enhanced for loop</h3><p>Java also provides the enhanced for loop.</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><pre>names.add(&quot;Rahul&quot;);<br>names.add(&quot;Priya&quot;);<br>names.add(&quot;Aman&quot;);</pre><pre>for (String name : names) {<br>    System.out.println(name);<br>}</pre><p>This is simpler when we only need to read elements.</p><p>However, we should not structurally modify an ordinary collection directly inside an enhanced for loop. Doing so may cause a ConcurrentModificationException.</p><p>If we need to remove elements while traversing, use an iterator’s supported remove() method or another appropriate operation.</p><h3>24. List Iterator</h3><p>ListIterator is specifically designed for Lists.</p><p>Unlike an ordinary Iterator, it can traverse in both directions and supports additional operations.</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><pre>names.add(&quot;Rahul&quot;);<br>names.add(&quot;Priya&quot;);<br>names.add(&quot;Aman&quot;);</pre><pre>ListIterator&lt;String&gt; iterator = names.listIterator();</pre><pre>while (iterator.hasNext()) {<br>    System.out.println(iterator.next());<br>}</pre><pre>while (iterator.hasPrevious()) {<br>    System.out.println(iterator.previous());<br>}</pre><p>It also supports operations such as add(), set(), and remove() where permitted.</p><p>Use ListIterator when you need more control over traversal and modification of a list.</p><h3>25. Fail-fast iterators</h3><p>Many standard collection iterators are described as fail-fast.</p><p>If a collection is structurally modified outside the iterator while iteration is in progress, the iterator may throw ConcurrentModificationException.</p><pre>List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();</pre><pre>numbers.add(10);<br>numbers.add(20);<br>numbers.add(30);</pre><pre>for (Integer number : numbers) {<br>    if (number == 20) {<br>        numbers.remove(number);<br>    }<br>}</pre><p>This code can throw ConcurrentModificationException.</p><p>A safer approach is:</p><pre>Iterator&lt;Integer&gt; iterator = numbers.iterator();</pre><pre>while (iterator.hasNext()) {<br>    Integer number = iterator.next();</pre><pre>    if (number == 20) {<br>        iterator.remove();<br>    }<br>}</pre><p>Fail-fast behavior is best-effort bug detection, not a synchronization guarantee. It should not be used as a way to coordinate multiple threads.</p><h3>Part 6: Sorting</h3><h3>26. Comparable</h3><p>Suppose we have a list of employees. We want to sort employees according to their IDs.</p><p>How does Java know which employee should come first?</p><p>We can implement Comparable to define the class&#39;s natural ordering.</p><pre>class Employee implements Comparable&lt;Employee&gt; {</pre><pre>    int id;<br>    String name;</pre><pre>    Employee(int id, String name) {<br>        this.id = id;<br>        this.name = name;<br>    }</pre><pre>    @Override<br>    public int compareTo(Employee other) {<br>        return Integer.compare(this.id, other.id);<br>    }</pre><pre>    @Override<br>    public String toString() {<br>        return id + &quot; - &quot; + name;<br>    }<br>}</pre><p>Now we can sort a list:</p><pre>List&lt;Employee&gt; employees = new ArrayList&lt;&gt;();</pre><pre>employees.add(new Employee(103, &quot;Aman&quot;));<br>employees.add(new Employee(101, &quot;Rahul&quot;));<br>employees.add(new Employee(102, &quot;Priya&quot;));</pre><pre>Collections.sort(employees);</pre><pre>System.out.println(employees);</pre><p>The employees are sorted by ID.</p><p>compareTo() should return a negative number if the current object comes before the other object, zero if they compare equally, or a positive number if it comes after.</p><p>Use Integer.compare() rather than subtracting IDs, which can overflow.</p><h3>27. Comparator</h3><p>What if we want to sort the same employees by name instead of ID?</p><p>We can use Comparator to define an alternative ordering without changing the Employee class.</p><pre>employees.sort(<br>    Comparator.comparing(employee -&gt; employee.name)<br>);</pre><p>Or, using a method reference:</p><pre>employees.sort(Comparator.comparing(Employee::getName));</pre><p>The second example assumes Employee has a getName() method.</p><p>We can sort by multiple fields:</p><pre>employees.sort(<br>    Comparator.comparing(Employee::getName)<br>              .thenComparingInt(Employee::getId)<br>);</pre><p>This sorts by name first, then by ID when names compare equally.</p><h3>Comparable vs. Comparator</h3><p>ComparableComparatorDefines natural ordering in the classDefines an ordering externallyImplements compareTo()Implements compare() or uses factory methodsUsually represents the default orderingSupports multiple alternative orderingsCollections.sort(list) can use itlist.sort(comparator) can use it</p><p>Be careful when writing custom comparators: they should follow a consistent ordering contract.</p><h3>Part 7: Collections utility class</h3><h3>28. Collections vs. Collection</h3><p>These names look almost identical, but they mean different things.</p><ul><li>Collection is an interface.</li><li>Collections is a utility class containing static methods that operate on collections.</li></ul><p>For example:</p><pre>List&lt;Integer&gt; numbers =<br>    new ArrayList&lt;&gt;(Arrays.asList(40, 10, 30, 20));</pre><pre>Collections.sort(numbers);<br>System.out.println(numbers);</pre><pre>Collections.reverse(numbers);<br>System.out.println(numbers);</pre><pre>Collections.shuffle(numbers);<br>System.out.println(numbers);</pre><p>The final output after shuffling is not predictable.</p><p>Other useful methods include:</p><ul><li>Collections.min()</li><li>Collections.max()</li><li>Collections.frequency()</li><li>Collections.binarySearch()</li><li>Collections.unmodifiableList()</li><li>Collections.synchronizedList()</li></ul><h3>Binary search</h3><p>Binary search works on a sorted list.</p><pre>List&lt;Integer&gt; numbers =<br>    new ArrayList&lt;&gt;(Arrays.asList(10, 20, 30, 40, 50));</pre><pre>int index = Collections.binarySearch(numbers, 30);</pre><pre>System.out.println(index); // 2</pre><p>If the value is not found, the method returns a negative value encoding an insertion point.</p><p>Do not use binary search on an unsorted list and expect correct results.</p><h3>Part 8: Advanced concepts</h3><h3>29. Generics in collections</h3><p>Generics allow us to specify the type of elements a collection is intended to hold.</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><p>This tells the compiler that the list holds Strings.</p><p>The following is invalid:</p><pre>names.add(100);</pre><p>The compiler catches the type mismatch before execution.</p><p>Without generics, older code might use raw collections:</p><pre>List names = new ArrayList();</pre><pre>names.add(&quot;Rahul&quot;);<br>names.add(100);</pre><p>Now the collection can contain unrelated types, and casting values back to their expected types can cause runtime errors.</p><p>Prefer parameterized collections:</p><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><p>Generics improve type safety, readability, and maintainability.</p><h3>30. Wildcards in collections</h3><p>Java generics also support wildcards.</p><h3>Unbounded wildcard</h3><pre>void printAll(List&lt;?&gt; values) {<br>    for (Object value : values) {<br>        System.out.println(value);<br>    }<br>}</pre><p>List&lt;?&gt; means a List of some specific but unknown type.</p><p>We can read elements as Object, but generally cannot add arbitrary non-null values to the list.</p><h3>Upper-bounded wildcard</h3><pre>double sum(List&lt;? extends Number&gt; numbers) {<br>    double total = 0;</pre><pre>    for (Number number : numbers) {<br>        total += number.doubleValue();<br>    }</pre><pre>    return total;<br>}</pre><p>? extends Number allows a list of Integer, Double, or another Number subtype.</p><p>This is useful when a method needs to read values from a collection of related types.</p><h3>Lower-bounded wildcard</h3><pre>void addNumbers(List&lt;? super Integer&gt; numbers) {<br>    numbers.add(10);<br>    numbers.add(20);<br>}</pre><p>? super Integer accepts a List whose element type is Integer or a supertype such as Number or Object.</p><p>A useful rule is <strong>PECS</strong>:</p><ul><li>Producer Extends: use ? extends T when a structure produces values for us to read.</li><li>Consumer Super: use ? super T when a structure consumes values we add.</li></ul><p>This is a guideline, not a replacement for understanding the actual type requirements.</p><h3>31. Immutable and unmodifiable collections</h3><p>Sometimes we want to prevent a collection from being modified.</p><p>Java provides several approaches.</p><h3>Unmodifiable view</h3><pre>List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><pre>names.add(&quot;Rahul&quot;);<br>names.add(&quot;Priya&quot;);</pre><pre>List&lt;String&gt; view = Collections.unmodifiableList(names);</pre><p>The view cannot be modified through its own modifying methods.</p><p>However, changes to the original names list can still be visible through the view.</p><h3>Immutable factory methods</h3><p>Java 9 introduced factory methods such as:</p><pre>List&lt;String&gt; names = List.of(&quot;Rahul&quot;, &quot;Priya&quot;);<br>Set&lt;Integer&gt; ids = Set.of(101, 102, 103);<br>Map&lt;Integer, String&gt; users =<br>    Map.of(1, &quot;Rahul&quot;, 2, &quot;Priya&quot;);</pre><p>These collections cannot be structurally modified, and the factory methods reject null elements, keys, or values as applicable.</p><p>This is useful when we need fixed configuration or constant data.</p><p>Remember that an unmodifiable collection does not automatically make its contained objects immutable.</p><h3>32. The Stream API and collections</h3><p>Java 8 introduced the Stream API, which allows us to process collection data using operations such as filtering, mapping, and reducing.</p><p>For example:</p><pre>List&lt;Integer&gt; numbers =<br>    Arrays.asList(10, 15, 20, 25, 30);</pre><pre>List&lt;Integer&gt; evenNumbers = numbers.stream()<br>    .filter(number -&gt; number % 2 == 0)<br>    .collect(Collectors.toList());</pre><pre>System.out.println(evenNumbers);</pre><p>Output:</p><pre>[10, 20, 30]</pre><p>Let’s understand the operations:</p><ul><li>stream() creates a stream over the collection.</li><li>filter() keeps elements matching a condition.</li><li>collect() gathers the results into a collection.</li></ul><p>Another example:</p><pre>int total = numbers.stream()<br>    .mapToInt(Integer::intValue)<br>    .sum();</pre><pre>System.out.println(total);</pre><p>Streams do not automatically modify the original collection. They process elements and produce results according to the pipeline operations.</p><p>Use streams when they make data-processing logic clearer. For simple operations, a regular loop can be equally readable.</p><h3>33. Concurrent collections</h3><p>Most standard collection implementations, including ArrayList and HashMap, are not designed for unsynchronized concurrent modification by multiple threads.</p><p>Java provides concurrent collections for multithreaded applications.</p><h3>ConcurrentHashMap</h3><p>ConcurrentHashMap supports concurrent access and updates.</p><pre>Map&lt;String, Integer&gt; counts = new ConcurrentHashMap&lt;&gt;();</pre><pre>counts.put(&quot;Java&quot;, 10);<br>counts.put(&quot;Python&quot;, 5);</pre><pre>counts.merge(&quot;Java&quot;, 1, Integer::sum);</pre><pre>System.out.println(counts.get(&quot;Java&quot;)); // 11</pre><p>The merge() method performs the update using an atomic map operation, making it more appropriate for this example than separately reading and writing the value.</p><p>ConcurrentHashMap does not permit null keys or values.</p><h3>CopyOnWriteArrayList</h3><p>CopyOnWriteArrayList creates a new backing array when it is modified.</p><p>This can be useful when reads and iterations are frequent but updates are relatively rare.</p><p>It is not a good choice for every workload because each write can be expensive.</p><h3>BlockingQueue</h3><p>A BlockingQueue is useful when one thread produces work and another consumes it.</p><p>For example:</p><pre>Producer thread<br>       |<br>       v<br>  BlockingQueue<br>       |<br>       v<br>Consumer thread</pre><p>The queue can block a consumer when it is empty or block a producer when a bounded queue is full.</p><p>This is useful in task-processing systems, worker pools, and producer-consumer architectures.</p><h3>34. Performance and Big-O complexity</h3><p>Choosing the right collection requires understanding the operations your application performs most frequently.</p><p>CollectionAccess or lookupInsertRemoveArrayListIndex: O(1); search: O(n)End: amortized O(1); middle: O(n)Middle: O(n)LinkedListIndex: O(n)At an already-known end or node: O(1)At an already-known end or node: O(1)HashSetAverage O(1)Average O(1)Average O(1)TreeSetO(log n)O(log n)O(log n)HashMapAverage O(1)Average O(1)Average O(1)TreeMapO(log n)O(log n)O(log n)PriorityQueueHead: O(1); arbitrary search: O(n)O(log n)Head removal: O(log n)</p><p>These are typical complexity estimates, not guarantees for every implementation or every input. Hash-based collections depend on hashing behavior, while linked structures depend on whether the target position is already known.</p><h3>35. Common mistakes when using collections</h3><p><strong>Mistake 1: Assuming HashMap maintains insertion order.</strong></p><p>It does not guarantee iteration order. Use LinkedHashMap if insertion order matters.</p><p><strong>Mistake 2: Assuming Set preserves insertion order.</strong></p><p>HashSet does not guarantee it. Use LinkedHashSet when insertion order is required.</p><p><strong>Mistake 3: Modifying a collection directly while iterating.</strong></p><p>This can trigger ConcurrentModificationException. Use supported iterator operations or a suitable alternative.</p><p><strong>Mistake 4: Forgetting that Map keys are unique.</strong></p><p>Adding a value for an existing key replaces the previous mapping.</p><p><strong>Mistake 5: Using a mutable object as a HashMap key.</strong></p><p>Changing fields used by equals() or hashCode() can make the mapping difficult to retrieve.</p><p><strong>Mistake 6: Assuming thread safety from individual operations.</strong></p><p>Thread-safe operations do not automatically make a sequence of operations atomic.</p><p><strong>Mistake 7: Using the wrong collection for the requirement.</strong></p><p>A TreeSet is useful for sorted unique elements; an ArrayList is useful for indexed access; a HashMap is useful for key-based lookup.</p><h3>36. Which collection should we choose?</h3><p>Here is a practical decision guide.</p><p>RequirementRecommended starting pointResizable list with fast indexed accessArrayListUnique values with no ordering requirementHashSetUnique values in insertion orderLinkedHashSetUnique values in sorted orderTreeSetFast average key-based lookupHashMapMap entries in insertion orderLinkedHashMapMap entries sorted by keyTreeMapFIFO queueArrayDeque or a suitable Queue implementationStack operationsArrayDequePriority-based processingPriorityQueueConcurrent key-value accessConcurrentHashMapProducer-consumer task processingA suitable BlockingQueue</p><p>The best collection depends on your actual requirements, including ordering, null handling, concurrency, memory use, and operation frequency.</p><h3>37. Final revision: What have we learned?</h3><p>We started with a simple question: how do we manage groups of objects in Java?</p><p>We learned that the Collections Framework provides reusable interfaces, data structures, and algorithms.</p><p>We covered:</p><ul><li>The Collections Framework and its hierarchy.</li><li>The Collection interface.</li><li>Lists: ArrayList, LinkedList, Vector, and Stack.</li><li>Sets: HashSet, LinkedHashSet, and TreeSet.</li><li>Maps: HashMap, LinkedHashMap, TreeMap, Hashtable, and ConcurrentHashMap.</li><li>Queues: Queue, PriorityQueue, Deque, and ArrayDeque.</li><li>Iteration using Iterator, ListIterator, and enhanced for loops.</li><li>Sorting using Comparable and Comparator.</li><li>Utility methods from Collections.</li><li>Generics, wildcards, and immutable collections.</li><li>Streams and concurrent collections.</li><li>Internal data structures, time complexity, and common mistakes.</li></ul><h3>Conclusion</h3><p>The Java Collections Framework is much more than a group of classes for storing data. It provides the foundation for writing efficient, reusable, and maintainable Java applications.</p><p>As you practise, focus on understanding <strong>why a particular collection is useful, how it works internally, and what trade-offs it makes</strong>. That understanding will help you solve coding problems, answer interview questions, and choose the right data structure in real-world projects.</p><p>Happy learning! ☕</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e2579d16e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Errors and Exceptions in Java: From Beginner to Advanced ☕]]></title>
            <link>https://medium.com/@aishureddy/errors-and-exceptions-in-java-from-beginner-to-advanced-f754198baa45?source=rss-04ef0daaee11------2</link>
            <guid isPermaLink="false">https://medium.com/p/f754198baa45</guid>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Aishu Reddy]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 14:44:57 GMT</pubDate>
            <atom:updated>2026-10-11T14:44:57.059Z</atom:updated>
            <content:encoded><![CDATA[<h3>A complete guide to understanding, handling, and mastering exceptions</h3><h3>1. Introduction: What happens when something goes wrong?</h3><p>Imagine we are developing a banking application. A user tries to withdraw money, but the account has insufficient balance. Or imagine our application tries to read a file that does not exist.</p><p>Should the entire application stop working? Not necessarily!</p><p>Java provides a mechanism called <strong>exception handling</strong>, which allows us to detect and respond to exceptional situations during program execution.</p><p>Before understanding exception handling, let’s first understand the different types of programming mistakes.</p><h3>2. Types of errors in programming</h3><h3>2.1 Compile-time errors</h3><p>These errors occur when the compiler detects invalid syntax or a violation of Java’s language rules.</p><pre>int number = 10<br>System.out.println(number);</pre><p>We forgot the semicolon after 10, so the compiler reports an error.</p><h3>2.2 Runtime exceptions</h3><p>These occur while the program is running.</p><pre>int a = 10;<br>int b = 0;</pre><pre>System.out.println(a / b);</pre><p>This compiles successfully but throws an ArithmeticException during execution.</p><h3>2.3 Logical errors</h3><p>Logical errors occur when our program runs successfully but produces the wrong result.</p><pre>int length = 10;<br>int breadth = 5;</pre><pre>int area = length + breadth;</pre><p>We used addition instead of multiplication. The program runs, but the calculated area is incorrect.</p><p><strong>Important distinction:</strong> In Java terminology, Error is also a specific class in the exception hierarchy. A compile-time mistake or logical mistake is not automatically an instance of java.lang.Error.</p><h3>3. What is an exception?</h3><p>An exception is an event represented by an object that disrupts the normal flow of program execution.</p><p>For example:</p><pre>int result = 10 / 0;</pre><p>Java throws an ArithmeticException because integer division by zero is not allowed.</p><p>An exception object can contain a message, a stack trace, and an optional cause. We can use this information to understand what went wrong.</p><h3>4. The Java exception hierarchy</h3><p>Java organizes errors and exceptions into a class hierarchy.</p><pre>Object<br>  |<br>Throwable<br>  |<br>  |--- Error<br>  |<br>  |--- Exception<br>         |<br>         |--- IOException<br>         |--- SQLException<br>         |--- RuntimeException<br>                  |<br>                  |--- ArithmeticException<br>                  |--- NullPointerException<br>                  |--- IllegalArgumentException</pre><p>This is a simplified hierarchy.</p><ul><li>Throwable: The root class for objects that Java can throw.</li><li>Error: Represents serious JVM or system-level problems.</li><li>Exception: Represents exceptional conditions applications may handle.</li><li>RuntimeException: The superclass of unchecked exceptions commonly associated with invalid arguments, states, or programming mistakes.</li></ul><h3>5. Checked and unchecked exceptions</h3><h3>Checked exceptions</h3><p>The compiler requires checked exceptions to be caught or declared when the relevant operations can throw them.</p><p>Examples include IOException, SQLException, and InterruptedException.</p><pre>import java.io.FileReader;<br>import java.io.IOException;</pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        try {<br>            FileReader reader = new FileReader(&quot;data.txt&quot;);<br>            reader.close();<br>        } catch (IOException e) {<br>            System.out.println(&quot;File operation failed.&quot;);<br>        }<br>    }<br>}</pre><h3>Unchecked exceptions</h3><p>Unchecked exceptions do not have the compiler’s catch-or-declare requirement.</p><pre>int[] numbers = {10, 20, 30};<br>System.out.println(numbers[5]);</pre><p>This throws ArrayIndexOutOfBoundsException at runtime.</p><p><strong>Remember:</strong> Checked and unchecked refer to compiler enforcement, not whether an exception occurs at compile time or runtime.</p><h3>6. Exception handling using try and catch</h3><p>The try block contains code that might throw an exception. A catch block handles a matching exception.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        try {<br>            int result = 10 / 0;<br>            System.out.println(result);<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Cannot divide by zero.&quot;);<br>        }</pre><pre>        System.out.println(&quot;Program continues.&quot;);<br>    }<br>}</pre><p>Output:</p><pre>Cannot divide by zero.<br>Program continues.</pre><p>Once the exception occurs, the remaining statements in that try block are skipped, and Java searches for a suitable handler.</p><h3>7. Multiple catch blocks</h3><p>A single try block can be followed by multiple catch blocks.</p><pre>try {<br>    int[] values = {10, 20};<br>    System.out.println(values[5]);<br>} catch (ArrayIndexOutOfBoundsException e) {<br>    System.out.println(&quot;Invalid array index.&quot;);<br>} catch (Exception e) {<br>    System.out.println(&quot;Unexpected problem.&quot;);<br>}</pre><p>The more specific exception should come before its parent exception. Otherwise, the more specific handler may become unreachable.</p><p>Java also supports multi-catch:</p><pre>try {<br>    // Some operation<br>} catch (java.io.IOException | IllegalArgumentException e) {<br>    System.out.println(&quot;Operation failed.&quot;);<br>}</pre><p>Multi-catch is useful when unrelated exception types need identical handling.</p><h3>8. The finally block</h3><p>The finally block is commonly used for cleanup code.</p><pre>try {<br>    System.out.println(&quot;Inside try&quot;);<br>} catch (Exception e) {<br>    System.out.println(&quot;Exception handled&quot;);<br>} finally {<br>    System.out.println(&quot;Cleanup&quot;);<br>}</pre><p>The finally block normally executes when control leaves the try-catch statement, whether an exception occurs or not.</p><p>However, it is not guaranteed to run if the JVM or process terminates abruptly.</p><h3>9. The throw keyword</h3><p>We use throw to explicitly throw an exception object.</p><pre>public static void withdraw(double amount) {<br>    if (amount &lt;= 0) {<br>        throw new IllegalArgumentException(<br>            &quot;Amount must be positive&quot;<br>        );<br>    }</pre><pre>    System.out.println(&quot;Withdrawal requested.&quot;);<br>}</pre><p>Here, we enforce a business rule by throwing an exception when the amount is invalid.</p><h3>10. The throws keyword</h3><p>We use throws in a method declaration to indicate which exceptions the method may propagate to its caller.</p><pre>import java.io.IOException;</pre><pre>public class Main {<br>    static void readFile() throws IOException {<br>        // File-reading operation that may throw IOException<br>    }<br>}</pre><p>For checked exceptions, the caller must handle the exception or declare it in turn.</p><p>throwthrowsThrows an exception objectDeclares possible exceptionsUsed inside a method or blockUsed in a method signaturethrow new IOException();void read() throws IOException</p><h3>11. Exception propagation</h3><p>Suppose method A calls method B, and method B calls method C. If method C throws an exception without handling it, Java can propagate that exception up the call stack.</p><pre>public class Main {</pre><pre>    static void methodC() {<br>        int result = 10 / 0;<br>    }</pre><pre>    static void methodB() {<br>        methodC();<br>    }</pre><pre>    static void methodA() {<br>        methodB();<br>    }</pre><pre>    public static void main(String[] args) {<br>        try {<br>            methodA();<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Caught in main.&quot;);<br>        }<br>    }<br>}</pre><p>The exception travels from methodC() through methodB() and methodA() until the handler in main() catches it.</p><h3>12. Creating custom exceptions</h3><p>Sometimes built-in exceptions do not describe our application’s business rules clearly enough.</p><p>For example, we might want an InsufficientBalanceException.</p><pre>class InsufficientBalanceException extends Exception {<br>    public InsufficientBalanceException(String message) {<br>        super(message);<br>    }<br>}</pre><p>We can then use it in a method:</p><pre>static void withdraw(double balance, double amount)<br>        throws InsufficientBalanceException {</pre><pre>    if (amount &gt; balance) {<br>        throw new InsufficientBalanceException(<br>            &quot;Insufficient balance.&quot;<br>        );<br>    }<br>}</pre><p>Extending Exception creates a checked custom exception. Extending RuntimeException creates an unchecked custom exception.</p><h3>13. Try-with-resources</h3><p>Java 7 introduced try-with-resources to automatically close resources that implement AutoCloseable.</p><pre>import java.io.BufferedReader;<br>import java.io.FileReader;<br>import java.io.IOException;</pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        try (BufferedReader reader =<br>                 new BufferedReader(new FileReader(&quot;data.txt&quot;))) {</pre><pre>            System.out.println(reader.readLine());</pre><pre>        } catch (IOException e) {<br>            System.out.println(&quot;Unable to read the file.&quot;);<br>        }<br>    }<br>}</pre><p>Java automatically closes the reader when execution leaves the try-with-resources statement, including when an exception occurs.</p><h3>14. Advanced concept: Exception rethrowing</h3><p>Sometimes we catch an exception to log information or perform a small operation, but we still want the calling method to handle the failure.</p><pre>static void process() throws IOException {<br>    try {<br>        // An operation that may throw IOException<br>        throw new IOException(&quot;Processing failed&quot;);<br>    } catch (IOException e) {<br>        System.out.println(&quot;Logging the failure&quot;);<br>        throw e;<br>    }<br>}</pre><p>The exception is caught and then rethrown. The caller can still handle it.</p><p>Rethrowing is useful when a method needs to perform local work without taking responsibility for fully recovering from the failure.</p><h3>15. Advanced concept: Exception wrapping and chaining</h3><p>Suppose a low-level database operation throws SQLException, but our application exposes a service-level API.</p><p>Instead of exposing every database detail, we may wrap the original exception in a more meaningful exception.</p><pre>try {<br>    // Database operation<br>} catch (java.sql.SQLException e) {<br>    throw new IllegalStateException(<br>        &quot;Unable to load account details&quot;, e<br>    );<br>}</pre><p>The second argument, e, preserves the original cause.</p><p>This is called <strong>exception chaining</strong>. It helps us understand the high-level failure while retaining information about the underlying problem.</p><h3>16. Advanced concept: Custom checked vs. unchecked exceptions</h3><p>When designing an exception class, we need to decide whether it should be checked or unchecked.</p><pre>class InvalidOrderException extends RuntimeException {<br>    public InvalidOrderException(String message) {<br>        super(message);<br>    }<br>}</pre><p>An unchecked exception like this is useful when the caller is not expected to recover by explicitly catching every occurrence.</p><p>A checked exception may be appropriate when callers are expected to handle a recoverable condition and the API benefits from making that requirement explicit.</p><p>There is no universal rule that all business exceptions must be checked or unchecked. The decision depends on the API contract and how callers are expected to respond.</p><h3>17. Advanced concept: Suppressed exceptions</h3><p>Try-with-resources has an important detail that is often overlooked.</p><p>Suppose the code inside a try block throws one exception, and closing the resource also throws an exception. Java preserves the primary exception and records the closing exception as a <strong>suppressed exception</strong>.</p><pre>try (MyResource resource = new MyResource()) {<br>    throw new IllegalStateException(&quot;Primary failure&quot;);<br>}</pre><p>If close() also fails, the closing failure can be retrieved using:</p><pre>e.getSuppressed()</pre><p>This behavior helps prevent a cleanup failure from simply replacing the original exception.</p><p>The example assumes MyResource is a class that implements AutoCloseable and whose close() method can throw an exception.</p><h3>18. Advanced concept: The exception stack trace</h3><p>A stack trace helps us find where an exception occurred and how execution reached that point.</p><pre>try {<br>    int result = 10 / 0;<br>} catch (ArithmeticException e) {<br>    e.printStackTrace();<br>}</pre><p>A stack trace typically contains:</p><ul><li>The exception class and message.</li><li>The sequence of method calls.</li><li>The source file and line number, when available.</li></ul><p>In real applications, use a logging framework to record exceptions appropriately. Avoid swallowing exceptions or logging the same failure repeatedly at every layer.</p><h3>19. Advanced concept: Errors and recovery</h3><p>Examples of Java’s Error subclasses include:</p><ul><li>OutOfMemoryError</li><li>StackOverflowError</li><li>NoClassDefFoundError</li></ul><p>These often indicate serious runtime or environment problems. Catching them indiscriminately and continuing execution is usually unsafe.</p><p>For example, StackOverflowError may occur because of infinite recursion:</p><pre>static void repeat() {<br>    repeat();<br>}</pre><p>The method continues calling itself until the thread’s stack limit is exceeded.</p><p>The right solution is to fix the recursion or otherwise address the root cause, rather than blindly catching the error.</p><h3>20. Best practices for real-world Java applications</h3><ol><li>Catch exceptions that you can meaningfully handle.</li><li>Prefer specific exception types over broad catch blocks.</li><li>Never silently ignore an exception.</li><li>Use try-with-resources for files, streams, and other supported resources.</li><li>Preserve the original cause when wrapping exceptions.</li><li>Use custom exceptions when they communicate meaningful application-specific failures.</li><li>Avoid using exceptions for ordinary control flow.</li><li>Do not catch Error indiscriminately.</li><li>Include useful context in error messages without exposing passwords, tokens, or other secrets.</li><li>Handle InterruptedException carefully and preserve the thread&#39;s interrupt status when appropriate.</li></ol><h3>Conclusion</h3><p>Exception handling is not just about preventing a program from crashing. It is about designing predictable behavior when something goes wrong.</p><p>By learning the basics first and then progressing to propagation, custom exceptions, exception chaining, suppressed exceptions, and best practices, we can build a strong foundation in Java exception handling.</p><p>Keep practising these concepts with small examples before applying them to real-world applications.</p><p>Happy learning! ☕</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f754198baa45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wrapper Classes in Java]]></title>
            <link>https://medium.com/@aishureddy/wrapper-classes-in-java-e6c474972c31?source=rss-04ef0daaee11------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6c474972c31</guid>
            <category><![CDATA[wrapper-class]]></category>
            <dc:creator><![CDATA[Aishu Reddy]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 06:37:18 GMT</pubDate>
            <atom:updated>2026-10-09T06:37:18.459Z</atom:updated>
            <content:encoded><![CDATA[<p>Java is often called an <strong>object-oriented programming language</strong>, but there is one thing that makes it different from being completely object-oriented: <strong>Java has primitive data types</strong>.</p><p>Primitive data types are:</p><pre>byte<br>short<br>int<br>long<br>float<br>double<br>char<br>boolean</pre><p>These are not objects.</p><p>For example:</p><pre>int age = 22;</pre><p>Here, age is a primitive variable, not an object.</p><p>So we can say:</p><blockquote><em>Java is not considered purely object-oriented because it has primitive data types that are not objects.</em></blockquote><p>But this raises an interesting question:</p><p><strong>If Java is object-oriented, how can we represent primitive values as objects?</strong></p><p>This is where <strong>Wrapper Classes</strong> come into the picture.</p><h3>What are Wrapper Classes?</h3><p>Wrapper classes are classes that provide an <strong>object representation of primitive data types</strong>.</p><p>Each primitive data type has a corresponding wrapper class.</p><p>PrimitiveWrapper ClassbyteByteshortShortintIntegerlongLongfloatFloatdoubleDoublecharCharacterbooleanBoolean</p><p>For example:</p><pre>int age = 22;</pre><p>Here age is a primitive.</p><p>But:</p><pre>Integer age = 22;</pre><p>Here age is an object of the Integer wrapper class.</p><h3>Why do we use Primitive Data Types?</h3><p>If wrapper classes give us objects, then why don’t we simply use wrapper classes everywhere?</p><p>One major reason is <strong>performance</strong>.</p><p>Primitive data types are generally more lightweight and efficient than objects.</p><p>For example:</p><pre>int a = 10;<br>int b = 20;</pre><p>Here Java stores primitive values directly without requiring an object to represent each value.</p><p>Creating and working with objects involves additional memory and object-management overhead.</p><p>Therefore, when we simply need to store and perform operations on values, primitives are often more efficient.</p><p>So:</p><blockquote><strong><em>Primitives are generally preferred when we don’t need an object.</em></strong></blockquote><p>Wrapper classes become useful when Java or an API specifically requires an object.</p><h3>Why Do We Need Wrapper Classes?</h3><p>There are many situations in Java where we need an object instead of a primitive.</p><p>One common example is <strong>Collections</strong>.</p><p>Consider an ArrayList:</p><pre>ArrayList&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();</pre><p>We cannot write:</p><pre>ArrayList&lt;int&gt; numbers = new ArrayList&lt;&gt;();</pre><p>because Java Collections work with objects, not primitive types.</p><p>Therefore, we use:</p><pre>Integer</pre><p>instead of:</p><pre>int</pre><p>For example:</p><pre>ArrayList&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();</pre><pre>numbers.add(10);<br>numbers.add(20);<br>numbers.add(30);</pre><p>Here, Integer allows integer values to be represented as objects so they can be used with the collection.</p><h3>Autoboxing</h3><p>Now let’s understand <strong>autoboxing</strong>.</p><p>Autoboxing means Java automatically converts a <strong>primitive value into its corresponding wrapper object</strong>.</p><p>For example:</p><pre>int number = 10;</pre><pre>Integer obj = number;</pre><p>Here:</p><pre>int → Integer</pre><p>Java automatically converts the primitive int into an Integer object.</p><p>We don’t have to manually create the object.</p><p>This automatic conversion is called <strong>autoboxing</strong>.</p><p>Conceptually, Java does something similar to:</p><pre>Integer obj = Integer.valueOf(number);</pre><p>So:</p><pre>int number = 10;<br>Integer obj = number;</pre><p>is an example of autoboxing.</p><h3>Unboxing</h3><p>The opposite of autoboxing is called <strong>unboxing</strong>.</p><p>Unboxing means Java automatically converts a <strong>wrapper object back into its corresponding primitive type</strong>.</p><p>For example:</p><pre>Integer obj = 10;</pre><pre>int number = obj;</pre><p>Here:</p><pre>Integer → int</pre><p>Java automatically converts the Integer object into an int.</p><p>This is called <strong>unboxing</strong>.</p><p>Conceptually, Java does something similar to:</p><pre>int number = obj.intValue();</pre><h3>Autoboxing and Unboxing Together</h3><p>We can have both conversions in the same program.</p><pre>int a = 10;          // primitive</pre><pre>Integer b = a;       // autoboxing</pre><pre>int c = b;           // unboxing</pre><p>So the flow is:</p><pre>Autoboxing<br>int  ───────────────→  Integer<br> ↑                       |<br> |                       |<br> └───────────────────────┘<br>        Unboxing</pre><h3>Creating Wrapper Objects</h3><p>Wrapper classes are classes, so they provide methods that we can use.</p><p>For example:</p><pre>Integer number = Integer.valueOf(100);</pre><p>We can also use:</p><pre>Integer number = 100;</pre><p>The second form uses autoboxing.</p><p>For modern Java code, using valueOf() or autoboxing is preferred over explicitly creating wrapper objects using constructors.</p><p>For example, we should avoid:</p><pre>Integer number = new Integer(100);</pre><p>because wrapper constructors such as Integer(int) are deprecated.</p><p>Prefer:</p><pre>Integer number = Integer.valueOf(100);</pre><p>or simply:</p><pre>Integer number = 100;</pre><h3>Useful Methods in Wrapper Classes</h3><p>Wrapper classes provide many useful methods.</p><p>For example, Integer provides methods for converting strings into integers.</p><pre>int number = Integer.parseInt(&quot;100&quot;);</pre><p>Here:</p><pre>String &quot;100&quot;<br>      ↓<br>Integer.parseInt()<br>      ↓<br>int 100</pre><p>This is very useful when we receive numbers as strings.</p><p>For example:</p><pre>String age = &quot;22&quot;;</pre><pre>int number = Integer.parseInt(age);</pre><pre>System.out.println(number + 5);</pre><p>Output:</p><pre>27</pre><p>Without parsing, &quot;22&quot; + 5 would result in:</p><pre>225</pre><p>because &quot;22&quot; is a string.</p><h3>valueOf() vs parseInt()</h3><p>These two methods can sometimes be confusing.</p><h3>parseInt()</h3><p>Returns a primitive int.</p><pre>int number = Integer.parseInt(&quot;100&quot;);</pre><h3>valueOf()</h3><p>Returns an Integer object.</p><pre>Integer number = Integer.valueOf(&quot;100&quot;);</pre><p>So:</p><pre>parseInt() → int<br>valueOf()  → Integer</pre><h3>Wrapper Classes Can Contain null</h3><p>Primitive variables cannot normally contain null.</p><p>For example:</p><pre>int age = null;</pre><p>This is invalid.</p><p>But an Integer can contain null:</p><pre>Integer age = null;</pre><p>This is useful when we need to represent the absence of a value.</p><p>For example, in databases, a column might contain NULL.</p><p>A Java Integer can represent that missing value:</p><pre>Integer age = null;</pre><p>while:</p><pre>int age;</pre><p>cannot represent null.</p><h3>Wrapper Classes and Collections</h3><p>One of the most common places where wrapper classes are used is the Java Collections Framework.</p><p>For example:</p><pre>List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();</pre><p>We use Integer instead of int.</p><p>But notice something interesting:</p><pre>numbers.add(10);</pre><p>We are passing an int, not explicitly creating an Integer.</p><p>Java automatically performs <strong>autoboxing</strong>:</p><pre>10<br> ↓<br>int<br> ↓ autoboxing<br>Integer<br> ↓<br>List&lt;Integer&gt;</pre><p>Similarly, when we retrieve the value:</p><pre>int number = numbers.get(0);</pre><p>Java automatically performs <strong>unboxing</strong>:</p><pre>Integer<br>   ↓ unboxing<br>int</pre><p>This is one of the reasons autoboxing and unboxing are very useful.</p><h3>Wrapper Class Caching</h3><p>There is another interesting concept with wrapper classes.</p><p>Java may cache certain wrapper objects, especially for commonly used values.</p><p>For example, with Integer:</p><pre>Integer a = 100;<br>Integer b = 100;</pre><pre>System.out.println(a == b);</pre><p>This will typically print:</p><pre>true</pre><p>because commonly used Integer values are cached.</p><p>But:</p><pre>Integer a = 200;<br>Integer b = 200;</pre><pre>System.out.println(a == b);</pre><p>may print:</p><pre>false</pre><p>because two different objects may be created.</p><p>This is why we should <strong>not use </strong><strong>== to compare wrapper objects when we want to compare their values</strong>.</p><p>Instead, use:</p><pre>Integer a = 100;<br>Integer b = 100;</pre><pre>System.out.println(a.equals(b));</pre><p>equals() compares the values.</p><p>This is an important point when working with wrapper classes.</p><h3>The Big Picture</h3><p>We can understand wrapper classes using this simple flow:</p><pre>Primitive Data Types<br>       |<br>       | Need object representation<br>       ↓<br>Wrapper Classes<br>       |<br>       ├── int     → Integer<br>       ├── char    → Character<br>       ├── double  → Double<br>       ├── boolean → Boolean<br>       └── ...</pre><p>And Java makes the conversion easy:</p><pre>Primitive                    Wrapper<br>   int  ───── autoboxing ───→ Integer<br>   int  ←──── unboxing ───── Integer</pre><p>So the key idea is:</p><blockquote><strong><em>Wrapper classes provide object representations of primitive data types. They are especially useful when Java requires objects, such as when working with collections, and Java automatically converts between primitives and their wrapper classes through autoboxing and unboxing.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6c474972c31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Java : Abstract Classes, Interfaces, Inner Classes and Anonymous Classes in Java]]></title>
            <link>https://medium.com/@aishureddy/core-java-abstract-classes-interfaces-inner-classes-and-anonymous-classes-in-java-a2afb3312852?source=rss-04ef0daaee11------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2afb3312852</guid>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[abstract-keyword]]></category>
            <dc:creator><![CDATA[Aishu Reddy]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 06:36:56 GMT</pubDate>
            <atom:updated>2026-10-09T06:36:56.439Z</atom:updated>
            <content:encoded><![CDATA[<p>Now let’s talk about some important Java concepts:</p><ul><li>abstract classes and methods</li><li>Interfaces</li><li>Why we need interfaces</li><li>Multiple interfaces</li><li>Functional interfaces</li><li>Inner classes</li><li>Static nested classes</li><li>Anonymous inner classes</li></ul><p>These concepts are mainly used to achieve <strong>abstraction, code reuse, flexibility, and loose coupling</strong>.</p><h3>Abstract Keyword</h3><p>The abstract keyword is used when we want to define something without providing its complete implementation.</p><p>For example, imagine we have an Animal class.</p><p>Every animal makes some kind of sound, but the actual sound depends on the animal.</p><p>A dog barks, a cat meows, and a cow moos.</p><p>Instead of providing a generic implementation in the parent class, we can declare the method as abstract:</p><pre>abstract class Animal {</pre><pre>    abstract void sound();<br>}</pre><p>Here:</p><pre>abstract void sound();</pre><p>is an <strong>abstract method</strong>.</p><p>It has a method declaration but does not have a method body.</p><h3>Abstract Class</h3><p>A class containing an abstract method must be declared as an abstract class.</p><p>For example:</p><pre>abstract class Animal {</pre><pre>    abstract void sound();<br>}</pre><p>Now a child class can extend it and provide the implementation:</p><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>Dog is called a <strong>concrete class</strong> because it provides the implementation of the abstract method.</p><p>Now we can create a Dog object:</p><pre>Dog dog = new Dog();</pre><pre>dog.sound();</pre><p>Output:</p><pre>Dog barks</pre><h3>We Cannot Create an Object of an Abstract Class</h3><p>We cannot directly create an object of an abstract class.</p><p>For example:</p><pre>Animal animal = new Animal();</pre><p>This is not allowed.</p><p>Why?</p><p>Because Animal contains an abstract method whose implementation is not provided.</p><p>Java doesn’t know what should happen when we call:</p><pre>animal.sound();</pre><p>Instead, we create an object of the concrete child class:</p><pre>Animal animal = new Dog();</pre><p>This is allowed because the actual Dog class provides the implementation.</p><p>Notice that this is also an example of <strong>runtime polymorphism</strong>:</p><pre>Animal reference<br>      ↓<br>   Dog object<br>      ↓<br>Dog&#39;s sound() executes</pre><h3>Abstract Class Can Have Both Abstract and Normal Methods</h3><p>An abstract class does <strong>not</strong> have to contain only abstract methods.</p><p>It can contain:</p><ul><li>Abstract methods</li><li>Concrete methods</li><li>Variables</li><li>Constructors</li><li>Static methods</li><li>Other members</li></ul><p>For example:</p><pre>abstract class Animal {</pre><pre>    abstract void sound();</pre><pre>    void eat() {<br>        System.out.println(&quot;Animal is eating&quot;);<br>    }<br>}</pre><p>Here:</p><pre>abstract void sound();</pre><p>doesn’t have an implementation.</p><p>But:</p><pre>void eat() {<br>    System.out.println(&quot;Animal is eating&quot;);<br>}</pre><p>has an implementation.</p><p>A child class inherits the concrete method and implements the abstract method.</p><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><h3>Why Do We Need Abstract Classes?</h3><p>Suppose we have:</p><pre>Animal<br> ├── Dog<br> ├── Cat<br> └── Cow</pre><p>Every animal should have a sound() method, but each animal makes a different sound.</p><p>We can force every child class to provide its own implementation:</p><pre>abstract class Animal {</pre><pre>    abstract void sound();<br>}</pre><p>Now if we create:</p><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>Java makes sure that Dog implements the abstract method.</p><p>So an abstract class can provide a <strong>common structure or contract</strong> for its child classes.</p><h3>Interfaces</h3><p>Now let’s talk about interfaces.</p><p>An interface is another way of achieving <strong>abstraction</strong> in Java.</p><p>We create an interface using the interface keyword.</p><p>For example:</p><pre>interface Animal {</pre><pre>    void sound();<br>}</pre><p>Traditionally, interfaces were mainly used to define abstract methods.</p><p>But modern Java interfaces can also contain:</p><ul><li>Abstract methods</li><li>default methods</li><li>static methods</li><li>private methods</li></ul><p>So it is not completely correct to say:</p><blockquote><em>“An interface only contains abstract methods.”</em></blockquote><p>That was mainly true of older Java versions.</p><h3>Implementing an Interface</h3><p>A class uses the implements keyword to implement an interface.</p><pre>interface Animal {</pre><pre>    void sound();<br>}</pre><pre>class Dog implements Animal {</pre><pre>    @Override<br>    public void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>Now we can create:</p><pre>Dog dog = new Dog();</pre><pre>dog.sound();</pre><p>Output:</p><pre>Dog barks</pre><h3>extends vs implements</h3><p>This is an important rule.</p><p>When a <strong>class inherits from another class</strong>, we use:</p><pre>extends</pre><p>Example:</p><pre>class Dog extends Animal {<br>}</pre><p>When a <strong>class implements an interface</strong>, we use:</p><pre>implements</pre><p>Example:</p><pre>class Dog implements Animal {<br>}</pre><p>When an <strong>interface inherits from another interface</strong>, we use:</p><pre>extends</pre><p>Example:</p><pre>interface Animal {<br>    void sound();<br>}</pre><pre>interface Pet extends Animal {<br>    void play();<br>}</pre><p>So remember:</p><pre>Class → Class<br>extends</pre><pre>Class → Interface<br>implements</pre><pre>Interface → Interface<br>extends</pre><h3>Why Do We Need Interfaces?</h3><p>This is probably the most important question.</p><p>Imagine we are building a payment system.</p><p>We have different ways to make payments:</p><pre>Payment<br>   |<br>   ├── UPI<br>   ├── Credit Card<br>   └── Net Banking</pre><p>We can create an interface:</p><pre>interface Payment {</pre><pre>    void pay();<br>}</pre><p>Now different classes can implement it:</p><pre>class UPI implements Payment {</pre><pre>    @Override<br>    public void pay() {<br>        System.out.println(&quot;Payment using UPI&quot;);<br>    }<br>}</pre><pre>class CreditCard implements Payment {</pre><pre>    @Override<br>    public void pay() {<br>        System.out.println(&quot;Payment using Credit Card&quot;);<br>    }<br>}</pre><pre>class NetBanking implements Payment {</pre><pre>    @Override<br>    public void pay() {<br>        System.out.println(&quot;Payment using Net Banking&quot;);<br>    }<br>}</pre><p>Now all payment classes follow the same contract:</p><pre>Payment<br>   |<br>   ├── UPI<br>   ├── CreditCard<br>   └── NetBanking</pre><p>Every payment class must provide:</p><pre>pay()</pre><h3>The Real Power of Interfaces</h3><p>Suppose we have:</p><pre>void makePayment(Payment payment) {<br>    payment.pay();<br>}</pre><p>Now we can pass:</p><pre>makePayment(new UPI());<br>makePayment(new CreditCard());<br>makePayment(new NetBanking());</pre><p>We don’t need separate methods like:</p><pre>makeUPIPayment()<br>makeCreditCardPayment()<br>makeNetBankingPayment()</pre><p>Our code depends on the <strong>Payment interface</strong>, not on a specific implementation.</p><p>This is called <strong>programming to an interface</strong>.</p><p>It gives us flexibility.</p><p>Tomorrow, if we add:</p><pre>class Wallet implements Payment {</pre><pre>    @Override<br>    public void pay() {<br>        System.out.println(&quot;Payment using Wallet&quot;);<br>    }<br>}</pre><p>we can simply do:</p><pre>makePayment(new Wallet());</pre><p>The existing makePayment() method does not need to change.</p><p>This is one of the major reasons interfaces are heavily used in real-world Java applications and frameworks such as Spring.</p><h3>Multiple Interfaces</h3><p>One major advantage of interfaces is that a class can implement <strong>multiple interfaces</strong>.</p><p>For example:</p><pre>interface Camera {<br>    void takePhoto();<br>}</pre><pre>interface GPS {<br>    void navigate();<br>}</pre><p>A class can implement both:</p><pre>class Smartphone implements Camera, GPS {</pre><pre>    @Override<br>    public void takePhoto() {<br>        System.out.println(&quot;Taking photo&quot;);<br>    }</pre><pre>    @Override<br>    public void navigate() {<br>        System.out.println(&quot;Navigating&quot;);<br>    }<br>}</pre><p>Now:</p><pre>Smartphone phone = new Smartphone();</pre><pre>phone.takePhoto();<br>phone.navigate();</pre><p>This is allowed.</p><p>Java does not support multiple inheritance using classes:</p><pre>class C extends A, B</pre><p>But Java allows a class to implement multiple interfaces:</p><pre>class C implements A, B</pre><p>This gives Java a way to achieve multiple types/contracts without the ambiguity associated with multiple class inheritance.</p><h3>Interface Variables</h3><p>Variables declared inside an interface are automatically:</p><pre>public static final</pre><p>For example:</p><pre>interface Constants {</pre><pre>    int MAX_USERS = 100;<br>}</pre><p>This is effectively:</p><pre>public static final int MAX_USERS = 100;</pre><p>So we can access it using:</p><pre>Constants.MAX_USERS</pre><h3>Default Methods in Interfaces</h3><p>Modern Java allows interfaces to contain default methods.</p><p>A default method has an implementation.</p><pre>interface Animal {</pre><pre>    void sound();</pre><pre>    default void eat() {<br>        System.out.println(&quot;Animal is eating&quot;);<br>    }<br>}</pre><p>Now a class implementing the interface only needs to implement the abstract method:</p><pre>class Dog implements Animal {</pre><pre>    @Override<br>    public void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>And it can directly use:</p><pre>Dog dog = new Dog();</pre><pre>dog.sound();<br>dog.eat();</pre><p>Why were default methods introduced?</p><p>Imagine an interface already has hundreds of classes implementing it.</p><p>If we add a new abstract method, every existing class would have to implement it.</p><p>That could break existing code.</p><p>A default method allows an interface to add behaviour while providing a default implementation.</p><h3>Static Methods in Interfaces</h3><p>Interfaces can also contain static methods.</p><pre>interface Calculator {</pre><pre>    static int add(int a, int b) {<br>        return a + b;<br>    }<br>}</pre><p>We call it using the interface name:</p><pre>int result = Calculator.add(10, 20);</pre><h3>Functional Interface</h3><p>A <strong>functional interface</strong> is an interface that contains exactly <strong>one abstract method</strong>.</p><p>For example:</p><pre>@FunctionalInterface<br>interface Calculator {</pre><pre>    int add(int a, int b);<br>}</pre><p>The @FunctionalInterface annotation tells the compiler that this interface is intended to be a functional interface.</p><p>If we accidentally add another abstract method:</p><pre>@FunctionalInterface<br>interface Calculator {</pre><pre>    int add(int a, int b);</pre><pre>    int subtract(int a, int b);<br>}</pre><p>Java will give a compilation error.</p><p>A functional interface can still contain default and static methods. The important rule is that it must have exactly <strong>one abstract method</strong>.</p><h3>Why Do We Need Functional Interfaces?</h3><p>Functional interfaces are heavily used with <strong>lambda expressions</strong>.</p><p>Instead of creating a complete class:</p><pre>class CalculatorImpl implements Calculator {</pre><pre>    @Override<br>    public int add(int a, int b) {<br>        return a + b;<br>    }<br>}</pre><p>we can use a lambda:</p><pre>Calculator calculator = (a, b) -&gt; a + b;</pre><p>Then:</p><pre>System.out.println(calculator.add(10, 20));</pre><p>Output:</p><pre>30</pre><p>So functional interfaces are one of the foundations of <strong>lambda expressions and functional programming in Java</strong>.</p><p>Common built-in functional interfaces include:</p><pre>Predicate&lt;T&gt;<br>Function&lt;T, R&gt;<br>Consumer&lt;T&gt;<br>Supplier&lt;T&gt;</pre><p>For example:</p><pre>Predicate&lt;Integer&gt; isEven = number -&gt; number % 2 == 0;</pre><h3>Inner Classes</h3><p>Now let’s talk about inner classes.</p><p>An <strong>inner class is a class defined inside another class</strong>.</p><p>For example:</p><pre>class Outer {</pre><pre>    class Inner {</pre><pre>        void display() {<br>            System.out.println(&quot;Inner class&quot;);<br>        }<br>    }<br>}</pre><p>Here:</p><pre>Outer<br>  |<br>  └── Inner</pre><p>Inner is defined inside Outer.</p><p>We can create an inner class object like this:</p><pre>Outer outer = new Outer();</pre><pre>Outer.Inner inner = outer.new Inner();</pre><pre>inner.display();</pre><h3>Why Do We Use Inner Classes?</h3><p>Inner classes are useful when a class is closely related to another class and doesn’t need to be used independently.</p><p>For example, suppose Car has an Engine.</p><pre>class Car {</pre><pre>    class Engine {</pre><pre>        void start() {<br>            System.out.println(&quot;Engine started&quot;);<br>        }<br>    }<br>}</pre><p>The Engine is closely associated with the Car.</p><p>Inner classes can also access members of their enclosing class, including private members.</p><h3>Static Nested Class</h3><p>We can make a nested class static.</p><pre>class Outer {</pre><pre>    static class Inner {</pre><pre>        void display() {<br>            System.out.println(&quot;Static nested class&quot;);<br>        }<br>    }<br>}</pre><p>Now we don’t need an Outer object to create the Inner object:</p><pre>Outer.Inner obj = new Outer.Inner();</pre><pre>obj.display();</pre><p>This is called a <strong>static nested class</strong>.</p><p>Important point:</p><blockquote><em>Technically, a </em><em>static nested class is called a static nested class rather than a non-static inner class.</em></blockquote><p>Java allows:</p><pre>class Outer {<br>    static class Inner {<br>    }<br>}</pre><p>But we cannot make a <strong>top-level class</strong> static.</p><p>This is invalid:</p><pre>static class Outer {<br>}</pre><h3>Anonymous Inner Class</h3><p>Now let’s talk about an anonymous inner class.</p><p>An anonymous inner class is a class <strong>without a name</strong> that is created and used at the same time.</p><p>For example:</p><pre>interface Animal {</pre><pre>    void sound();<br>}</pre><p>Normally, we could create a class:</p><pre>class Dog implements Animal {</pre><pre>    @Override<br>    public void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>But if we only need this implementation once, creating a separate class can be unnecessary.</p><p>Instead, we can use an anonymous class:</p><pre>Animal animal = new Animal() {</pre><pre>    @Override<br>    public void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>};</pre><p>Notice:</p><pre>new Animal() {<br>    ...<br>};</pre><p>We are creating an implementation of Animal, but we haven&#39;t given the class a name.</p><p>That’s why it is called an <strong>anonymous class</strong>.</p><p>We can then call:</p><pre>animal.sound();</pre><p>Output:</p><pre>Dog barks</pre><h3>When Do We Use Anonymous Classes?</h3><p>Anonymous classes are useful when:</p><ul><li>We need an implementation only once.</li><li>We don’t want to create a separate named class.</li><li>We need to quickly customize a class or interface behaviour.</li></ul><p>They were especially common before lambda expressions were introduced.</p><p>For example, if we have a functional interface, a lambda is usually cleaner:</p><h3>Anonymous class</h3><pre>Calculator calculator = new Calculator() {</pre><pre>    @Override<br>    public int add(int a, int b) {<br>        return a + b;<br>    }<br>};</pre><h3>Lambda</h3><pre>Calculator calculator = (a, b) -&gt; a + b;</pre><p>For a functional interface, the lambda is usually much shorter and easier to read.</p><h3>Abstract Class vs Interface</h3><p>This is a very common interview question.</p><p>A simple way to think about it is:</p><blockquote><strong><em>Abstract class = what the related classes have in common</em></strong></blockquote><blockquote><strong><em>Interface = what a class promises that it can do</em></strong></blockquote><p>For example:</p><pre>Vehicle<br>   |<br>   ├── Car<br>   └── Bike</pre><p>An abstract Vehicle class could contain common things such as:</p><pre>int speed;</pre><pre>void start() {<br>    System.out.println(&quot;Starting&quot;);<br>}</pre><p>But an interface could describe a capability:</p><pre>interface Flyable {<br>    void fly();<br>}</pre><p>Then a class can implement it:</p><pre>class Airplane implements Flyable {</pre><pre>    @Override<br>    public void fly() {<br>        System.out.println(&quot;Airplane is flying&quot;);<br>    }<br>}</pre><p>A class can also implement multiple capabilities:</p><pre>class FlyingCar extends Vehicle implements Flyable, GPS {</pre><pre>}</pre><h3>Final Picture</h3><p>All these concepts connect together:</p><pre>ABSTRACTION<br>                        |<br>              ┌─────────┴─────────┐<br>              |                   |<br>        Abstract Class        Interface<br>              |                   |<br>           extends             implements<br>              |                   |<br>        Concrete Class        Concrete Class<br>                                  |<br>                         Multiple Interfaces</pre><p>And inside classes we can have:</p><pre>Class<br> |<br> ├── Inner Class<br> |<br> ├── Static Nested Class<br> |<br> └── Anonymous Inner Class</pre><p>And for interfaces:</p><pre>Interface<br>    |<br>    └── Functional Interface<br>             |<br>             └── Lambda Expression</pre><p>The most important things to remember are:</p><pre>abstract class<br>    ↓<br>Cannot directly create an object<br>Can contain abstract + concrete methods</pre><pre>interface<br>    ↓<br>Defines a contract<br>Class uses implements<br>Interface uses extends<br>Class can implement multiple interfaces</pre><pre>inner class<br>    ↓<br>Class inside another class</pre><pre>static nested class<br>    ↓<br>Nested class that does not require an outer-class object</pre><pre>anonymous class<br>    ↓<br>Unnamed class created for one-time use</pre><pre>functional interface<br>    ↓<br>Exactly one abstract method<br>Can be used with lambda expressions</pre><p>So the overall purpose of these concepts is to help us write Java programs that are <strong>more flexible, reusable, maintainable, and loosely coupled</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2afb3312852" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Java : Enums in Java]]></title>
            <link>https://medium.com/@aishureddy/core-java-enums-in-java-b7fc05192637?source=rss-04ef0daaee11------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7fc05192637</guid>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[Aishu Reddy]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 06:36:06 GMT</pubDate>
            <atom:updated>2026-10-09T06:36:06.276Z</atom:updated>
            <content:encoded><![CDATA[<p>An <strong>enum</strong> is used when we have a fixed set of values.</p><p>For example, suppose we have an application where an order can have only a few possible statuses:</p><pre>RUNNING<br>PROCESSING<br>COMPLETED<br>FAILED</pre><p>Instead of storing these as random strings, Java allows us to define an enum:</p><pre>enum Status {<br>    RUNNING,<br>    PROCESSING,<br>    COMPLETED,<br>    FAILED<br>}</pre><p>We can use it like this:</p><pre>Status status = Status.RUNNING;</pre><p>Here, RUNNING, PROCESSING, COMPLETED, and FAILED are called <strong>enum constants</strong>.</p><p>They are actually instances (objects) of the Status enum type.</p><h3>Enum with Values</h3><p>Enums can also have their own variables, constructors and methods.</p><p>For example:</p><pre>enum Status {</pre><pre>    RUNNING(500),<br>    PROCESSING(100),<br>    COMPLETED(200);</pre><pre>    private int code;</pre><pre>    Status(int code) {<br>        this.code = code;<br>    }</pre><pre>    public int getCode() {<br>        return code;<br>    }<br>}</pre><p>Now:</p><pre>Status status = Status.RUNNING;</pre><pre>System.out.println(status.getCode());</pre><p>Output:</p><pre>500</pre><p>Here:</p><pre>RUNNING(500)<br>PROCESSING(100)<br>COMPLETED(200)</pre><p>are enum constants, and each constant is created using the constructor.</p><p>So we can think of it like:</p><pre>Status<br> ├── RUNNING      -&gt; code = 500<br> ├── PROCESSING   -&gt; code = 100<br> └── COMPLETED    -&gt; code = 200</pre><p>The constructor:</p><pre>Status(int code) {<br>    this.code = code;<br>}</pre><p>is called when the enum constants are created.</p><p>Enum constructors are implicitly private, so we cannot create enum objects using new.</p><p>For example, this is not allowed:</p><pre>Status s = new Status(500); // Error</pre><h3>Can an Enum Have Methods?</h3><p>Yes!</p><p>An enum can contain:</p><ul><li>Variables</li><li>Constructors</li><li>Methods</li><li>Abstract methods</li><li>Static methods</li></ul><p>For example:</p><pre>enum Status {</pre><pre>    RUNNING(500),<br>    PROCESSING(100),<br>    COMPLETED(200);</pre><pre>    private int code;</pre><pre>    Status(int code) {<br>        this.code = code;<br>    }</pre><pre>    public int getCode() {<br>        return code;<br>    }</pre><pre>    public boolean isCompleted() {<br>        return this == COMPLETED;<br>    }<br>}</pre><p>Now:</p><pre>Status status = Status.COMPLETED;</pre><pre>System.out.println(status.getCode());<br>System.out.println(status.isCompleted());</pre><p>Output:</p><pre>200<br>true</pre><h3>Useful Enum Methods</h3><p>Java provides some useful methods for enums.</p><h3>values()</h3><p>Returns all the enum constants.</p><pre>for (Status status : Status.values()) {<br>    System.out.println(status);<br>}</pre><p>Output:</p><pre>RUNNING<br>PROCESSING<br>COMPLETED</pre><h3>valueOf()</h3><p>Converts a string into the corresponding enum constant.</p><pre>Status status = Status.valueOf(&quot;RUNNING&quot;);</pre><pre>System.out.println(status);</pre><p>Output:</p><pre>RUNNING</pre><p>If the string does not exactly match an enum constant, valueOf() throws an IllegalArgumentException.</p><h3>name()</h3><p>Returns the name of the enum constant.</p><pre>Status status = Status.RUNNING;</pre><pre>System.out.println(status.name());</pre><p>Output:</p><pre>RUNNING</pre><h3>ordinal()</h3><p>Returns the position of the enum constant, starting from 0.</p><pre>System.out.println(Status.RUNNING.ordinal());<br>System.out.println(Status.PROCESSING.ordinal());</pre><p>Output:</p><pre>0<br>1</pre><p>However, we should generally <strong>not use </strong><strong>ordinal() as a database ID or business value</strong>, because changing the order of enum constants changes their ordinal values.</p><h3>Annotations in Java</h3><p>Annotations provide <strong>metadata or additional information about code</strong>.</p><p>They start with @.</p><p>For example:</p><pre>@Override</pre><p>Annotations can be used on classes, methods, fields, parameters, etc., depending on what the annotation allows.</p><p>One important thing to understand is that an annotation usually <strong>does not itself execute the code</strong>. Instead, the compiler, JVM, framework, or another tool can read the annotation and take some action based on it.</p><h3>@Override</h3><p>We have already seen this while discussing method overriding.</p><pre>class Animal {</pre><pre>    void sound() {<br>        System.out.println(&quot;Animal makes sound&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>@Override tells the compiler:</p><blockquote><em>“I intend to override a method from the parent class.”</em></blockquote><p>If we accidentally make a mistake:</p><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sounds() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>The compiler will complain because sounds() does not actually override the parent&#39;s sound() method.</p><p>So @Override helps us catch mistakes.</p><h3>@Deprecated</h3><p>This annotation tells developers that a method, class, or field should no longer be used.</p><pre>@Deprecated<br>public void oldMethod() {<br>    // old implementation<br>}</pre><p>When someone uses it, the compiler/IDE can show a warning.</p><h3>@SuppressWarnings</h3><p>This tells the compiler to suppress certain warnings.</p><p>For example:</p><pre>@SuppressWarnings(&quot;unchecked&quot;)</pre><p>It is commonly used when we know about a warning and intentionally want to suppress it.</p><h3>@FunctionalInterface</h3><p>This annotation is used for functional interfaces.</p><pre>@FunctionalInterface<br>interface Calculator {<br>    int add(int a, int b);<br>}</pre><p>The compiler makes sure that the interface has exactly one abstract method.</p><p>If we accidentally add another abstract method:</p><pre>@FunctionalInterface<br>interface Calculator {</pre><pre>    int add(int a, int b);</pre><pre>    int subtract(int a, int b);<br>}</pre><p>the compiler will report an error.</p><h3>Types of Interfaces</h3><p>We can broadly come across interfaces such as:</p><ol><li>Normal interface</li><li>Functional interface</li><li>Marker interface</li></ol><p>Let’s understand each one.</p><h3>1. Normal Interface</h3><p>A normal interface is used to define a <strong>contract</strong>.</p><p>For example:</p><pre>interface Payment {</pre><pre>    void pay();<br>}</pre><p>Different classes can provide different implementations:</p><pre>class UPI implements Payment {</pre><pre>    @Override<br>    public void pay() {<br>        System.out.println(&quot;Payment using UPI&quot;);<br>    }<br>}</pre><pre>class CreditCard implements Payment {</pre><pre>    @Override<br>    public void pay() {<br>        System.out.println(&quot;Payment using Credit Card&quot;);<br>    }<br>}</pre><p>Now we can use polymorphism:</p><pre>Payment payment = new UPI();<br>payment.pay();</pre><p>Output:</p><pre>Payment using UPI</pre><p>We could also do:</p><pre>Payment payment = new CreditCard();<br>payment.pay();</pre><p>Output:</p><pre>Payment using Credit Card</pre><p>This is one of the major reasons we use interfaces: <strong>we can program against a contract instead of depending on a specific implementation.</strong></p><p>For example:</p><pre>void makePayment(Payment payment) {<br>    payment.pay();<br>}</pre><p>Now this method can work with:</p><pre>makePayment(new UPI());<br>makePayment(new CreditCard());</pre><p>without changing the makePayment() method.</p><h3>2. Functional Interface</h3><p>A <strong>functional interface</strong> is an interface that has exactly <strong>one abstract method</strong>.</p><p>Example:</p><pre>@FunctionalInterface<br>interface Calculator {</pre><pre>    int calculate(int a, int b);<br>}</pre><p>It can have default, static, and private methods as well, but it must have only <strong>one abstract method</strong>.</p><p>The biggest advantage of a functional interface is that it can be used with <strong>lambda expressions</strong>.</p><p>Without a lambda:</p><pre>Calculator calculator = new Calculator() {</pre><pre>    @Override<br>    public int calculate(int a, int b) {<br>        return a + b;<br>    }<br>};</pre><p>With a lambda:</p><pre>Calculator calculator = (a, b) -&gt; a + b;</pre><p>Much shorter!</p><p>Java provides many built-in functional interfaces.</p><h3>Predicate</h3><p>Used when we want to check something and get true or false.</p><pre>Predicate&lt;Integer&gt; isEven = number -&gt; number % 2 == 0;</pre><pre>System.out.println(isEven.test(10));</pre><p>Output:</p><pre>true</pre><h3>Function</h3><p>Takes one input and produces one output.</p><pre>Function&lt;String, Integer&gt; length = str -&gt; str.length();</pre><pre>System.out.println(length.apply(&quot;Java&quot;));</pre><p>Output:</p><pre>4</pre><h3>Consumer</h3><p>Takes an input but does not return anything.</p><pre>Consumer&lt;String&gt; print = name -&gt; System.out.println(name);</pre><pre>print.accept(&quot;Aishu&quot;);</pre><h3>Supplier</h3><p>Does not take an input but produces a value.</p><pre>Supplier&lt;String&gt; message = () -&gt; &quot;Hello Java&quot;;</pre><pre>System.out.println(message.get());</pre><p>So a simple way to remember them is:</p><pre>Predicate  -&gt; input  -&gt; true/false<br>Function   -&gt; input  -&gt; output<br>Consumer   -&gt; input  -&gt; nothing<br>Supplier   -&gt; nothing -&gt; output</pre><h3>3. Marker Interface</h3><p>A <strong>marker interface</strong> is an interface that has <strong>no methods and no fields that define behavior</strong>.</p><p>It is used to mark a class and tell Java or a framework that the class has some special capability or should receive special treatment.</p><p>Example:</p><pre>interface MyMarker {<br>}</pre><p>A class can implement it:</p><pre>class Student implements MyMarker {<br>}</pre><p>The interface doesn’t contain a method that Student needs to implement.</p><p>So why do we need it?</p><p>The interface acts like a <strong>tag</strong> or <strong>marker</strong>.</p><p>One famous example is:</p><pre>Serializable</pre><h3>What is Serialization?</h3><p>Suppose we have an object:</p><pre>Student student = new Student(&quot;Aishu&quot;, 22);</pre><p>This object exists in memory while our Java program is running.</p><p>But what if we want to:</p><ul><li>save the object to a file</li><li>send the object over a network</li><li>store the object’s state somewhere</li><li>transfer the object between systems</li></ul><p>We need to convert the object into a format that can be stored or transferred.</p><p>This process is called <strong>serialization</strong>.</p><p>In simple words:</p><pre>Object<br>   ↓<br>Serialization<br>   ↓<br>Byte stream<br>   ↓<br>File / Network / Storage</pre><p>For Java’s built-in object serialization mechanism, a class implements:</p><pre>Serializable</pre><p>Example:</p><pre>import java.io.Serializable;</pre><pre>class Student implements Serializable {</pre><pre>    private String name;<br>    private int age;</pre><pre>    public Student(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>}</pre><p>Notice that Serializable does not require us to implement any method.</p><p>That’s why it is called a <strong>marker interface</strong>.</p><p>It tells Java:</p><blockquote><em>“Objects of this class are allowed to participate in Java’s serialization mechanism.”</em></blockquote><h3>Serialization Example</h3><pre>Student student = new Student(&quot;Aishu&quot;, 22);</pre><pre>ObjectOutputStream output =<br>        new ObjectOutputStream(new FileOutputStream(&quot;student.ser&quot;));</pre><pre>output.writeObject(student);<br>output.close();</pre><p>The object is converted into a byte stream and written to the file.</p><h3>What is Deserialization?</h3><p>Deserialization is the reverse process.</p><p>We take the serialized byte stream and convert it back into an object.</p><pre>File / Network<br>      ↓<br>Byte stream<br>      ↓<br>Deserialization<br>      ↓<br>Java Object</pre><p>Example:</p><pre>ObjectInputStream input =<br>        new ObjectInputStream(new FileInputStream(&quot;student.ser&quot;));</pre><pre>Student student = (Student) input.readObject();</pre><pre>input.close();</pre><p>Now student is again a Java object.</p><p>So the easiest way to remember is:</p><pre>Serialization<br>Object → Byte Stream</pre><pre>Deserialization<br>Byte Stream → Object</pre><h3>Why is Serializable called a Marker Interface?</h3><p>Because it doesn’t contain methods that we need to implement.</p><pre>public interface Serializable {<br>}</pre><p>It simply marks a class as being eligible for Java’s serialization mechanism.</p><p>Other examples of marker interfaces include:</p><pre>Serializable<br>Cloneable<br>RandomAccess</pre><p>For example, Cloneable indicates that an object&#39;s clone() operation is permitted by Java&#39;s cloning mechanism.</p><h3>One Important Point About Interfaces</h3><p>An interface is <strong>not limited to only abstract methods</strong> in modern Java.</p><p>We can have:</p><pre>interface Payment {</pre><pre>    void pay();                 // abstract method</pre><pre>    default void receipt() {    // default method<br>        System.out.println(&quot;Receipt generated&quot;);<br>    }</pre><pre>    static void help() {        // static method<br>        System.out.println(&quot;Payment help&quot;);<br>    }<br>}</pre><p>So when learning interfaces, remember:</p><pre>Interface<br>   |<br>   ├── Abstract methods<br>   ├── Default methods<br>   ├── Static methods<br>   └── Private methods</pre><p>The main purpose of an interface is still to define a <strong>contract/capability</strong>, while modern Java gives interfaces some additional behavior through default, static, and private methods.</p><h3>Simple Summary</h3><pre>Enum<br>   → Represents a fixed set of constants<br>   → Each constant is an instance of the enum<br>   → Can have variables, constructors and methods</pre><pre>Annotation<br>   → Provides metadata/information<br>   → Examples: @Override, @Deprecated, @SuppressWarnings</pre><pre>Normal Interface<br>   → Defines a contract<br>   → A class can implement it</pre><pre>Functional Interface<br>   → Exactly one abstract method<br>   → Can be used with lambda expressions<br>   → Example: Predicate, Function, Consumer, Supplier</pre><pre>Marker Interface<br>   → No abstract methods<br>   → Used as a marker/tag<br>   → Example: Serializable</pre><pre>Serialization<br>   → Object → Byte Stream</pre><pre>Deserialization<br>   → Byte Stream → Object</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7fc05192637" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Java: Static and Final Keywords in Java]]></title>
            <link>https://medium.com/@aishureddy/core-java-static-and-final-keywords-in-java-5ce0a144afae?source=rss-04ef0daaee11------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ce0a144afae</guid>
            <category><![CDATA[static-keyword]]></category>
            <category><![CDATA[static]]></category>
            <category><![CDATA[final-keyword]]></category>
            <category><![CDATA[final-keyword-in-java]]></category>
            <dc:creator><![CDATA[Aishu Reddy]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 06:57:51 GMT</pubDate>
            <atom:updated>2026-10-07T06:57:51.324Z</atom:updated>
            <content:encoded><![CDATA[<p>Now let’s talk about two important keywords in Java:</p><ul><li>static</li><li>final</li></ul><p>They are used for very different purposes.</p><p>The easiest way to remember them is:</p><blockquote><strong><em>static → belongs to the class</em></strong></blockquote><blockquote><strong><em>final → cannot be changed further</em></strong></blockquote><h3>Static Keyword</h3><p>The static keyword is used when something should belong to the <strong>class rather than to individual objects</strong>.</p><p>Normally, when we create objects, every object gets its own copy of instance variables.</p><p>For example:</p><pre>class Student {</pre><pre>    String name;<br>    int age;<br>}</pre><p>If we create two students:</p><pre>Student s1 = new Student();<br>Student s2 = new Student();</pre><pre>s1.name = &quot;Aishu&quot;;<br>s2.name = &quot;Rahul&quot;;</pre><p>Both objects have their own name.</p><pre>s1 → name = Aishu<br>s2 → name = Rahul</pre><p>Changing s1.name does not affect s2.name.</p><p>But sometimes we want a value that is <strong>common to all objects</strong>.</p><p>That’s where static comes in.</p><h3>Static Variable</h3><p>A static variable belongs to the <strong>class</strong>, not to individual objects.</p><p>For example, suppose every student belongs to the same school:</p><pre>class Student {</pre><pre>    String name;<br>    static String school = &quot;ABC School&quot;;<br>}</pre><p>Now:</p><pre>Student s1 = new Student();<br>Student s2 = new Student();</pre><pre>s1.name = &quot;Aishu&quot;;<br>s2.name = &quot;Rahul&quot;;</pre><p>Both students share the same school variable.</p><p>We should access it using the class name:</p><pre>Student.school</pre><p>So:</p><pre>System.out.println(Student.school);</pre><p>Output:</p><pre>ABC School</pre><p>There is only <strong>one copy</strong> of the static variable for the class, rather than one copy for every object.</p><h3>What happens if we change a static variable?</h3><p>This is an important point.</p><pre>class Student {</pre><pre>    String name;<br>    static String school = &quot;ABC School&quot;;<br>}</pre><p>Now:</p><pre>Student s1 = new Student();<br>Student s2 = new Student();</pre><pre>Student.school = &quot;XYZ School&quot;;</pre><p>Now both objects see:</p><pre>XYZ School</pre><p>because they are sharing the same static variable.</p><p>Conceptually:</p><pre>Student Class<br>                   |<br>             school = XYZ School<br>                /       \<br>               /         \<br>             s1           s2</pre><p>There is one shared school variable.</p><h3>Static Variables Should Be Accessed Using the Class Name</h3><p>Since a static variable belongs to the class, the preferred way to access it is:</p><pre>Student.school</pre><p>rather than:</p><pre>s1.school</pre><p>Java technically allows accessing a static member through an object reference, but it is <strong>not recommended</strong>, because it can make it look like the variable belongs to that particular object.</p><p>Prefer:</p><pre>Student.school;</pre><h3>Static Method</h3><p>We can also make methods static.</p><p>Example:</p><pre>class Calculator {</pre><pre>    static int add(int a, int b) {<br>        return a + b;<br>    }<br>}</pre><p>We don’t need to create a Calculator object to call this method.</p><p>We can directly do:</p><pre>int result = Calculator.add(10, 20);</pre><p>because the method belongs to the class.</p><h3>Why can’t a static method directly access instance variables?</h3><p>This is an important concept.</p><p>Suppose we have:</p><pre>class Student {</pre><pre>    String name;</pre><pre>    static void display() {<br>        System.out.println(name);<br>    }<br>}</pre><p>This will give a compilation error.</p><p>Why?</p><p>Because name is an <strong>instance variable</strong>.</p><p>Every object has its own name:</p><pre>s1 → name = Aishu<br>s2 → name = Rahul</pre><p>But a static method belongs to the class.</p><p>If we call:</p><pre>Student.display();</pre><p>Java doesn’t know:</p><blockquote><em>“Which student’s </em><em>name should I use?&quot;</em></blockquote><p>Should it use Aishu?</p><p>Or Rahul?</p><p>There is no particular object associated with the static method call.</p><p>Therefore, a static method <strong>cannot directly access instance variables or instance methods</strong>.</p><p>It can directly access static members.</p><p>For example:</p><pre>class Student {</pre><pre>    static String school = &quot;ABC School&quot;;</pre><pre>    static void displaySchool() {<br>        System.out.println(school);<br>    }<br>}</pre><p>This works because both school and displaySchool() belong to the class.</p><h3>But remember:</h3><p>A static method <strong>can access an instance variable if it is given an object reference</strong>.</p><p>For example:</p><pre>class Student {</pre><pre>    String name;</pre><pre>    static void display(Student student) {<br>        System.out.println(student.name);<br>    }<br>}</pre><p>Here we explicitly tell the method which object to use.</p><h3>Static Block</h3><p>A static block is a block of code declared using the static keyword.</p><p>Example:</p><pre>class Student {</pre><pre>    static {<br>        System.out.println(&quot;Static block executed&quot;);<br>    }<br>}</pre><p>A static block is mainly used for <strong>static initialization</strong>.</p><p>For example:</p><pre>class Database {</pre><pre>    static String url;</pre><pre>    static {<br>        url = &quot;jdbc:mysql://localhost:3306/test&quot;;<br>        System.out.println(&quot;Database configuration loaded&quot;);<br>    }<br>}</pre><p>The static block executes when the class is initialized.</p><h3>When does a Static Block Execute?</h3><p>A static block executes when the class is <strong>initialized by the JVM</strong>, generally before the class is used to create objects or access its static members.</p><p>For example:</p><pre>class Test {</pre><pre>    static {<br>        System.out.println(&quot;Static block&quot;);<br>    }</pre><pre>    Test() {<br>        System.out.println(&quot;Constructor&quot;);<br>    }<br>}</pre><p>Now:</p><pre>Test obj = new Test();</pre><p>Output:</p><pre>Static block<br>Constructor</pre><p>The static initialization happens before the constructor.</p><h3>Static Block vs Constructor</h3><p>This is a very important difference.</p><h3>Static block</h3><ul><li>Belongs to the class</li><li>Runs when the class is initialized</li><li>Generally runs once per class initialization</li><li>Used for static initialization</li></ul><h3>Constructor</h3><ul><li>Belongs to object creation</li><li>Runs whenever an object is created</li><li>Used to initialize an object</li></ul><p>For example:</p><pre>class Test {</pre><pre>    static {<br>        System.out.println(&quot;Static block&quot;);<br>    }</pre><pre>    Test() {<br>        System.out.println(&quot;Constructor&quot;);<br>    }<br>}</pre><p>If we create two objects:</p><pre>Test t1 = new Test();<br>Test t2 = new Test();</pre><p>Output will generally be:</p><pre>Static block<br>Constructor<br>Constructor</pre><p>The static initialization happens once, while the constructor runs for each object.</p><h3>Class.forName()</h3><p>You mentioned:</p><pre>Class.forName(&quot;classname&quot;);</pre><p>This is another interesting concept.</p><p>Class.forName() loads a class using its fully qualified class name.</p><p>For example:</p><pre>Class.forName(&quot;com.example.Student&quot;);</pre><p>This is commonly associated with <strong>loading and initializing a class dynamically</strong>.</p><p>One important point: Class.forName() can trigger class initialization, so static initialization code can run.</p><p>For example:</p><pre>class Test {</pre><pre>    static {<br>        System.out.println(&quot;Test class initialized&quot;);<br>    }<br>}</pre><p>Then:</p><pre>Class.forName(&quot;Test&quot;);</pre><p>can cause:</p><pre>Test class initialized</pre><p>to be printed when the class is initialized.</p><p>Historically, Class.forName() was commonly used for loading JDBC drivers, although modern JDBC drivers can often be discovered automatically through the JDBC driver mechanism.</p><h3>Static Nested Class</h3><p>There is one important correction regarding <strong>static class</strong>.</p><p>In Java, we <strong>cannot declare a top-level class as </strong><strong>static</strong>.</p><p>This is invalid:</p><pre>static class Student {<br>}</pre><p>However, we can have a <strong>static nested class</strong> inside another class.</p><p>For example:</p><pre>class Outer {</pre><pre>    static class Inner {</pre><pre>        void display() {<br>            System.out.println(&quot;Inner class&quot;);<br>        }<br>    }<br>}</pre><p>Now we can create the nested class without creating an object of Outer:</p><pre>Outer.Inner obj = new Outer.Inner();</pre><pre>obj.display();</pre><p>A static nested class belongs to the outer class rather than to an instance of the outer class.</p><h3>Final Keyword</h3><p>Now let’s talk about the final keyword.</p><p>The final keyword is used when we want something to <strong>not be changed further</strong>.</p><p>It can be used with:</p><ul><li>Variables</li><li>Methods</li><li>Classes</li></ul><h3>Final Variable</h3><p>A final variable can be assigned only once.</p><pre>final int age = 25;</pre><p>Now we cannot do:</p><pre>age = 30;</pre><p>This gives a compilation error.</p><p>Once a final variable has been assigned a value, it cannot be reassigned.</p><h3>Final Variables Without Immediate Initialization</h3><p>A final variable doesn’t necessarily need to be initialized on the same line.</p><p>For example:</p><pre>final int age;</pre><pre>age = 25;</pre><p>This is valid as long as it is assigned exactly once before it is used.</p><p>For instance variables, such a variable is often called a <strong>blank final variable</strong> and can be initialized in a constructor.</p><pre>class Student {</pre><pre>    final int id;</pre><pre>    Student(int id) {<br>        this.id = id;<br>    }<br>}</pre><p>Now:</p><pre>Student s1 = new Student(101);<br>Student s2 = new Student(102);</pre><p>Each object can have a different id, but once assigned, that object&#39;s id cannot be reassigned.</p><h3>Final Static Variable</h3><p>A very common combination is:</p><pre>static final</pre><p>This is used for constants.</p><p>For example:</p><pre>class Constants {</pre><pre>    static final double PI = 3.14159;<br>}</pre><p>Now we access it using:</p><pre>Constants.PI</pre><p>Because:</p><ul><li>static → belongs to the class</li><li>final → cannot be reassigned</li></ul><p>By convention, constants are written in <strong>UPPERCASE</strong>:</p><pre>static final int MAX_USERS = 100;</pre><h3>Final Method</h3><p>A final method <strong>cannot be overridden</strong> by a child class.</p><p>Example:</p><pre>class Parent {</pre><pre>    final void display() {<br>        System.out.println(&quot;Parent method&quot;);<br>    }<br>}</pre><p>Now:</p><pre>class Child extends Parent {</pre><pre>    void display() {<br>        System.out.println(&quot;Child method&quot;);<br>    }<br>}</pre><p>This will result in a compilation error because display() is final in the parent.</p><p>Why would we want this?</p><p>Because sometimes we want to make sure that a particular method’s implementation <strong>cannot be changed by subclasses</strong>.</p><h3>Final Class</h3><p>A final class <strong>cannot be extended</strong>.</p><p>Example:</p><pre>final class Vehicle {</pre><pre>    void start() {<br>        System.out.println(&quot;Vehicle starts&quot;);<br>    }<br>}</pre><p>Now this is not allowed:</p><pre>class Car extends Vehicle {<br>}</pre><p>because Vehicle is final.</p><p>A common example from Java is:</p><pre>public final class String</pre><p>The String class is final, so we cannot create a subclass of String.</p><h3>Static vs Final</h3><p>These keywords solve completely different problems.</p><h3>static</h3><p>Answers:</p><blockquote><em>“Should this belong to the class rather than each object?”</em></blockquote><p>Example:</p><pre>static int count;</pre><h3>final</h3><p>Answers:</p><blockquote><em>“Should this value/implementation/class be prevented from changing?”</em></blockquote><p>Example:</p><pre>final int age = 25;</pre><p>Together:</p><pre>static final int MAX_USERS = 100;</pre><p>means:</p><blockquote><em>This value belongs to the class and cannot be reassigned.</em></blockquote><h3>One More Important Example: Static Object Counter</h3><p>A very common real-world use of static is counting how many objects have been created.</p><pre>class Student {</pre><pre>    static int count = 0;</pre><pre>    Student() {<br>        count++;<br>    }<br>}</pre><p>Now:</p><pre>Student s1 = new Student();<br>Student s2 = new Student();<br>Student s3 = new Student();</pre><pre>System.out.println(Student.count);</pre><p>Output:</p><pre>3</pre><p>Why?</p><p>Because count is shared by all objects.</p><p>Each constructor call increments the <strong>same static variable</strong>.</p><pre>Student Class<br>     |<br> count = 3<br>   / | \<br>  /  |  \<br>s1  s2  s3</pre><p>If count were not static, every object would have its own separate counter, and this approach would not work.</p><h3>Final Summary</h3><p>The easiest way to remember is:</p><pre>static<br>   ↓<br>Belongs to the CLASS</pre><pre>final<br>   ↓<br>Cannot be changed / extended / overridden</pre><p>So when you see:</p><pre>static final int MAX_LIMIT = 100;</pre><p>you can read it as:</p><blockquote><em>MAX_LIMIT belongs to the class, and its reference/value cannot be reassigned.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ce0a144afae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Java: Polymorphism in Java]]></title>
            <link>https://medium.com/@aishureddy/core-java-polymorphism-in-java-5a81b1e7033d?source=rss-04ef0daaee11------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a81b1e7033d</guid>
            <category><![CDATA[dynamic-dispatch]]></category>
            <category><![CDATA[polymorphism]]></category>
            <dc:creator><![CDATA[Aishu Reddy]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 06:57:09 GMT</pubDate>
            <atom:updated>2026-10-07T06:57:09.258Z</atom:updated>
            <content:encoded><![CDATA[<p>The word <strong>polymorphism</strong> comes from two words:</p><ul><li><strong>Poly</strong> → Many</li><li><strong>Morphism</strong> → Forms or behaviours</li></ul><p>So, polymorphism basically means <strong>one thing can have many forms or behaviours</strong>.</p><p>In Java, polymorphism allows the same method name or reference to behave differently depending on the situation.</p><p>There are two main types of polymorphism in Java:</p><ol><li><strong>Compile-time polymorphism</strong></li><li><strong>Runtime polymorphism</strong></li></ol><h3>1. Compile-Time Polymorphism</h3><p>Compile-time polymorphism is also called <strong>static polymorphism</strong>.</p><p>Here, Java decides which method needs to be called <strong>at compile time</strong>.</p><p>This is achieved using <strong>method overloading</strong>.</p><h3>Method Overloading</h3><p>Method overloading means having multiple methods with the <strong>same name but different parameters</strong> in the same class.</p><p>For example:</p><pre>class Calculator {</pre><pre>    int add(int a, int b) {<br>        return a + b;<br>    }</pre><pre>    int add(int a, int b, int c) {<br>        return a + b + c;<br>    }</pre><pre>    double add(double a, double b) {<br>        return a + b;<br>    }<br>}</pre><p>Here we have three add() methods.</p><p>Their names are the same, but their parameter lists are different.</p><pre>Calculator calculator = new Calculator();</pre><pre>calculator.add(10, 20);<br>calculator.add(10, 20, 30);<br>calculator.add(10.5, 20.5);</pre><p>Java can determine which method to call based on the arguments we provide.</p><p>For example:</p><pre>calculator.add(10, 20);</pre><p>Java sees two int arguments, so it chooses:</p><pre>add(int a, int b)</pre><p>Whereas:</p><pre>calculator.add(10, 20, 30);</pre><p>has three arguments, so Java chooses:</p><pre>add(int a, int b, int c)</pre><p>This decision is made during <strong>compile time</strong>, which is why it is called compile-time polymorphism.</p><h3>Important point</h3><p>Method overloading can be done by changing:</p><ul><li>Number of parameters</li><li>Type of parameters</li><li>Order of parameters</li></ul><p>For example:</p><pre>void display(int a, String b)<br>void display(String a, int b)</pre><p>But we <strong>cannot overload a method only by changing its return type</strong>.</p><p>This is not valid:</p><pre>int add(int a, int b)<br>double add(int a, int b)</pre><p>because the parameter list is exactly the same.</p><h3>2. Runtime Polymorphism</h3><p>Runtime polymorphism is also called <strong>dynamic polymorphism</strong>.</p><p>In runtime polymorphism, Java decides which method to execute <strong>at runtime</strong>.</p><p>Runtime polymorphism is achieved through <strong>method overriding</strong>.</p><p>For example:</p><pre>class Animal {</pre><pre>    void sound() {<br>        System.out.println(&quot;Animal makes a sound&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>Here, Dog overrides the sound() method of Animal.</p><p>Now:</p><pre>Dog dog = new Dog();</pre><pre>dog.sound();</pre><p>Output:</p><pre>Dog barks</pre><p>The child class has provided its own implementation of the parent’s method.</p><h3>Dynamic Method Dispatch</h3><p>Now we come to one of the most important parts of runtime polymorphism.</p><p>We can create a <strong>parent-class reference that points to a child-class object</strong>.</p><p>For example:</p><pre>Animal animal = new Dog();</pre><p>Let’s break this down.</p><pre>Animal animal = new Dog();<br>   ↑              ↑<br>Reference        Object</pre><p>The reference is of type Animal, but the actual object created is a Dog.</p><p>This is possible because Dog <strong>extends</strong> Animal.</p><pre>Animal<br>   ↑<br>   |<br>  Dog</pre><p>Now if we call:</p><pre>animal.sound();</pre><p>Which sound() will execute?</p><p>The Dog version:</p><pre>Dog barks</pre><p>Why?</p><p>Because the actual object is a Dog.</p><p>Java determines the overridden method based on the <strong>actual object at runtime</strong>.</p><p>This is called <strong>Dynamic Method Dispatch</strong>.</p><h3>Why do we need Dynamic Method Dispatch?</h3><p>This is where polymorphism becomes really useful.</p><p>Suppose we have different types of animals:</p><pre>class Animal {</pre><pre>    void sound() {<br>        System.out.println(&quot;Animal sound&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><pre>class Cat extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        System.out.println(&quot;Cat meows&quot;);<br>    }<br>}</pre><p>Without polymorphism, we might write separate code for every type:</p><pre>Dog dog = new Dog();<br>dog.sound();</pre><pre>Cat cat = new Cat();<br>cat.sound();</pre><p>But with polymorphism, we can use the parent type:</p><pre>Animal animal1 = new Dog();<br>Animal animal2 = new Cat();</pre><pre>animal1.sound();<br>animal2.sound();</pre><p>Output:</p><pre>Dog barks<br>Cat meows</pre><p>The same reference type, Animal, is being used, but the behaviour changes depending on the actual object.</p><p>This is the real power of polymorphism.</p><h3>A Real-World Example</h3><p>Imagine we are building a payment system.</p><p>We have a parent class:</p><pre>class Payment {</pre><pre>    void pay() {<br>        System.out.println(&quot;Making payment&quot;);<br>    }<br>}</pre><p>Then we have different payment methods:</p><pre>class UPI extends Payment {</pre><pre>    @Override<br>    void pay() {<br>        System.out.println(&quot;Payment through UPI&quot;);<br>    }<br>}</pre><pre>class CreditCard extends Payment {</pre><pre>    @Override<br>    void pay() {<br>        System.out.println(&quot;Payment through Credit Card&quot;);<br>    }<br>}</pre><pre>class NetBanking extends Payment {</pre><pre>    @Override<br>    void pay() {<br>        System.out.println(&quot;Payment through Net Banking&quot;);<br>    }<br>}</pre><p>Now we can write:</p><pre>Payment payment;</pre><p>And depending on what payment method we need:</p><pre>payment = new UPI();<br>payment.pay();</pre><p>or:</p><pre>payment = new CreditCard();<br>payment.pay();</pre><p>or:</p><pre>payment = new NetBanking();<br>payment.pay();</pre><p>The method call is the same:</p><pre>payment.pay();</pre><p>But the behaviour is different.</p><pre>UPI        → Payment through UPI<br>CreditCard → Payment through Credit Card<br>NetBanking → Payment through Net Banking</pre><p>This is polymorphism.</p><h3>Why not simply create the child object directly?</h3><p>You might wonder:</p><blockquote><em>Why do we write </em><em>Payment payment = new UPI() instead of simply </em><em>UPI payment = new UPI()?</em></blockquote><p>For a simple example, both can work.</p><p>But the advantage becomes clear when we write reusable code.</p><p>For example:</p><pre>void makePayment(Payment payment) {<br>    payment.pay();<br>}</pre><p>Now we can pass <strong>any payment type that extends </strong><strong>Payment</strong>:</p><pre>makePayment(new UPI());<br>makePayment(new CreditCard());<br>makePayment(new NetBanking());</pre><p>We don’t need to create a separate method for every payment type.</p><p>The method only cares that the object is a Payment.</p><p>At runtime, Java will execute the correct overridden pay() method.</p><p>This gives us:</p><ul><li><strong>Loose coupling</strong></li><li><strong>Code reusability</strong></li><li><strong>Flexibility</strong></li><li><strong>Easier maintenance</strong></li><li>The ability to add new child classes without changing existing code</li></ul><p>For example, tomorrow we can add:</p><pre>class Wallet extends Payment {</pre><pre>    @Override<br>    void pay() {<br>        System.out.println(&quot;Payment through Wallet&quot;);<br>    }<br>}</pre><p>And we can simply do:</p><pre>makePayment(new Wallet());</pre><p>The makePayment() method does not need to be changed.</p><h3>One Important Limitation</h3><p>When we write:</p><pre>Animal animal = new Dog();</pre><p>the <strong>reference type controls what members are accessible</strong>, while the <strong>actual object controls which overridden instance method runs</strong>.</p><p>For example:</p><pre>class Animal {</pre><pre>    void sound() {<br>        System.out.println(&quot;Animal&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        System.out.println(&quot;Dog&quot;);<br>    }</pre><pre>    void bark() {<br>        System.out.println(&quot;Barking&quot;);<br>    }<br>}</pre><p>Now:</p><pre>Animal animal = new Dog();</pre><pre>animal.sound();  // Allowed<br>animal.bark();   // Not allowed</pre><p>Why?</p><p>Because the reference is of type Animal.</p><p>Java knows that an Animal has sound(), but the Animal reference does not know about the bark() method that exists only in Dog.</p><p>However, when sound() is called, Java checks the actual object at runtime and executes Dog&#39;s overridden version.</p><h3>The Easy Way to Remember Polymorphism</h3><p>Think of it like this:</p><h3>Compile-time polymorphism</h3><pre>Same method name<br>       ↓<br>Different parameters<br>       ↓<br>Method Overloading<br>       ↓<br>Decision at compile time</pre><h3>Runtime polymorphism</h3><pre>Parent reference<br>       ↓<br>Child object<br>       ↓<br>Method Overriding<br>       ↓<br>Decision at runtime<br>       ↓<br>Dynamic Method Dispatch</pre><p>So:</p><blockquote><strong><em>Method overloading → Compile-time polymorphism</em></strong></blockquote><blockquote><strong><em>Method overriding → Runtime polymorphism</em></strong></blockquote><blockquote><strong><em>Parent reference + child object → Dynamic Method Dispatch</em></strong></blockquote><p>And the biggest benefit of polymorphism is that <strong>we can write code against a common parent type while allowing different child objects to provide their own behaviour.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a81b1e7033d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Java: Inheritance in Java]]></title>
            <link>https://medium.com/@aishureddy/core-java-inheritance-in-java-112ca38532be?source=rss-04ef0daaee11------2</link>
            <guid isPermaLink="false">https://medium.com/p/112ca38532be</guid>
            <category><![CDATA[inheritence]]></category>
            <dc:creator><![CDATA[Aishu Reddy]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 06:56:48 GMT</pubDate>
            <atom:updated>2026-10-07T06:56:48.876Z</atom:updated>
            <content:encoded><![CDATA[<p>Inheritance is one of the important concepts of <strong>Object-Oriented Programming (OOP)</strong>.</p><p>In simple words, <strong>inheritance means a child class can acquire the properties and behaviours of a parent class.</strong></p><p>In Java, inheritance is achieved using the <strong>extends</strong> keyword.</p><p>For example, suppose we have a Vehicle class:</p><pre>class Vehicle {<br>    String brand = &quot;Toyota&quot;;</pre><pre>    void start() {<br>        System.out.println(&quot;Vehicle is starting&quot;);<br>    }<br>}</pre><p>Now we create a Car class that extends Vehicle:</p><pre>class Car extends Vehicle {</pre><pre>    void drive() {<br>        System.out.println(&quot;Car is driving&quot;);<br>    }<br>}</pre><p>Now Car can use the properties and methods of Vehicle:</p><pre>public class Main {<br>    public static void main(String[] args) {</pre><pre>        Car car = new Car();</pre><pre>        System.out.println(car.brand);<br>        car.start();<br>        car.drive();<br>    }<br>}</pre><p>Output:</p><pre>Toyota<br>Vehicle is starting<br>Car is driving</pre><p>Here:</p><ul><li>Vehicle is the <strong>parent/superclass</strong></li><li>Car is the <strong>child/subclass</strong></li><li>extends is used to create the inheritance relationship</li></ul><p>So we can say:</p><blockquote><em>A </em><em>Car </em><strong><em>is a</em></strong><em> </em><em>Vehicle.</em></blockquote><p>This is also called an <strong>IS-A relationship</strong>.</p><h3>Why do we need inheritance?</h3><p>Inheritance mainly helps us with <strong>code reusability</strong>.</p><p>Imagine we have many different types of vehicles:</p><pre>Vehicle<br>   |<br>   +---- Car<br>   |<br>   +---- Bike<br>   |<br>   +---- Truck</pre><p>Instead of writing start() separately inside every class, we can define it once in Vehicle and let the child classes inherit it.</p><p>This avoids duplicate code.</p><h3>Types of Inheritance in Java</h3><p>Java supports different forms of inheritance.</p><h3>1. Single Inheritance</h3><p>One child class inherits from one parent class.</p><pre>Parent<br>  |<br>Child</pre><p>Example:</p><pre>class Animal {<br>    void eat() {<br>        System.out.println(&quot;Eating&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {<br>    void bark() {<br>        System.out.println(&quot;Barking&quot;);<br>    }<br>}</pre><p>Dog inherits from Animal.</p><h3>2. Multilevel Inheritance</h3><p>In multilevel inheritance, one class inherits from another class, and another class inherits from that child class.</p><pre>Animal<br>   |<br>  Dog<br>   |<br> Puppy</pre><p>Example:</p><pre>class Animal {<br>    void eat() {<br>        System.out.println(&quot;Eating&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {<br>    void bark() {<br>        System.out.println(&quot;Barking&quot;);<br>    }<br>}</pre><pre>class Puppy extends Dog {<br>    void play() {<br>        System.out.println(&quot;Playing&quot;);<br>    }<br>}</pre><p>Now Puppy can access methods from both Dog and Animal.</p><pre>Puppy puppy = new Puppy();</pre><pre>puppy.eat();<br>puppy.bark();<br>puppy.play();</pre><p>So the inheritance happens across multiple levels.</p><h3>3. Hierarchical Inheritance</h3><p>Multiple child classes inherit from the same parent class.</p><pre>Vehicle<br>       /     \<br>     Car     Bike</pre><p>Example:</p><pre>class Vehicle {<br>    void start() {<br>        System.out.println(&quot;Vehicle starts&quot;);<br>    }<br>}</pre><pre>class Car extends Vehicle {<br>    void drive() {<br>        System.out.println(&quot;Car drives&quot;);<br>    }<br>}</pre><pre>class Bike extends Vehicle {<br>    void ride() {<br>        System.out.println(&quot;Bike rides&quot;);<br>    }<br>}</pre><p>Both Car and Bike can use the start() method.</p><h3>Does Java support Multiple Inheritance?</h3><p>Java <strong>does not support multiple inheritance through classes</strong>.</p><p>That means we cannot do this:</p><pre>class Child extends Parent1, Parent2 {<br>}</pre><p>Why?</p><p>One major reason is <strong>ambiguity</strong>.</p><p>Suppose Java allowed:</p><pre>Parent1       Parent2<br>           \          /<br>             Child</pre><p>And both parents had the same method:</p><pre>class Parent1 {<br>    void show() {<br>        System.out.println(&quot;Parent 1&quot;);<br>    }<br>}</pre><pre>class Parent2 {<br>    void show() {<br>        System.out.println(&quot;Parent 2&quot;);<br>    }<br>}</pre><p>If Child inherited from both, then:</p><pre>Child obj = new Child();<br>obj.show();</pre><p>Which show() should Java execute?</p><p>Should it execute:</p><pre>Parent 1</pre><p>or</p><pre>Parent 2</pre><p>This creates ambiguity.</p><p>Therefore, Java does not allow multiple inheritance using classes.</p><p>However, Java <strong>does support multiple inheritance through interfaces</strong>, because a class can implement multiple interfaces and Java provides rules for resolving conflicts.</p><h3>this Keyword</h3><p>Now let’s understand the this keyword.</p><p>this refers to the <strong>current object</strong>.</p><p>It can be used for several purposes, such as:</p><ul><li>referring to the current object’s variables</li><li>calling another method of the current object</li><li>calling another constructor of the same class</li></ul><p>For example:</p><pre>class Student {</pre><pre>    String name;<br>    int age;</pre><pre>    Student(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>}</pre><p>Here we have:</p><pre>this.name = name;</pre><p>The this.name refers to the instance variable, while name refers to the constructor parameter.</p><h3>this() Constructor Call</h3><p>this() is used to call <strong>another constructor of the same class</strong>.</p><p>For example:</p><pre>class Student {</pre><pre>    String name;<br>    int age;</pre><pre>    Student() {<br>        this(&quot;Unknown&quot;, 0);<br>    }</pre><pre>    Student(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>}</pre><p>When we create:</p><pre>Student s = new Student();</pre><p>The no-argument constructor calls:</p><pre>this(&quot;Unknown&quot;, 0);</pre><p>which calls the parameterized constructor of the <strong>same class</strong>.</p><p>One important rule:</p><blockquote><em>this() must be the </em><strong><em>first statement</em></strong><em> inside a constructor.</em></blockquote><h3>super Keyword</h3><p>super is used to refer to the <strong>parent class</strong>.</p><p>It can be used to:</p><ol><li>Call the parent class constructor</li><li>Access the parent class variable</li><li>Call the parent class method</li></ol><p>For example:</p><pre>class Animal {</pre><pre>    String name = &quot;Animal&quot;;</pre><pre>    void sound() {<br>        System.out.println(&quot;Animal makes a sound&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {</pre><pre>    String name = &quot;Dog&quot;;</pre><pre>    void display() {<br>        System.out.println(name);<br>        System.out.println(super.name);<br>    }<br>}</pre><p>Here:</p><pre>name</pre><p>refers to the Dog variable.</p><p>Whereas:</p><pre>super.name</pre><p>refers to the Animal variable.</p><h3>super() Constructor</h3><p>super() is used to call the <strong>parent class constructor</strong>.</p><p>Example:</p><pre>class Animal {</pre><pre>    Animal() {<br>        System.out.println(&quot;Animal constructor&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {</pre><pre>    Dog() {<br>        super();<br>        System.out.println(&quot;Dog constructor&quot;);<br>    }<br>}</pre><p>When we create:</p><pre>Dog dog = new Dog();</pre><p>The output will be:</p><pre>Animal constructor<br>Dog constructor</pre><p>This happens because the parent constructor executes before the child constructor.</p><h3>What happens if we don’t write super()?</h3><p>This is an important point.</p><p>If we don’t explicitly write super() inside a child constructor, Java automatically inserts it as the <strong>first statement</strong>, provided the parent has an accessible no-argument constructor.</p><p>For example:</p><pre>class Animal {</pre><pre>    Animal() {<br>        System.out.println(&quot;Animal&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {</pre><pre>    Dog() {<br>        System.out.println(&quot;Dog&quot;);<br>    }<br>}</pre><p>Java internally treats the constructor approximately like:</p><pre>Dog() {<br>    super();<br>    System.out.println(&quot;Dog&quot;);<br>}</pre><p>So the parent constructor is called first.</p><h3>The Object Class</h3><p>There is another important concept here.</p><p>In Java, every class ultimately inherits from the <strong>Object class</strong>, either directly or indirectly.</p><p>For example:</p><pre>Object<br>   |<br>Animal<br>   |<br>Dog</pre><p>Even if we write:</p><pre>class Animal {<br>}</pre><p>it is conceptually similar to:</p><pre>class Animal extends Object {<br>}</pre><p>And if:</p><pre>class Dog extends Animal {<br>}</pre><p>then:</p><pre>Dog → Animal → Object</pre><p>So when a Dog object is created, constructor execution ultimately reaches the Object constructor at the top of the inheritance hierarchy.</p><p>The constructor chain works from <strong>parent to child</strong>:</p><pre>Object constructor<br>        ↓<br>Animal constructor<br>        ↓<br>Dog constructor</pre><p>This is why we often say:</p><blockquote><em>The first statement of a constructor is either an explicit </em><em>this()/</em><em>super() call, or Java inserts </em><em>super() automatically.</em></blockquote><p>If this() is used, that constructor calls another constructor in the same class, and eventually the chain must reach a superclass constructor.</p><h3>Method Overriding</h3><p>Now let’s talk about <strong>method overriding</strong>.</p><p>Method overriding happens when a <strong>child class provides its own implementation of a method that is already defined in the parent class</strong>.</p><p>Example:</p><pre>class Animal {</pre><pre>    void sound() {<br>        System.out.println(&quot;Animal makes a sound&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>Both Animal and Dog have a method called:</p><pre>sound()</pre><p>But Dog provides its own implementation.</p><p>Now:</p><pre>Dog dog = new Dog();<br>dog.sound();</pre><p>Output:</p><pre>Dog barks</pre><p>The child implementation is executed.</p><p>The @Override annotation tells the compiler that we intend to override a parent method.</p><p>It is recommended because the compiler can catch mistakes for us.</p><p>For example, if we accidentally write:</p><pre>@Override<br>void sounds() {<br>}</pre><p>Java will give a compilation error because sounds() does not actually override a method from the parent.</p><h3>Why is Method Overriding Important?</h3><p>Method overriding is one of the concepts that enables <strong>runtime polymorphism</strong>.</p><p>For example:</p><pre>Animal animal = new Dog();</pre><pre>animal.sound();</pre><p>Even though the reference type is Animal, the actual object is Dog.</p><p>Therefore, Java executes:</p><pre>Dog&#39;s sound()</pre><p>and the output is:</p><pre>Dog barks</pre><p>This is called <strong>dynamic method dispatch</strong>.</p><p>The method that gets executed is determined at runtime based on the actual object.</p><h3>super.method() and Method Overriding</h3><p>Sometimes the child wants to use the parent’s implementation as well.</p><p>We can use super for this.</p><pre>class Animal {</pre><pre>    void sound() {<br>        System.out.println(&quot;Animal makes a sound&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        super.sound();<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>Now:</p><pre>Dog dog = new Dog();<br>dog.sound();</pre><p>Output:</p><pre>Animal makes a sound<br>Dog barks</pre><p>Here:</p><pre>super.sound();</pre><p>calls the <strong>parent’s version</strong> of the method.</p><h3>Important Rules of Method Overriding</h3><p>There are some important rules to remember:</p><h3>1. Method signature should match</h3><p>The child method should have the same method name and parameters as the parent method.</p><h3>2. Return type</h3><p>The return type should be the same, or a compatible <strong>covariant return type</strong>.</p><h3>3. Access level cannot be more restrictive</h3><p>For example, if the parent method is:</p><pre>public void show()</pre><p>the child cannot override it as:</p><pre>private void show()</pre><p>because that would reduce its accessibility.</p><h3>4. final methods cannot be overridden</h3><p>If we write:</p><pre>final void show() {<br>}</pre><p>a child class cannot override that method.</p><h3>5. static methods are not overridden</h3><p>Static methods belong to the class rather than the object. If a child defines a static method with the same signature, it is called <strong>method hiding</strong>, not overriding.</p><h3>Inheritance vs Method Overriding</h3><p>These two concepts are related but different.</p><p><strong>Inheritance</strong> means the child class gets access to properties and methods from the parent.</p><pre>Parent<br>   ↓<br>Child</pre><p><strong>Method overriding</strong> means the child provides a different implementation for an inherited method.</p><pre>Parent<br>   ↓<br>Child → changes the implementation</pre><p>For example:</p><pre>class Animal {</pre><pre>    void sound() {<br>        System.out.println(&quot;Animal sound&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {</pre><pre>    @Override<br>    void sound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><p>Here:</p><ul><li>extends → inheritance</li><li>sound() in Dog → method overriding</li><li>@Override → tells Java that we are overriding the parent method</li><li>super.sound() → calls the parent implementation</li></ul><h3>One Simple Picture to Remember Everything</h3><pre>Object<br>                      |<br>                   Animal<br>                      |<br>                    Dog<br>                 /         \<br>          inherits       overrides<br>             |               |<br>          sound()         sound()</pre><p>So, the main idea is:</p><blockquote><strong><em>Inheritance allows a child class to reuse the properties and behaviours of a parent class, while method overriding allows the child class to provide its own implementation of an inherited method.</em></strong></blockquote><p>And remember the difference between this and super:</p><pre>this()  → calls another constructor of the same class</pre><pre>super() → calls the constructor of the parent class</pre><pre>this.x  → current class/object variable</pre><pre>super.x → parent class variable</pre><pre>this.method()  → current class method</pre><pre>super.method() → parent class method</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=112ca38532be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>