<?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 Daniel Baumann on Medium]]></title>
        <description><![CDATA[Stories by Daniel Baumann on Medium]]></description>
        <link>https://medium.com/@dr4wone?source=rss-64ddfd525c04------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UV-7lLSdkQ3GrMk2YVfoHQ.jpeg</url>
            <title>Stories by Daniel Baumann on Medium</title>
            <link>https://medium.com/@dr4wone?source=rss-64ddfd525c04------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:43:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dr4wone/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[Unveiling the Mysteries of Vectors, Arrays, and Matrices in Java: A Instructive Guide]]></title>
            <link>https://medium.com/@dr4wone/unveiling-the-mysteries-of-vectors-arrays-and-matrices-in-java-a-instructive-guide-815ffb0e85a5?source=rss-64ddfd525c04------2</link>
            <guid isPermaLink="false">https://medium.com/p/815ffb0e85a5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Daniel Baumann]]></dc:creator>
            <pubDate>Tue, 14 Nov 2023 01:36:59 GMT</pubDate>
            <atom:updated>2023-11-14T01:37:54.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCb8NI5WyC1tH0Sx3dkJVw.jpeg" /></figure><p>If you’ve taken your first steps into the vast universe of Java programming, you’ve likely encountered terms like vector, array, and matrix. At first glance, they may seem confusing and interchangeable, but we have good news: unraveling these mysteries can be as exciting as solving a puzzle!</p><h3>What Are They and Why Are They Important?</h3><p>Before delving into the details, let’s grasp the essence of these concepts.</p><p><strong>Vector:</strong></p><ul><li>Definition: Picture a single corridor where you can place several boxes side by side. Each box has a number, and you can easily access them. That’s a vector! In Java, a vector is a sequence of elements of the same type, accessed by indices.</li><li>Example:</li></ul><pre>int[] vector = {1, 2, 3, 4, 5};</pre><p><strong>Array:</strong></p><ul><li>Definition: Now, think of a warehouse with multiple shelves. Each shelf can contain various boxes, and each box has a number. This more flexible and comprehensive structure is what we call an array in Java. It can be unidimensional (like a vector) or multidimensional.</li><li>Example:</li></ul><pre>// Unidimensional array<br>int[] unidimensionalArray = {1, 2, 3, 4, 5};<br><br>// Bidimensional array (matrix)<br>int[][] matrix = {<br>    {1, 2, 3},<br>    {4, 5, 6},<br>    {7, 8, 9}<br>};</pre><p><strong>Matrix:</strong></p><ul><li>Definition: Now, expand our warehouse to have more than one shelf. Each shelf is a row, and each box within the shelf has a number. This is our matrix in Java, a bidimensional structure.</li><li>Example:</li></ul><pre>int[][] matrix = {<br>    {1, 2, 3},<br>    {4, 5, 6},<br>    {7, 8, 9}<br>};</pre><h3>Playing with Code: Practical Challenge</h3><p>The best way to understand is to practice! Here’s a challenge for you:</p><ol><li><strong>Create a vector in Java:</strong></li></ol><ul><li>Initialize it with your lucky numbers.</li><li>Print each element of the vector.</li></ul><pre>int[] myVector = {7, 14, 21, 28, 35};<br><br>for (int i = 0; i &lt; myVector.length; i++) {<br>    System.out.println(&quot;Element &quot; + i + &quot;: &quot; + myVector[i]);<br>}</pre><p><strong>2. Create a 3x3 matrix in Java:</strong></p><ul><li>Fill each cell with your birthdate numbers.</li><li>Print each element of the matrix.</li></ul><pre>int[][] myMatrix = {<br>    {1, 2, 3},<br>    {4, 5, 6},<br>    {7, 8, 9}<br>};<br><br>for (int i = 0; i &lt; myMatrix.length; i++) {<br>    for (int j = 0; j &lt; myMatrix[i].length; j++) {<br>        System.out.print(myMatrix[i][j] + &quot; &quot;);<br>    }<br>    System.out.println();<br>}</pre><h3>Choosing Between Vectors and Arrays:</h3><p>In the vast landscape of Java programming, the decision to use a vector or an array is not a one-size-fits-all situation. Each has its strengths and ideal use cases, and understanding when to employ one over the other is crucial for efficient and effective coding. Let’s explore scenarios where vectors and arrays shine, using Java language examples to guide us.</p><h3>When to Embrace Vectors:</h3><p><strong>1. Dynamic Size:</strong></p><ul><li>Example Scenario:</li><li>Imagine you’re building a program that dynamically receives user inputs, and the number of inputs is not predetermined. This is where vectors, particularly the ArrayList class, come to the rescue.</li><li>Code Example:</li></ul><pre>import java.util.Vector;<br><br>// Creating a Vector to store user inputs<br>Vector&lt;String&gt; userInputVector = new Vector&lt;&gt;();<br><br>// Adding user inputs to the Vector<br>userInputVector.add(&quot;Input 1&quot;);<br>userInputVector.add(&quot;Input 2&quot;);<br>// ...</pre><p><strong>2. Easy Manipulation:</strong></p><ul><li>Example Scenario:</li><li>Consider a situation where you need to frequently add or remove elements from a collection. Vectors provide convenient methods for these operations.</li><li>Code Example:</li></ul><pre>import java.util.Vector;<br><br>// Creating a Vector<br>Vector&lt;Integer&gt; numbers = new Vector&lt;&gt;();<br><br>// Adding elements<br>numbers.add(1);<br>numbers.add(2);<br><br>// Removing an element<br>numbers.remove(0);</pre><h3>When to Embrace Arrays:</h3><p><strong>1. Fixed Size:</strong></p><ul><li>Example Scenario:</li><li>If you know in advance the exact number of elements you’ll be storing, and that number won’t change during the program’s execution, using a traditional array is a suitable choice.</li><li>Code Example:</li></ul><pre>// Creating an array with a fixed size<br>int[] fixedSizeArray = new int[5];<br><br>// Assigning values to array elements<br>fixedSizeArray[0] = 10;<br>fixedSizeArray[1] = 20;<br>// ...</pre><p><strong>2. Performance Considerations:</strong></p><ul><li>Example Scenario:</li><li>In scenarios where optimal performance for simple element access and manipulation is critical, arrays may outshine some dynamic data structures.</li><li>Code Example:</li></ul><pre>// Creating an array<br>String[] colors = {&quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;};<br><br>// Accessing elements<br>System.out.println(colors[0]);  // Output: Red</pre><h3>How to Make the Right Choice:</h3><p><strong>1. Dynamic vs. Fixed Size:</strong></p><ul><li>Guidance:</li><li>Opt for a vector if the size of your collection might change during runtime.</li><li>Choose an array if the size is fixed and known in advance.</li></ul><p><strong>2. Performance vs. Convenience:</strong></p><ul><li>Guidance:</li><li>Opt for an array for better performance in scenarios where size is fixed and direct element access is crucial.</li><li>Choose a vector for dynamic sizing and when built-in methods for manipulation are convenient.</li></ul><p>Remember, Java’s ArrayList is a commonly used dynamic array (vector) implementation, and often, the choice between an array and a vector boils down to your specific use case and performance requirements.</p><h3>The quick job interview definition answer:</h3><p>A vector is a one-dimensional structure, an array can be either one-dimensional or multidimensional, and a matrix is a specific two-dimensional structure. The use of these terms may vary depending on the programming language and context.</p><h3>Unraveling the Mysteries</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCb8NI5WyC1tH0Sx3dkJVw.jpeg" /></figure><p>Vectors, arrays, and matrices are powerful tools that make Java programming more flexible and dynamic. Now that you’ve unraveled these mysteries, feel free to explore and experiment. Who knows what fun and exciting challenges you’ll encounter along the way!</p><p>Enjoy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=815ffb0e85a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Equals vs. compareTo in Java: Understanding the Differences]]></title>
            <link>https://medium.com/@dr4wone/equals-vs-compareto-in-java-understanding-the-differences-fce0a0d4b292?source=rss-64ddfd525c04------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce0a0d4b292</guid>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java11]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[equals-method-java]]></category>
            <dc:creator><![CDATA[Daniel Baumann]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 23:25:18 GMT</pubDate>
            <atom:updated>2023-04-09T23:25:18.643Z</atom:updated>
            <content:encoded><![CDATA[<p>Java provides two methods for comparing objects: equals() and compareTo(). Both methods are used to compare objects, but they have different purposes and implementations. In this article, we will explore the differences between equals() and compareTo() and provide examples to illustrate how they work.</p><h3>Equals()</h3><p>The equals() method is used to compare objects for equality. It returns true if two objects are equal and false if they are not. By default, the equals() method in Java compares objects based on their memory location. In other words, if two objects have the same memory address, they are considered equal.</p><p>However, we can override the default implementation of equals() to compare objects based on their properties. Let’s consider a simple example to see how it works.</p><h4>Example: Implementing equals() with ID</h4><p>Suppose we have a Person class that contains a name and an ID. We want to compare two Person objects based on their ID, not on their memory location. Here is an implementation of the equals() method that compares Person objects based on their ID:</p><pre>public class Person {<br>    private String name;<br>    private int id;<br><br>    public Person(String name, int id) {<br>        this.name = name;<br>        this.id = id;<br>    }<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (o == null || getClass() != o.getClass()) {<br>            return false;<br>        }<br><br>        Person person = (Person) o;<br>        return id == person.id;<br>    }<br>}</pre><p>In this implementation, we first check if the argument is null or not an instance of the Person class. If either of these conditions is true, we return false. If the argument is an instance of the Person class, we cast it to a Person object and compare its ID to the ID of the current object. If the IDs are equal, we return true, indicating that the two objects are equal.</p><p>Note that we only compare the ID property in this implementation. If two Person objects have the same ID, they are considered equal, regardless of their name.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        Person p1 = new Person(1, &quot;John&quot;);<br>        Person p2 = new Person(1, &quot;Jane&quot;);<br><br>        System.out.println(p1.equals(p2)); // true<br>        System.out.println(p1.hashCode() == p2.hashCode()); // true<br><br>        Set&lt;Person&gt; set = new HashSet&lt;&gt;();<br>        set.add(p1);<br>        set.add(p2);<br><br>        System.out.println(set.size()); // 1<br>    }<br>}<br><br>//*******************************<br><br>true<br>true<br>1</pre><h4>Example: Implementing equals() with all elements</h4><p>Now let’s consider another example where we want to compare two objects based on all their properties. We can implement the equals() method as follows:</p><pre>public class Book {<br>    private String title;<br>    private String author;<br>    private int pages;<br><br>    public Book(String title, String author, int pages) {<br>        this.title = title;<br>        this.author = author;<br>        this.pages = pages;<br>    }<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (o == this) {<br>            return true;<br>        }<br><br>        if (!(o instanceof Book)) {<br>            return false;<br>        }<br><br>        Book book = (Book) o;<br>        return Objects.equals(title, book.title) &amp;&amp;<br>                Objects.equals(author, book.author) &amp;&amp;<br>                pages == book.pages;<br>    }<br>}</pre><p>In this implementation, we first check if the argument is the same object as the current object. If it is, we return true. If the argument is not an instance of the Book class, we return false. If the argument is a Book object, we compare all its properties to the properties of the current object. If all properties are equal, we return true, indicating that the two objects are equal.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        Book b1 = new Book(1, &quot;The Great Gatsby&quot;);<br>        Book b2 = new Book(1, &quot;To Kill a Mockingbird&quot;);<br><br>        System.out.println(b1.equals(b2)); // false<br>        System.out.println(b1.hashCode() == b2.hashCode()); // false<br><br>        Set&lt;Book&gt; set = new HashSet&lt;&gt;();<br>        set.add(b1);<br>        set.add(b2);<br><br>        System.out.println(set.size()); // 2<br>    }<br>}<br><br>//**************************************************<br><br>false<br>false<br>2</pre><p>Note that we use the Objects.equals() method to compare the title and author properties because they are Strings. We use the == operator to compare the pages property because it is an int.</p><h3>CompareTo()</h3><p>The compareTo() method is used to compare objects based on their natural ordering. It returns a negative integer, zero, or a positive integer, depending on whether the current object is less than, equal to, or greater than the object passed as an argument. The natural ordering is defined by the class itself and should be consistent with the equals method. In cases where the natural ordering of a class is not well-defined, such as when comparing two BigDecimal objects, the compareTo method may not be consistent with the equals method, leading to unexpected behavior in certain situations. It’s important to keep this in mind when implementing these methods to ensure that they are consistent with each other and with the natural ordering of the class.</p><p>Now, let’s see an example of implementing the compareTo method. The compareTo method is used for ordering objects of a class, and it should return a negative integer, zero, or a positive integer depending on whether the object being compared is less than, equal to, or greater than the object passed as an argument.</p><p>Let’s say we have a class called Person, which has two fields: name and age. We want to compare instances of this class by age. Here is an example implementation of the compareTo method:</p><pre>        Person p1 = new Person(&quot;John&quot;, 30);<br>        Person p2 = new Person(&quot;Jane&quot;, 25);<br><br>        System.out.println(p1.compareTo(p2)); // 1<br>        System.out.println(p2.compareTo(p1)); // -1<br>        System.out.println(p1.compareTo(p1)); // 0</pre><p>In this example, we use the static method Integer.compare to compare the ages of two Person objects. This method returns a negative integer if the age of the current object is less than the age of the other object, zero if they are equal, and a positive integer if the age of the current object is greater than the age of the other object.</p><pre>        Integer a = 10;<br>        Integer b = 20;<br><br>        System.out.println(a.compareTo(b)); // -1<br>        System.out.println(b.compareTo(a)); // 1<br>        System.out.println(a.compareTo(a)); // 0</pre><p>It’s important to note that when implementing the compareTo method, we must ensure that it is consistent with the equals method. That means that if two objects are equal according to the equals method, they must also return zero when compared using the compareTo method. Failure to do so can lead to unexpected behavior in certain situations.</p><p>Let’s modify the Person class to add an equals method that compares both name and age fields:</p><pre>public class Person {<br>    private String name;<br>    private int age;<br><br>    // constructor, getters and setters<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (o == null || getClass() != o.getClass()) return false;<br>        Person person = (Person) o;<br>        return age == person.age &amp;&amp;<br>                Objects.equals(name, person.name);<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        return Objects.hash(name, age);<br>    }<br>}</pre><p>In this example, we override the equals method inherited from the Object class to compare both name and age fields. We also override the hashCode method to ensure that objects that are equal according to the equals method have the same hash code.</p><p>It’s worth noting that the equals and hashCode methods should always be implemented together, as they are used in many Java collections, such as HashSet and HashMap.</p><p>In conclusion, while both the equals and compareTo methods are used for comparing objects, they serve different purposes. The equals method is used to test for equality of objects, while the compareTo method is used for ordering objects. When implementing these methods, it’s important to ensure that they are consistent with each other, to avoid unexpected behavior in certain situations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce0a0d4b292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics in Java: The Lifesaver You Never Knew You Needed]]></title>
            <link>https://medium.com/@dr4wone/generics-in-java-the-lifesaver-you-never-knew-you-needed-e584fea42a90?source=rss-64ddfd525c04------2</link>
            <guid isPermaLink="false">https://medium.com/p/e584fea42a90</guid>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <dc:creator><![CDATA[Daniel Baumann]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 01:37:42 GMT</pubDate>
            <atom:updated>2023-04-04T01:40:18.986Z</atom:updated>
            <content:encoded><![CDATA[<p>Picture this: You’re a Java developer working on a complex project that involves handling a lot of different data types. You’ve got your lists, your maps, your sets, and they’re all filled with different kinds of objects. It’s a nightmare trying to keep track of all of them, and you’re constantly worried about accidentally passing the wrong type of object to a method or function. But fear not, my fellow developer, for there is a solution to your woes: generics.</p><p>Generics are a feature in Java that allow you to write code that can work with multiple data types. Think of them as placeholders that can be replaced with actual types when you use them. They were introduced in Java 5 and have since become an essential part of the language. But enough with the history lesson, let’s dive into some code examples.</p><p>Let’s say you’re working on a project that involves sorting a list of objects. Without generics, you might write something like this:</p><pre>List unsortedList = new ArrayList();<br>unsortedList.add(&quot;apple&quot;);<br>unsortedList.add(&quot;banana&quot;);<br>unsortedList.add(42); // oops, we added an integer to a list of strings<br>Collections.sort(unsortedList);</pre><p>This code might compile without any errors, but when you run it, you’ll get a ClassCastException because you’re trying to sort a list that contains both strings and integers. But fear not, for with generics, we can avoid this problem entirely:</p><pre>List&lt;String&gt; unsortedList = new ArrayList&lt;&gt;();<br>unsortedList.add(&quot;apple&quot;);<br>unsortedList.add(&quot;banana&quot;);<br>unsortedList.add(42); // compiler error: incompatible types<br>Collections.sort(unsortedList);</pre><p>By specifying that our list should only contain strings, we’ve eliminated the possibility of adding an integer to it. And when we try to add an integer anyway, the compiler will catch it and give us an error. This might seem like a small improvement, but it can save you a lot of headaches down the line.</p><p>But the power of generics doesn’t stop there. Let’s say you’re working on a method that needs to return a specific type of object. Without generics, you might write something like this:</p><pre>public Object getObject() {<br>    // some code here<br>    return someObject;<br>}</pre><p>This method can return any type of object, which might be fine in some cases, but it’s not very specific. With generics, we can make our code more precise:</p><pre>public &lt;T&gt; T getObject(Class&lt;T&gt; clazz) {<br>    // some code here<br>    return clazz.cast(someObject);<br>}</pre><p>Now our method can return an object of any type, as long as we specify what type we want when we call the method. For example:</p><pre>String myString = getObject(String.class);<br>Integer myInteger = getObject(Integer.class);</pre><p>By using generics, we’ve made our code more flexible and more specific at the same time. It’s a win-win.</p><p>Now let’s take a look at this situation I have faced in my day-to-day work:</p><p>I work in this extensive legacy codebase, with more than a thousand classes and tables in the database. The base code was originally written in Java 7 and has since been upgraded to Java 8. You get the picture! In this specific case, we are not able to refactor all the base code to implement Builder Factories in all the classes we have. It’s an enormous and painful task. In this case, generics have saved my life! I have implemented a generic class to use the Builder pattern in whichever class I want! Take a look at the class:</p><pre>public class Builder&lt;T&gt; {<br>    // A Supplier is a functional interface that takes no arguments and returns a value.<br>    // In this case, the Supplier is used to create a new instance of a generic type T.<br>    private final Supplier&lt;T&gt; instantiator;<br>    <br>    // A List of Consumer functions, where each Consumer modifies a T instance in some way.<br>    private final List&lt;Consumer&lt;T&gt;&gt; instanceModifiers = new ArrayList&lt;&gt;();<br><br>    // Constructor that takes a Supplier of T instances<br>    public Builder(Supplier&lt;T&gt; instantiator) {<br>        this.instantiator = instantiator;<br>    }<br><br>    // Static factory method that creates a new Builder with the given instantiator<br>    public static &lt;T&gt; Builder&lt;T&gt; of(Supplier&lt;T&gt; instantiator) {<br>        return new Builder&lt;&gt;(instantiator);<br>    }<br><br>    // Method that takes a BiConsumer and a value of type U, and adds a new Consumer to the list<br>    // of instanceModifiers. The new Consumer uses the BiConsumer to modify a T instance with the<br>    // given value.<br>    public &lt;U&gt; Builder&lt;T&gt; with(BiConsumer&lt;T, U&gt; consumer, U value) {<br>        Consumer&lt;T&gt; c = instance -&gt; consumer.accept(instance, value);<br>        instanceModifiers.add(c);<br>        return this;<br>    }<br><br>    // Method that creates a new instance of T using the instantiator, applies all of the instanceModifiers<br>    // to it, and returns the result.<br>    public T build() {<br>        T value = instantiator.get();<br>        instanceModifiers.forEach(modifier -&gt; modifier.accept(value));<br>        instanceModifiers.clear();<br>        return value;<br>    }<br>}</pre><p>This class allows us to implement the Builder pattern without having to modify every class in our codebase. We can simply create a new instance of the Builder class and use it to build objects of any type. Let&#39;s take a look at some code examples:</p><pre>public class Person {<br>    private String name;<br>    private int age;<br>    private String address;<br><br>    // getters and setters<br>}<br><br>// using the builder to create a Person object<br>Person person = Builder.of(Person::new)<br>                .with(Person::setName, &quot;John Doe&quot;)<br>                .with(Person::setAge, 30)<br>                .build();</pre><p>In this example, we’re using the Builder class to create a Person object. We start by creating a new instance of the Builder class and passing in a new Person object by reference. We then use the with method to set the name and age fields of the Person object. Finally, we call the build method to create the final Person object.</p><p>Another example:</p><pre>public class Car {<br>    private String make;<br>    private String model;<br>    private int year;<br><br>    public Car(String make, String model, int year) {<br>        this.make = make;<br>        this.model = model;<br>        this.year = year;<br>    }<br><br>    // getters and setters<br>}<br><br>// using the builder to create a Car object<br>Car car = Builder.of(() -&gt; new Car(null, null, 0))<br>            .with(Car::setMake, &quot;Toyota&quot;)<br>            .with(Car::setModel, &quot;Camry&quot;)<br>            .with(Car::setYear, 2021)<br>            .build();</pre><p>In this example, we’re using the Builder class to create a Car object. We follow the same pattern as before, creating a new instance of the Builder class and passing in a new Car object by reference. We then use the with method to set the make, model, and year fields of the Car object. Finally, we call the build method to create the final Car object.</p><p>In conclusion, generics in Java can be a lifesaver for developers who work with complex data types. They allow us to write code that is both more flexible and more specific, which can save us from a lot of headaches down the line. So the next time you’re working on a Java project, remember to use generics. Your future self will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e584fea42a90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Battle of String Concatenation in Java: Which Method Reigns Supreme?]]></title>
            <link>https://medium.com/@dr4wone/the-battle-of-string-concatenation-in-java-which-method-reigns-supreme-86d07d5d0525?source=rss-64ddfd525c04------2</link>
            <guid isPermaLink="false">https://medium.com/p/86d07d5d0525</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[string]]></category>
            <dc:creator><![CDATA[Daniel Baumann]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 14:25:19 GMT</pubDate>
            <atom:updated>2023-04-09T23:28:26.226Z</atom:updated>
            <content:encoded><![CDATA[<p>String concatenation is a common task in programming, and in Java, there are two ways to do it: using the + operator or the StringBuilder class. But did you know that these two methods have different performance characteristics?</p><p>Let’s put it in simpler terms. Imagine you’re trying to make a sandwich. You have two slices of bread and a slice of ham. Using the + operator is like getting a new plate every time you add a new ingredient - it&#39;s inefficient and creates unnecessary dishes. On the other hand, using StringBuilder is like having a single plate that you can add ingredients to without creating a mess.</p><p>But don’t take our word for it — let’s look at the numbers. We conducted a benchmark test to measure the time taken to concatenate the strings “ab” and “c” using both methods.</p><p>Using the + operator:</p><pre>long startTime = System.nanoTime();<br><br>String text = &quot;ab&quot;;<br>text += &quot;c&quot;;<br><br>long endTime = System.nanoTime();<br>long duration = endTime - startTime;<br>System.out.println(&quot;Time taken: &quot; + duration + &quot; nanoseconds&quot;);</pre><p>Using StringBuilder:</p><pre>long startTime = System.nanoTime();<br><br>StringBuilder textBuilder = new StringBuilder(&quot;ab&quot;);<br>textBuilder.append(&quot;c&quot;);<br><br>long endTime = System.nanoTime();<br>long duration = endTime - startTime;<br>System.out.println(&quot;Time taken: &quot; + duration + &quot; nanoseconds&quot;);</pre><p>The + operator method took 1122 nanoseconds, while the StringBuilder method took only 43 nanoseconds! That&#39;s a massive difference in performance.</p><p>Concatenating a string 100,000 times with the + operator can result in poor performance, while using StringBuilder can be much more efficient. Let´s see the following code :</p><pre>long startTime = System.nanoTime();<br><br>// Using the + operator<br>String text = &quot;&quot;;<br>for (int i = 0; i &lt; 100000; i++) {<br>    text += &quot;hello&quot;;<br>}<br><br>long endTime = System.nanoTime();<br>long duration = endTime - startTime;<br>System.out.println(&quot;Using + operator: Time taken = &quot; + duration + &quot; nanoseconds&quot;);<br><br>startTime = System.nanoTime();<br><br>// Using StringBuilder<br>StringBuilder textBuilder = new StringBuilder();<br>for (int i = 0; i &lt; 100000; i++) {<br>    textBuilder.append(&quot;hello&quot;);<br>}<br><br>endTime = System.nanoTime();<br>duration = endTime - startTime;<br>System.out.println(&quot;Using StringBuilder: Time taken = &quot; + duration + &quot; nanoseconds&quot;);</pre><p>When we run this code, we get the following output:</p><pre>Using + operator: Time taken = 263273505 nanoseconds<br>Using StringBuilder: Time taken = 41124 nanoseconds</pre><p>As you can see, the difference in performance between the + operator and StringBuilder is even more significant when we&#39;re concatenating the string many times in a loop. In this case, using StringBuilder is over 6,000 times faster than using the + operator!</p><p>So, the next time you’re concatenating strings in Java, remember that using StringBuilder can significantly improve your program&#39;s efficiency.</p><p>Fun fact: Did you know that the StringBuilder class was introduced in Java 1.5? Before that, the only way to concatenate strings was to use the + operator, which resulted in poor performance for large concatenations. Thank goodness for StringBuilder!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86d07d5d0525" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>