<?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 Prasanna Srikanth on Medium]]></title>
        <description><![CDATA[Stories by Prasanna Srikanth on Medium]]></description>
        <link>https://medium.com/@prasanna8898?source=rss-f92ac7795cc8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Prasanna Srikanth on Medium</title>
            <link>https://medium.com/@prasanna8898?source=rss-f92ac7795cc8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:23:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prasanna8898/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[Functional Interfaces and Lambdas]]></title>
            <link>https://medium.com/@prasanna8898/functional-interfaces-and-lambdas-541d91671597?source=rss-f92ac7795cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/541d91671597</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-functional-interface]]></category>
            <category><![CDATA[java-8-feature]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Prasanna Srikanth]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 08:53:44 GMT</pubDate>
            <atom:updated>2025-03-29T08:53:44.921Z</atom:updated>
            <content:encoded><![CDATA[<p>In Java, functional interfaces and lambda expressions are key concepts in functional programming that were introduced in Java 8. They are used together to create more concise and expressive code, especially for tasks that involve passing behavior as parameters or implementing small function objects.</p><p>Before moving to these approaches and how it will be used, lets cover some tradational examples and scenarios where it can be used.</p><pre>public interface Add {<br>    public int add(int a,int b);<br>}</pre><pre>public class AddImpl implements Add{<br><br>    @Override<br>    public int add(int a, int b) {<br>        return a+b;<br>    }<br>}</pre><pre>public class main {<br>    public static void main(String[] args) {<br>        Add obj = new AddImpl();<br>        int result = obj.add(10,15);<br>        System.out.println(result);<br>    }<br>}</pre><p>Here Add Interface has single abstract method and just to add its implementation we have written AddImpl implementing Add interface.</p><p>Here Functional interface &amp; Lambdas comes into picture.</p><p><strong>Functional Interface and Lambdas:-</strong></p><p>A<strong> </strong>functional interface is an interface with just one abstract method<strong>.</strong> It can have multiple default or static methods, but only one abstract method.</p><p>A lambda expression is a concise way to represent an anonymous function (or instance of a functional interface). It allows you to write code in a more readable and compact form without having to explicitly create an implementation of a functional interface.</p><p>Now the above code can be written as below,</p><pre>@FunctionalInterface<br>public interface Add {<br>    public int add(int a,int b);<br>}</pre><pre>public class main {<br>    public static void main(String[] args) {<br>        Add obj = (a,b) -&gt; {<br>            {<br>                System.out.println(&quot;Inside add method);<br>                return a+b;<br>            }<br>        };<br>        int res = obj.add(10,40);<br>        System.out.println(res);<br>    }<br>}</pre><p>Using Functional Interface, we have avoided AddImpl class which writes the implementation of method implementing from add interface.</p><p>It is not mandatory to have @FunctionalInterface annotation in Add Interface. but if we do have this annotation, we should not add more than one abstract method in this interface.</p><p>In this approach we have directly written the implementation.but this is not the final version though,</p><p>we need to have curly braces only when method definition is having two or more lines. Let’s assume if we don’t need to have System.out.println, code can be reduced as below.</p><pre>public class main {<br>    public static void main(String[] args) {<br>        Add obj = (a,b) -&gt; a+b;<br>        int res = obj.add(10,40);<br>        System.out.println(res);<br>    }<br>}</pre><p>In the above code (a,b) -&gt; a+b; is the example for lambda expression.</p><p>We will see two more examples with below patterns:-</p><p><strong>Function with one argument and return value.</strong></p><pre>¸@FunctionalInterface<br>public interface Square {<br>    public int square(int a);<br>}</pre><pre>public class main {<br>    public static void main(String[] args) {<br>        Square obj = a -&gt; a*a;<br>        int res = obj.square(10);<br>        System.out.println(res);<br>    }<br>}</pre><p><strong>Function with no argument and return value.</strong></p><pre>@FunctionalInterface<br>public interface printTimeInMs {<br>    public Long printTime();<br>}</pre><pre>public class main {<br>    public static void main(String[] args) {<br>        printTimeInMs obj = () -&gt; System.currentTimeMillis();<br>        System.out.println(obj.printTime());<br>    }<br>}</pre><p><strong>Exception handling with Functional Interface</strong></p><p>Now what happens if some error occurs in lambda function which we wrote, Below code is gonna throw Arithmetic Exception</p><pre>@FunctionalInterface<br>public interface Divide {<br>    public float divide(int a,int b);<br>}</pre><pre>public class main {<br>    public static void main(String[] args) {<br>        Divide obj = (a, b) -&gt; a / b;<br>        Float res = obj.divide(2, 0);<br>        System.out.println(res);<br>    }<br>}</pre><p>As we are dividing a number by zero, we get the below Exception</p><pre>Exception in thread &quot;main&quot; java.lang.ArithmeticException: / by zero<br> at com.FunctionalInterface.main.lambda$main$0(main.java:5)<br> at com.FunctionalInterface.main.main(main.java:6)</pre><p>Now, We will cover how can we handle this exception.</p><pre>public class main {<br>    public static void main(String[] args) {<br>        Divide obj = (a,b) -&gt; {<br>            if(b == 0) {<br>                throw new ArithmeticException(&quot;Cannot Divide by zero&quot;);<br>            }<br>            return a / b;<br>        };<br>        try {<br>            Float res = obj.divide(2, 0);<br>            System.out.println(res);<br>        }<br>        catch (Exception e) {<br>            System.out.println(e.getMessage());<br>        }<br>    }<br>}</pre><p>when this code was executed, we get below as output.</p><pre>Cannot Divide by zero</pre><p>what if we want to throw some Checked Exception?</p><p>we can do the same as above, but parent interface from which we are implementing the method should throw that type of exception in its method.</p><pre>@FunctionalInterface<br>public interface Divide {<br>    public float divide(int a,int b) throws IOException;<br>}</pre><pre>public class main {<br>    public static void main(String[] args) {<br>        Divide obj = (a,b) -&gt; {<br>            if(b == 0) {<br>                throw new IOException(&quot;Cannot Divide by zero&quot;);<br>            }<br>            return a / b;<br>        };<br>        try {<br>            Float res = obj.divide(2, 0);<br>            System.out.println(res);<br>        }<br>        catch (Exception e) {<br>            System.out.println(e.getMessage());<br>        }<br>    }<br>}</pre><p>By Default, Java provides some interface which we can use directly.</p><p><strong>Function&lt;T,R&gt; Interface:</strong></p><p>The Function interface represents a function that takes one argument of type T and produces a result of type R. It&#39;s used when you want to perform a transformation or operation on a single input and return a result.</p><p>Method name: <strong>apply</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zyCYgQTEGycD-MyjBXAd2g.png" /></figure><p><strong>Example:-</strong></p><pre>public class main {<br>    public static void main(String[] args) {<br>        Function&lt;Integer,Integer&gt; square = (a) -&gt; a*a;<br>        System.out.println(square.apply(20));<br>    }<br>}</pre><p><strong>Output:-</strong></p><pre>400</pre><p><strong>Predicate&lt;T&gt; Interface:</strong></p><p>The Predicate interface represents a boolean-valued function of one argument. It&#39;s commonly used for testing or filtering conditions.</p><p>Method name: <strong>test</strong></p><figure><img alt="Java Predicate Method" src="https://cdn-images-1.medium.com/max/1024/1*Wb0wyQ9f_-qj3-cSJ8v1Fw.png" /></figure><p><strong>Example:-</strong></p><pre>public class main {<br>    public static void main(String[] args) {<br>        Predicate&lt;Integer&gt; isEven = (num) -&gt; (num%2 == 0);<br>        System.out.println(isEven.test(5));<br>    }<br>}</pre><p><strong>Output:-</strong></p><pre>false</pre><p><strong>Consumer&lt;T&gt; Interface:</strong></p><p>The Consumer interface represents an operation that accepts a single argument of type T and returns no result(void) . It&#39;s used when you want to perform an action with an input.</p><p>Method name: <strong>accept</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3OcgpBgeURokZxE80oY5A.png" /></figure><p><strong>Example:</strong></p><pre>public class main {<br>    public static void main(String[] args) {<br>        Consumer&lt;Float&gt; printTotalMark = (total) -&gt; System.out.println(&quot;Total mark scored is &quot;+total);<br>        printTotalMark.accept(450.5f);<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Total mark scored is 450.5</pre><p><strong>BiFunction&lt;T,U,R&gt; Interface:</strong></p><p>Combining two inputs to produce a result, such as performing arithmetic on two values or combining two strings.</p><p>Method name: <strong>accept</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zJlDpTyrwg6amCRPykCnw.png" /></figure><p><strong>Example:</strong></p><pre>public class BiFunctionInterface {<br>    public static void main(String[] args) {<br>        BiFunction&lt;Integer,Integer,Integer&gt; calculateTotalPrice = (cost,quantity) -&gt; cost*quantity;<br>        System.out.println(calculateTotalPrice.apply(50,30));<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>1500</pre><p><strong>BiPredicate&lt;T,U&gt; Interface:</strong></p><p>Testing conditions on two inputs, such as checking if two fields in a form are valid or validating two values against certain rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwNWziJwbPEfxlnGPSVyEg.png" /></figure><p><strong>Example:</strong></p><pre>public class BiPredicateInterface {<br>    public static void main(String[] args) {<br>        BiPredicate&lt;Boolean,Float&gt; isEligibleForScholarShip = (pass,totalMark) -&gt; pass &amp;&amp; totalMark &gt; 400.0f;<br>        System.out.println(isEligibleForScholarShip.test(true,412f));<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>true</pre><p><strong>BiConsumer&lt;T,U&gt; Interface:</strong></p><p>Performing actions on two inputs, such as logging two pieces of data, updating two tables in a database, or sending two pieces of data in a notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHxKXNgjka_fBQbpxhkc1A.png" /></figure><p><strong>Example:</strong></p><pre>public class BiConsumerInterface {<br>    public static void main(String[] args) {<br>        BiConsumer&lt;String,String&gt; printLog = (username,action) -&gt; System.out.println(&quot;User &quot;+username+<br>                &quot; performed action type &quot;+action);<br>        printLog.accept(&quot;John&quot;,&quot;Login&quot;);<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>User John performed action type Login</pre><p><strong>Conclusion:</strong></p><p>Functional interfaces and lambda expressions in Java are powerful tools that promote a functional programming style. A functional interface contains exactly one abstract method, allowing it to be implemented using lambda expressions, which offer a more compact and readable syntax compared to traditional anonymous classes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=541d91671597" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Generics]]></title>
            <link>https://medium.com/@prasanna8898/java-generics-4d17d785e1b2?source=rss-f92ac7795cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d17d785e1b2</guid>
            <category><![CDATA[generics-in-java]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Prasanna Srikanth]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 09:18:52 GMT</pubDate>
            <atom:updated>2025-03-25T09:18:52.225Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Generics:-</strong></p><p>In Java, generics provide a way to write classes, interfaces, and methods that can operate on objects of various types while providing compile-time type safety.</p><p>Using generics, you can create a single class, interface, or method that can work with different data types without losing the benefits of type checking at compile time.</p><p>First Let’s see some example why generics required,</p><p>Look at below Student, StudentRecord and Staff, StaffRecord</p><p><strong>Student class</strong></p><pre>public class Student {<br>    private long id;<br>    private String name;<br><br>    public Student(long id, String name) {<br>        this.id = id;<br>        this.name = name;<br>    }<br><br>    public long getId() {<br>        return id;<br>    }<br><br>    public void setId(long id) {<br>        this.id = id;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Student{&quot; +<br>                &quot;Id=&quot; + id +<br>                &quot;, name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><p><strong>Staff Class</strong></p><pre>public class Staff {<br>    private long id;<br>    private String name;<br><br>    public Staff(long id, String name) {<br>        this.id = id;<br>        this.name = name;<br>    }<br><br>    public long getId() {<br>        return id;<br>    }<br><br>    public void setId(long id) {<br>        this.id = id;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Staff{&quot; +<br>                &quot;id=&quot; + id +<br>                &quot;, name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><p><strong>StudentRecord class</strong></p><pre>public class StudentRecord {<br>    private Student[] records;<br><br>    public StudentRecord() {<br>        this.records = new Student[100];<br>    }<br><br>    public void addRecord(Student student) {<br>        for(int i=0;i&lt; records.length;i++) {<br>            if(Objects.isNull(records[i])) {<br>                records[i] = student;<br>                break;<br>            }<br>        }<br>    }<br><br>    public Student getItem(int index) {<br>        return records[index];<br>    }<br>}</pre><p><strong>StaffRecord class</strong></p><pre>public class StaffRecord {<br><br>    private Staff[] records;<br><br>    public StaffRecord() {<br>        this.records = new Staff[100];<br>    }<br><br>    public void addRecord(Staff staff) {<br>        for (int i = 0; i &lt; records.length; i++) {<br>            if (Objects.isNull(records[i])) {<br>                records[i] = staff;<br>                break;<br>            }<br>        }<br>    }<br><br>    public Staff getItem(int index) {<br>        return records[index];<br>    }<br>}</pre><p><strong>Demo class which uses StudentRecord and StaffRecord</strong></p><pre>public class Demo {<br><br>    public static void main(String[] args) {<br>        Student studentOne = new Student(1,&quot;John&quot;);<br>        Student studentTwo = new Student(2,&quot;Abraham&quot;);<br><br>        StudentRecord studentRecord = new StudentRecord();<br>        studentRecord.addRecord(studentOne);<br>        studentRecord.addRecord(studentTwo);<br><br>        Staff staffOne = new Staff(1,&quot;Parker&quot;);<br>        Staff staffTwo = new Staff(2,&quot;Affleck&quot;);<br><br>        StaffRecord staffRecord = new StaffRecord();<br>        staffRecord.addRecord(staffOne);<br>        staffRecord.addRecord(staffTwo);<br><br>        System.out.println(&quot;1st Student record is &quot;+studentRecord.getItem(0));<br>        System.out.println(&quot;2nd Staff Record is &quot;+staffRecord.getItem(1));<br>    }<br>}</pre><p>This is a normal way of writing code for separate classes, i.e,, for student and staff.</p><p>Both are performing the similar two function (addItem and getItem).</p><p>Just because the POJO differs we have written two different classes with two different method and used those in this demo class.</p><p>Can this be done in better way?</p><p>Let’s assume instead of passing Student and Staff, we will pass Object.</p><p>This is possible because in Java all class are extended by Object class.(Object is the parent of all class).</p><p><strong>ObjectRecord Class</strong></p><pre>public class ObjectRecord {<br>    private Object[] records;<br><br>    public ObjectRecord() {<br>        this.records = new Object[100];<br>    }<br><br>    public void addRecord(Object record) {<br>        for(int i=0;i&lt; records.length;i++) {<br>            if(Objects.isNull(records[i])) {<br>                records[i] = record;<br>                break;<br>            }<br>        }<br>    }<br><br>    public Object getItem(int index) {<br>        return records[index];<br>    }<br>}</pre><p><strong>DemoOne class which uses ObjectRecord for both Student and Staff.</strong></p><pre>public class DemoOne {<br>    public static void main(String[] args) {<br>        <br>        Student studentOne = new Student(1,&quot;John&quot;);<br>        Student studentTwo = new Student(2,&quot;Abraham&quot;);<br><br>        Staff staffOne = new Staff(1,&quot;Parker&quot;);<br>        Staff staffTwo = new Staff(2,&quot;Affleck&quot;);<br>        <br>        //creating ObjectRecord and adding Student and Staff record to it.<br>        ObjectRecord record = new ObjectRecord();<br><br>        record.addRecord(studentOne);<br>        record.addRecord(studentTwo);<br><br>        record.addRecord(staffOne);<br>        record.addRecord(staffTwo);<br><br>        //Trying to fetch Student and Staff from record<br>        Student student = (Student) record.getItem(0);<br>        Staff staff = (Staff) record.getItem(3);<br><br>        System.out.println(&quot;Fetched student is &quot;+student);<br>        System.out.println(&quot;Fetched staff is &quot;+staff);<br>    }<br>}</pre><p><strong>Output:-</strong></p><pre>Fetched student is Student{Id=1, name=&#39;John&#39;}<br>Fetched staff is Staff{id=2, name=&#39;Affleck&#39;}</pre><p>This works well , but there are two disadvantages</p><p>1. We need to cast the value everytime.</p><p>2. If casting goes wrong, it will throw ClassCastException.</p><p>We will see what happens when retrieving goes wrong.</p><pre>public class DemoOne {<br>    public static void main(String[] args) {<br><br>        Student studentOne = new Student(1,&quot;John&quot;);<br>        Student studentTwo = new Student(2,&quot;Abraham&quot;);<br><br>        Staff staffOne = new Staff(1,&quot;Parker&quot;);<br>        Staff staffTwo = new Staff(2,&quot;Affleck&quot;);<br><br>        //creating ObjectRecord and adding Student and Staff record to it.<br>        ObjectRecord record = new ObjectRecord();<br><br>        record.addRecord(studentOne);<br>        record.addRecord(studentTwo);<br><br>        record.addRecord(staffOne);<br>        record.addRecord(staffTwo);<br><br>        //Trying to fetch Student and Staff from record<br>        Student student = (Student) record.getItem(0);<br>        //retrieving student record and casting to Staff<br>        Staff staff = (Staff) record.getItem(1);<br><br>        System.out.println(&quot;Fetched student is &quot;+student);<br>        System.out.println(&quot;Fetched staff is &quot;+staff);<br>    }<br>}</pre><p><strong>Output:-</strong></p><pre>Exception in thread &quot;main&quot; java.lang.ClassCastException: class <br>com.generics.generics.Student cannot be cast to class com.generics.generics<br>.Staff (com.generics.generics.Student and com.generics.generics.Staff are <br>in unnamed module of loader &#39;app&#39;)<br> at com.generics.generics.DemoOne.main(DemoOne.java:23)</pre><p>Now generics comes into picture.</p><p><strong>Why generics?</strong></p><p><strong>Type Safety</strong>: Generics ensure that the types you use in your classes and methods are checked at compile-time, preventing type errors.</p><p><strong>Code Reusability</strong>: Generics allow you to write code that works with any object type, making it more reusable.</p><p><strong>Elimination of Casts</strong>: Without generics, you often need to cast objects when retrieving them from collections. With generics, the compiler ensures the correct type is used.</p><p>Implementing GenericRecord using Generic Class</p><pre>public class GenericRecord &lt;T&gt; {<br>    private T[] records;<br><br>    public GenericRecord() {<br>        this.records = (T[]) new Object[100];<br>    }<br><br>    public void addRecord(T record) {<br>        for(int i=0;i&lt; records.length;i++) {<br>            if(Objects.isNull(records[i])) {<br>                records[i] = record;<br>                break;<br>            }<br>        }<br>    }<br>    public T getItem(int index) {<br>        return records[index];<br>    }<br>}</pre><p>DemoTwo which uses above GenericRecord class for Staff and Student</p><pre>public class DemoTwo {<br>    public static void main(String[] args) {<br>        Student studentOne = new Student(1,&quot;John&quot;);<br>        Student studentTwo = new Student(2,&quot;Abraham&quot;);<br><br>        Staff staffOne = new Staff(1,&quot;Parker&quot;);<br>        Staff staffTwo = new Staff(2,&quot;Affleck&quot;);<br><br>        GenericRecord&lt;Student&gt; studentGenericRecord = new GenericRecord&lt;&gt;();<br>        studentGenericRecord.addRecord(studentOne);<br>        studentGenericRecord.addRecord(studentTwo);<br><br>        GenericRecord&lt;Staff&gt; staffGenericRecord = new GenericRecord&lt;&gt;();<br>        staffGenericRecord.addRecord(staffOne);<br>        staffGenericRecord.addRecord(staffTwo);<br><br>        Student student = studentGenericRecord.getItem(1);<br>        Staff staff = staffGenericRecord.getItem(0);<br><br>        System.out.println(&quot;Fetched Student is &quot;+student);<br>        System.out.println(&quot;Fetched Staff is &quot;+staff);<br>    }<br>}</pre><p><strong>Output:-</strong></p><pre>Fetched Student is Student{Id=2, name=&#39;Abraham&#39;}<br>Fetched Staff is Staff{id=1, name=&#39;Parker&#39;}</pre><p>Assigning studentRecord to staffGenricRecord or staffRecord to StudentGenericRecord is prohibited and will throw compile time error as we have mentioned Generic type to them.</p><p>Observe the below image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*VSxpkDIxOmEbo_uiqir2Ww.png" /></figure><p>We are providing a class on which type GenericRecord will accept and provide, So it ensures Type Safety.</p><p>We are reusing Generic Record for both Student and Staff class.</p><p>No Casting is happening during retrieving value.</p><p><strong>Generic Methods:-</strong></p><p>A generic method is a method that can operate on objects of various types while ensuring type safety. Just like with generic classes, generic methods allow you to define a method that can work with any data type without needing to duplicate code for different types.</p><p>First, let’s see normal approach of writing methods.</p><p><strong>Demo class using different method for printing Staff and Student</strong></p><pre>public class Demo {<br>    public static void main(String[] args) {<br><br>        Student studentOne = new Student(1,&quot;John&quot;);<br>        Student studentTwo = new Student(2,&quot;Abraham&quot;);<br>        Student[] students = {studentOne,studentTwo};<br><br>        Staff staffOne = new Staff(1,&quot;Parker&quot;);<br>        Staff staffTwo = new Staff(2,&quot;Affleck&quot;);<br>        Staff[] staffs = {staffOne,staffTwo};<br><br>        printAllStudents(students);<br>        printAllStaffs(staffs);<br>    }<br><br>    private static void printAllStudents(Student[] students) {<br>        System.out.println(&quot;Printing Student records&quot;);<br>        for (Student student : students) {<br>            System.out.println(student);<br>        }<br>    }<br><br>    private static void printAllStaffs(Staff[] staffs) {<br>        System.out.println(&quot;Printing Staff records&quot;);<br>        for (Staff staff : staffs) {<br>            System.out.println(staff);<br>        }<br>    }<br>}</pre><p><strong>Output:-</strong></p><pre>Printing Student records<br>Student{Id=1, name=&#39;John&#39;}<br>Student{Id=2, name=&#39;Abraham&#39;}<br>Printing Staff records<br>Staff{id=1, name=&#39;Parker&#39;}<br>Staff{id=2, name=&#39;Affleck&#39;}</pre><p>In this class both methods printAllStudents and printAllStaffs are doing the same function , just because the type is different we are writing the same code twice. <br>May be in this case its fine, but it becomes difficult when same operation needs to be done for 100 class types, we need 100 different methods. This is extremely difficult to write and manage.</p><p>Even though we write it, even there is small change we need to do in logic, we have to do it all the methods.</p><p>This is where Generic method can be used</p><p><strong>Demo class with Generic method Print</strong></p><pre>public class Demo {<br>    public static void main(String[] args) {<br><br>        Student studentOne = new Student(1,&quot;John&quot;);<br>        Student studentTwo = new Student(2,&quot;Abraham&quot;);<br>        Student[] students = {studentOne,studentTwo};<br><br>        Staff staffOne = new Staff(1,&quot;Parker&quot;);<br>        Staff staffTwo = new Staff(2,&quot;Affleck&quot;);<br>        Staff[] staffs = {staffOne,staffTwo};<br><br>        print(students);<br>        print(staffs);<br>    }<br><br>    public static &lt;T&gt; void print(T[] list) {<br>        System.out.println(&quot;printing List&quot;);<br>        for (T t : list) {<br>            System.out.println(t);<br>        }<br>    }<br>}</pre><p>Here the generic method print will work for all types of data. With single method we can perform the operations for different data types.</p><p><strong>Wrapper class:-</strong></p><p>In Java, wrapper classes are used to convert primitive data types into objects. Java provides a wrapper class for each of the 8 primitive data types:</p><ol><li>byte → Byte</li><li>short → Short</li><li>int → Integer</li><li>long → Long</li><li>float → Float</li><li>double → Double</li><li>char → Character</li><li>boolean → Boolean</li></ol><p>Generics supports only wrapper classes. No primitive types are allowed in generics.</p><p><strong>Example:-</strong></p><p>GenericRecord&lt;int&gt; is not allowed whereas GenericRecord&lt;Integer&gt; is allowed.</p><p>Always pass an Object as type as primitive data types are not supported by Generics.</p><p><strong>Wildcards:-</strong></p><p>wildcards in generics are used to represent an unknown type. Wildcards allow you to create more flexible and reusable code when working with generics. There are three types of wildcards in Java generics:</p><ol><li>Unbounded Wildcard (?)</li><li>Upper Bounded Wildcard (? extends T)</li><li>Lower Bounded Wildcard (? super T)</li></ol><p>Let’s go over all with simple example:-</p><pre>public class DemoThree {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; stringList = Arrays.asList(&quot;Alex&quot;,&quot;Jack&quot;);<br>        List&lt;Integer&gt; integerList = Arrays.asList(1,3,5);<br>        List&lt;Double&gt; doubleList = Arrays.asList(2.4,3.8,5.1,9.8);<br>        List&lt;Number&gt; numberList = Arrays.asList(1,2.0,3.3f);<br><br>        //print all types<br>        printElements(stringList);<br>        printElements(integerList);<br><br>        //print double and its parent<br>        printDoubleAndItsParent(doubleList);<br>        printDoubleAndItsParent(numberList);<br><br>        //print number and its child types<br>        printNumberAndItsChild(numberList);<br>        printNumberAndItsChild(integerList);<br>        printNumberAndItsChild(doubleList);<br>    }<br><br>    /**<br>     supports all types<br>     */<br>    private static void printElements(List&lt;?&gt; list) {<br>        System.out.println(&quot;Printing unbound wildcard Elements&quot;);<br>        System.out.println(list);<br>    }<br><br>    /**<br>     supports only Double and its parent type(Number) apart from that anything we pass will lead to compile time error.<br>     Try passing Integer. it will cause error.<br>     */<br>    <br>    private static void printDoubleAndItsParent(List&lt;? super Double&gt; list) {<br>        System.out.println(&quot;Printing Double and its parent Elements&quot;);<br>        System.out.println(list);<br>    }<br><br>    /**<br>     supports Number and its all types. other types will cause compile time error.<br>     Try passing String , it won&#39;t be accepted as it was not child class of Number<br>     * @param list<br>     */<br>    private static void printNumberAndItsChild(List&lt;? extends Number&gt; list) {<br>        System.out.println(&quot;Printing Double and its parent Elements&quot;);<br>        System.out.println(list);<br>    }<br>}</pre><p>printElements methods is the example for unbounded wildcard. It supports all the example types.</p><p>printNumberAndItsChild methos is the example for Upper Bounded Wildcard. In this example this method supports Number and all its child types.</p><p>printDoubleAndItsParent method is the example for Lower Bounded Wildcard. In this example this method supports Double and its parent types.</p><p><strong>Where can we use wildcards?</strong></p><p>Wildcards are great when you only need to <strong>read</strong> from a collection or generic type without modifying it. For example, when passing a list to a method and you just need to print or return values without changing the list.</p><p><strong>Avoid wildcards for manipulations</strong></p><p>If you need to manipulate the values in a specific way (e.g., adding elements), avoid using wildcards because they limit the type of operations you can perform (e.g., you can’t add to a List&lt;?&gt;).</p><p><strong>Conclusion:-</strong></p><p>Generics are a crucial part of Java programming, promoting clean, maintainable, and type<strong>-</strong>safe code. By using generics, you avoid errors related to type mismatches, eliminate the need for casting, and improve the flexibility and reusability of your code. While generics can be tricky at first, especially when working with wildcards and bounded types, they offer substantial benefits in creating robust, efficient, and scalable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d17d785e1b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exception Handling:-]]></title>
            <link>https://medium.com/@prasanna8898/exception-handling-704b7d205256?source=rss-f92ac7795cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/704b7d205256</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Prasanna Srikanth]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 11:33:08 GMT</pubDate>
            <atom:updated>2025-03-22T11:33:08.338Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Exception Handling:-</strong></p><p><strong>What is Exception?</strong></p><p>An exception in Java is an event that disrupts the normal flow of the program, often due to errors like invalid input or system failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*o0RV3O_x2TsbujLpoMLUDQ.jpeg" /></figure><p><strong>What is Exception Handling?</strong></p><p>Exception handling is a programming technique used to handle runtime errors, ensuring that the program can continue executing or fail gracefully without crashing.</p><p>Let’s take a look at below example on what will happen if exception is unhandled in Java.</p><pre>public class UnhandledException {<br>    public static void main(String[] args) {<br>        int a=10;<br>        int b=0;<br>        UnhandledException object = new UnhandledException();<br>        object.sum(a,b);<br>        object.divide(a,b);<br>        object.multiply(a,b);<br>    }<br><br>    public void sum(int a,int b) {<br>        int sum = a+b;<br>        System.out.println(&quot;Sum of &quot; + a + &quot; and &quot; + b + &quot; is &quot; + sum);<br>    }<br><br>    public void divide(int a,int b) {<br>        int division = a/b;<br>        System.out.println(&quot;Division of &quot; + a + &quot; by &quot; + b + &quot; is &quot; + division);<br>    }<br><br>    public void multiply(int a,int b) {<br>        int multiplication = a*b;<br>        System.out.println(&quot;Multiplication of &quot; + a + &quot; and &quot; + b <br>      + &quot; is &quot; + multiplication);<br>    }<br>}</pre><p><strong>Output:-</strong></p><pre>Sum of 10 and 0 is 10<br>Exception in thread &quot;main&quot; java.lang.ArithmeticException: / by zero<br> at UnhandledException.divide(UnhandledException.java:51)<br> at UnhandledException.main(UnhandledException.java:41)</pre><p>When the above code is observed, Error is thrown during division operation and program was terminated and because of that further operation(multiplication operation) is interrupted.</p><p>If exception is not handled in a proper way, there might be possibility where information about code will be thrown to user and it leads to security related issues.</p><p>In above example, Error thrown gives info about class name and some values. This is not good and all these details should be hidden. It is best to handle error and give human-readable error.</p><p>In real time projects, this kind of behaviour is not expected.</p><p>Program flow should not be stopped or terminated due to these errors. Let’s look on types of exception and it can be handled.</p><p>In Java , Exception is of mainly two types:-</p><p><strong>1. Checked Exceptions:-</strong></p><p>Checked exceptions are errors that are detected by the compiler while the program is being written. These exceptions must be addressed in the code before the program can run.</p><p>Few examples are</p><p>-&gt; IOException</p><p>-&gt; SQLException</p><p>-&gt; FileNotFoundException</p><p><strong>2. Unchecked Exceptions:-</strong></p><p>Unchecked exceptions are errors that occur during program execution and are usually caused by mistakes in the code.</p><p>Few examples are</p><p>-&gt; NullPointerException</p><p>-&gt; ArrayIndexOutOfBoundsException</p><p>-&gt; ArithmeticException</p><p>-&gt; ClassCastException</p><p>So, how exception can be handled?</p><p>Exception can be handled using try-catch block.</p><p>Now , we will use the same example to see how the error was handled for above example code:</p><pre>public class UnhandledException {<br>    public static void main(String[] args) {<br>        UnhandledException object = new UnhandledException();<br>        object.sum(10,40);<br>        object.divide(10,0);<br>        object.multiply(20,5);<br>    }<br><br>    public void sum(int a,int b) {<br>        int sum = a+b;<br>        System.out.println(&quot;Sum of &quot; + a + &quot; and &quot; + b + &quot; is &quot; + sum);<br>    }<br><br>    public void divide(int a,int b) {<br>        try {<br>            int division = a / b;<br>            System.out.println(&quot;Division of &quot; + a + &quot; by &quot; + b + &quot; is &quot; <br>            + division);<br>        }<br>        catch (ArithmeticException e) {<br>            System.out.println(&quot;Arithmetic exception occured and exception is &quot;<br>            +e.getMessage());<br>        }<br>    }<br><br>    public void multiply(int a,int b) {<br>        int multiplication = a*b;<br>        System.out.println(&quot;Multiplication of &quot; + a + &quot; and &quot; + b + &quot; is &quot; + <br>        multiplication);<br>    }<br>}</pre><p><strong>Output:-</strong></p><pre>Sum of 10 and 40 is 50<br>Arithmetic exception occurred and exception is / by zero<br>Multiplication of 20 and 5 is 100</pre><p>Now the Exception has been handled and it was displaying a message which we printed in the catch block and the flow of program is not interrupted and reached further the Error after try-catch block.</p><p>Now what if some other exception occurs in the same try-catch block, let’s try that,</p><pre>public class UnhandledException {<br>    public static void main(String[] args) {<br>        UnhandledException object = new UnhandledException();<br>        object.sum(10,40);<br>        object.divide(10,0,new int[]{20,40,80,35});<br>        object.multiply(20,5);<br>    }<br><br>    public void sum(int a,int b) {<br>        int sum = a+b;<br>        System.out.println(&quot;Sum of &quot; + a + &quot; and &quot; + b + &quot; is &quot; + sum);<br>    }<br><br>    public void divide(int a,int b,int[] arr) {<br>        try {<br>            int divideFirstElementByLast = arr[0]/arr[5];<br>            System.out.println(&quot;Division from array value is &quot;<br>                +divideFirstElementByLast);<br>            int division = a / b;<br>              System.out.println(&quot;Division of &quot; + a + &quot; by &quot; + b + &quot; is &quot; <br>                 + division);<br>        }<br>        catch (ArithmeticException e) {<br>            System.out.println(&quot;Arithmetic exception occured and exception is &quot;<br>                +e.getMessage());<br>        }<br>    }<br><br>    public void multiply(int a,int b) {<br>        int multiplication = a*b;<br>        System.out.println(&quot;Multiplication of &quot; + a + &quot; and &quot; + b + &quot; is &quot; <br>            + multiplication);<br>    }<br>}</pre><p><strong>Output:-</strong></p><pre>Sum of 10 and 40 is 50<br>Exception in thread &quot;main&quot; java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4<br> at UnhandledException.divide(UnhandledException.java:16)<br> at UnhandledException.main(UnhandledException.java:5)</pre><p>Code has been failed due to ArrayIndexOutOfBoundException as we tried to access element 6th element from array arr which has only 4 elements. So the code block handled only Arithmetic Exception and it need to handle this exception as well.</p><p>This can be done by passing Multiple Exception in catch block or pass parent class of Exception in catch block.</p><p><strong>Multiple Catch Blocks:-</strong></p><pre>public void divide(int a,int b,int[] arr) {<br>    try {<br>        int divideFirstElementByLast = arr[0]/arr[5];<br>        System.out.println(&quot;Division from array value is &quot;<br>            +divideFirstElementByLast);<br>        int division = a / b;<br>        System.out.println(&quot;Division of &quot; + a + &quot; by &quot; + b + &quot; is &quot; <br>            + division);<br>    }<br>    catch (ArithmeticException e) {<br>        System.out.println(&quot;Arithmetic exception occurred and <br>            exception message is &quot;+e.getMessage());<br>    }<br>    catch (IndexOutOfBoundsException e) {<br>        System.out.println(&quot;Index out of bounds exception occurred and <br>            exception message is &quot;+e.getMessage());<br>    }<br>}</pre><p>During Multiple catch block, order of exception should be from low to high. i.e, Parent class cannot be written in first catch block followed by child catch block.</p><p>Try writing Exception in first block and any other Exception in further block. It will cause compile time error.</p><p>Reason behind this was child Exception is also derived from parent, So there will be no scope for below catch blocks if parent catch was placed first.</p><p>Passing Multiple Exceptions:-</p><pre>public void divide(int a,int b,int[] arr) {<br>    try {<br>        int divideFirstElementByLast = arr[0]/arr[5];<br>        System.out.println(&quot;Division from array value is &quot;<br>            +divideFirstElementByLast);<br>        int division = a / b;<br>        System.out.println(&quot;Division of &quot; + a + &quot; by &quot; + b + &quot; is &quot; <br>            + division);<br>    }<br>    catch (ArithmeticException | IndexOutOfBoundsException e) {<br>        System.out.println(&quot;Some exception occurred and exception message is &quot;<br>          +e.getMessage());<br>    }<br>}</pre><p>Passing parent Exception:-</p><pre>public void divide(int a,int b,int[] arr) {<br>    try {<br>        int divideFirstElementByLast = arr[0]/arr[5];<br>        System.out.println(&quot;Division from array value is &quot;<br>            +divideFirstElementByLast);<br>        int division = a / b;<br>        System.out.println(&quot;Division of &quot; + a + &quot; by &quot; + b + &quot; is &quot; <br>            + division);<br>    }<br>    catch (Exception e) {<br>        System.out.println(&quot;Arithmetic exception occurred and <br>              exception message is &quot;+e.getMessage());<br>    }</pre><p>In Java, all checked and Unchecked Exceptions are derived from parent class Exception. So, by passing parent class Exception as type in catch block handles all type of Exception.</p><p>There might be some scenarios where we can use this, but in general it’s not a good practice to do it. Using Multiple catch block is an ideal way.</p><p><strong>Handling Exception in main class:-</strong></p><p>Exception not only occur in single method, but it can happen anywhere. In our example, divide method is the place which causes error. But there is a possibility of error to be occur in sum or multiply method as well. Instead of handling method from all methods, let’s handle the error in main method.</p><p>Observe the below code, try-catch has been removed from method and placed in main method.</p><pre>public class UnhandledException {<br>    public static void main(String[] args) {<br>        UnhandledException object = new UnhandledException();<br>        try {<br>            object.sum(10, 40);<br>            object.divide(10, 0, new int[]{20, 40, 80, 35});<br>            object.multiply(20, 5);<br>        }<br>        catch (ArithmeticException e) {<br>            System.out.println(&quot;Arithmetic exception occurred and exception <br>                message is &quot;+e.getMessage());<br>        }<br>        catch (IndexOutOfBoundsException e) {<br>            System.out.println(&quot;Index out of bounds exception occurred and <br>                exception message is &quot;+e.getMessage());<br>        }<br>    }<br><br>    public void sum(int a,int b) {<br>        int sum = a+b;<br>        System.out.println(&quot;Sum of &quot; + a + &quot; and &quot; + b + &quot; is &quot; + sum);<br>    }<br><br>    public void divide(int a,int b,int[] arr) {<br>        int divideFirstElementByLast = arr[0] / arr[5];<br>        System.out.println(&quot;Division from array value is &quot;<br>               + divideFirstElementByLast);<br>        int division = a / b;<br>        System.out.println(&quot;Division of &quot; + a + &quot; by &quot; + b + &quot; is &quot;<br>               + division);<br>    }<br><br>    public void multiply(int a,int b) {<br>        int multiplication = a*b;<br>        System.out.println(&quot;Multiplication of &quot; + a + &quot; and &quot; + b + &quot; is &quot; <br>                + multiplication);<br>    }<br>}</pre><p>Finally block:-</p><p>Finally, block is always executed even when there is no exception has been thrown.</p><p>Some real use case of finally block</p><p>1. Can be used to close the File/Resource used in try block operation.</p><p>2. Logging the event irrespective of success/failure.</p><p>3. Release lock of concurrent program.</p><p>Example for Finally block:-</p><pre>public class ReadFile {<br>    public static void main(String[] args) {<br>        BufferedReader bufferedReader = null;<br>        try{<br>            bufferedReader = new BufferedReader(<br>                  new FileReader(&quot;src/main/java/RandomText.txt&quot;));<br>            String line;<br>            while((line = bufferedReader.readLine()) != null) {<br>                System.out.println(line);<br>            }<br>        } catch (IOException e) {<br>            System.out.println(&quot;Some Error occurred during File read&quot;);<br>        }<br>        finally {<br>            try {<br>                if(bufferedReader != null) {<br>                    bufferedReader.close();<br>                }<br>            } catch (IOException e) {<br>                throw new RuntimeException(e);<br>            }<br>        }<br>    }<br>}</pre><p>Here Finally block is used to close the reader after using BufferedReader to read the file.</p><p>Try with resources:-</p><p>Try with resources used for managing resources, such as files, network connections, or database connections. It automatically closes resources at the end of a block of code, which helps prevent resource leaks.</p><p>Example:-</p><pre>public class ReadFile {<br>    public static void main(String[] args) {<br>        try (BufferedReader bufferedReader = new BufferedReader(<br>                new FileReader(&quot;src/main/java/RandomText.txt&quot;)))<br>        {<br>            String line;<br>            while ((line = bufferedReader.readLine()) != null) {<br>                System.out.println(line);<br>            }<br>        } catch (IOException e) {<br>            System.out.println(&quot;Some Error occurred during File read&quot;);<br>        }<br>    }<br>}</pre><p>When the resource is placed in try block, it will closed automatically at the end of try block.</p><p>Multiple resources can be written inside try with resources, and they can be separated using ‘;’</p><pre>try (ResourceType resource1 = new ResourceType();<br>     ResourceType resource2 = new ResourceType()) {<br>    // Code that uses the resources<br>} catch (Exception e) {<br>    // Handle exceptions<br>}</pre><p>Throw and Throws keyword:-</p><p>The throw keyword is used to explicitly throw an exception from within a method or a block of code. It is used when you want to create a new exception or rethrow an existing exception.</p><pre>public class ThrowError {<br><br>    public static void main(String[] args) {<br>        int mark = 120;<br>        try {<br>            checkValidMark(mark);<br>        }<br>        catch (IllegalArgumentException e) {<br>            System.out.println(e.getMessage());<br>        }<br>    }<br><br>    static void checkValidMark(int mark) {<br>        if(mark &lt;= 0 || mark &gt;= 100) {<br>            throw new IllegalArgumentException(&quot;Invalid Mark. Mark should be <br>                  in range 0-100.&quot;);<br>        }<br>    }<br>}</pre><p>So, in the above code we check the mark value and we throw the error incase if its not in range 0–100. We are using throw to throw IllegalArgument Exception and display the error which we passed to it.</p><p>try-catch block catches the error which was thrown and displays it in catch block.</p><p>Throws</p><p>The throws keyword is used to declare that a method might throw one or more exceptions. It is placed in the method signature, and it indicates that the method may throw the specified exceptions to the caller.</p><p>When to use throws:</p><p>When a method calls another method that throws a checked exception (like IOException, SQLException, etc.), and the calling method does not want to handle the exception itself but wants to pass it on.</p><pre>import java.io.IOException;<br><br>public class ThrowsExample {<br><br>    public static void readFile() throws IOException {<br>        throw new IOException(&quot;Unable to read file&quot;);<br>    }<br><br>    public static void main(String[] args) {<br>        try {<br>            readFile(); <br>        } catch (IOException e) {<br>            System.out.println(&quot;Caught IOException: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><p>In the above example, readFile method is throwing IOException(Checked Exception). So we are adding throws in that method defintion followed by exception which that method throws.</p><p><strong>Conclusion:-</strong></p><p>Exception handling is a powerful mechanism in Java that allows programmers to manage and handle runtime errors in a structured and controlled way. It is crucial for building robust and fault-tolerant applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=704b7d205256" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring Jacoco plugin for Maven Project]]></title>
            <link>https://medium.com/@prasanna8898/configuring-jacoco-plugin-for-maven-project-be28abd91bd0?source=rss-f92ac7795cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/be28abd91bd0</guid>
            <category><![CDATA[jacoco]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jacoco-configuration]]></category>
            <dc:creator><![CDATA[Prasanna Srikanth]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 07:14:29 GMT</pubDate>
            <atom:updated>2024-10-10T07:14:29.213Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>JaCoCo (Java Code Coverage) is a popular open-source tool used for measuring and reporting code coverage in Java applications. Its primary purposes include:</blockquote><blockquote><strong>Code Coverage Measurement</strong>: JaCoCo tracks how much of your code is executed during tests, helping to identify untested parts of your application.</blockquote><blockquote><strong>Test Quality Improvement</strong>: By highlighting areas lacking test coverage, it encourages developers to write additional tests, leading to more robust and reliable code.</blockquote><blockquote><strong>Integration with Build Tools</strong>: JaCoCo can easily integrate with various build tools like Maven and Gradle, as well as CI/CD pipelines, making it convenient to automate coverage reporting.</blockquote><blockquote><strong>Reporting</strong>: It generates detailed reports in various formats (HTML, XML, CSV) that visually represent coverage data, making it easier to analyze and communicate results.</blockquote><p><strong>Setting up Jacoco on Maven project</strong></p><blockquote>Add the below plugin on pom.xml</blockquote><pre><strong>&lt;plugin&gt;<br>    &lt;groupId&gt;org.jacoco&lt;/groupId&gt;<br>    &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;0.8.8&lt;/version&gt;<br>    &lt;executions&gt;<br>       &lt;execution&gt;<br>        &lt;id&gt;prepare-agent&lt;/id&gt;<br>        &lt;goals&gt;<br>         &lt;goal&gt;prepare-agent&lt;/goal&gt;<br>        &lt;/goals&gt;<br>       &lt;/execution&gt;<br>       &lt;execution&gt;<br>        &lt;id&gt;report&lt;/id&gt;<br>        &lt;phase&gt;verify&lt;/phase&gt;<br>        &lt;goals&gt;<br>         &lt;goal&gt;report&lt;/goal&gt;<br>        &lt;/goals&gt;<br>       &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</strong></pre><blockquote>Once the dependancy has been added, run the project using below command.</blockquote><pre><strong>mvn clean install</strong></pre><blockquote>After execution of the command, we can observe that target folder is generated similar to below structure.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*Kuo_tlU21qIxyn7DBq-_hQ.png" /><figcaption>target folder structure</figcaption></figure><blockquote>All the test reports will be stored in the index.html and we can see the test report by opening it in any browser.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YA0cfkHD7m2Q8lGQd7HTg.png" /><figcaption>Sample example of index.html</figcaption></figure><p><strong>Setting up Jacoco on Multi Module Maven project</strong></p><blockquote>In case of multiple module maven project, we can collect the test across all modules and create an aggregate report in main module.</blockquote><blockquote>Add the below plugin in parent pom.xml</blockquote><pre><strong>&lt;build&gt;<br>  &lt;plugins&gt;<br>    &lt;plugin&gt;<br>      &lt;groupId&gt;org.jacoco&lt;/groupId&gt;<br>      &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;<br>      &lt;executions&gt;<br>        &lt;execution&gt;<br>          &lt;id&gt;report&lt;/id&gt;<br>          &lt;goals&gt;<br>            &lt;goal&gt;report-aggregate&lt;/goal&gt;<br>          &lt;/goals&gt;<br>          &lt;phase&gt;verify&lt;/phase&gt;<br>        &lt;/execution&gt;<br>      &lt;/executions&gt;<br>    &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br>&lt;/build&gt;</strong></pre><blockquote>Add below plugin in pom.xml of all sub modules</blockquote><pre><strong>&lt;plugin&gt;<br>    &lt;groupId&gt;org.jacoco&lt;/groupId&gt;<br>    &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;0.8.5&lt;/version&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>          &lt;id&gt;prepare-agent&lt;/id&gt;<br>          &lt;goals&gt;<br>           &lt;goal&gt;prepare-agent&lt;/goal&gt;<br>          &lt;/goals&gt;<br>        &lt;/execution&gt;<br>        &lt;execution&gt;<br>          &lt;id&gt;report&lt;/id&gt;<br>          &lt;goals&gt;<br>           &lt;goal&gt;report&lt;/goal&gt;<br>          &lt;/goals&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</strong></pre><blockquote>Again once dependancy has been added, same steps can be followed for this as like simple Maven project.</blockquote><blockquote>Run a command <strong>mvn clean install </strong>and report will be created in a target folder.</blockquote><p><strong>Add on tips for debugging:-</strong></p><blockquote>In my case when i tried to setup jacoco, i have faced an issue as below:</blockquote><blockquote><strong>“Skipping JaCoCo execution due to missing execution data file”</strong></blockquote><blockquote>and the issue was related to property pointing to the JaCoCo runtime agent that can be passed as a VM argument.</blockquote><blockquote>Any plugin like maven-failsafe-plugin or maven-surefire-plugin which overrides &lt;argLine&gt; configuration throws this error.</blockquote><blockquote>Once removing all those configuration, report was successfully generated.</blockquote><blockquote>Related stackoverflow link which helped me to resolve the issue</blockquote><blockquote><a href="https://stackoverflow.com/questions/18107375/getting-skipping-jacoco-execution-due-to-missing-execution-data-file-upon-exec">https://stackoverflow.com/questions/18107375/getting-skipping-jacoco-execution-due-to-missing-execution-data-file-upon-exec</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be28abd91bd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>