Calculate elapsed time using Apache Commons Lang StopWatch

You need to calculate the timing or elapsed time of your code execution, so you know how long a particular method or some block of code take to finish its execution. You can do this by capturing the start-time and the end-time using System.currentTimeMillis() and find their differences. Another way is to use the StopWatch class from the Apache Commons Lang library. The StopWatch class can be found in the org.apache.commons.lang3.time package.

The simplest steps to use the StopWatch is to create an instance of the StopWatch class, start the stopwatch by calling the start() method. After the stopwatch is started you can execute the target method or block of code you want to watch and call the stop() method to complete the timing session. To get the time of the stopwatch, you can call the getTime() method.

Now, let’s see the code for the process described above.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.StopWatch;

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatchExample demo = new StopWatchExample();
        demo.timingOne();
    }

    private void timingOne() {
        // Create an instance of StopWatch.
        StopWatch stopWatch = new StopWatch();

        // Start the watch, do some task and stop the watch.
        stopWatch.start();
        doSomeTask(5000);
        stopWatch.stop();

        // Print out the total time of the watch
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Here is the output of the code above:

Time: 5000

Besides doing a simple timing calculation using the start() and stop() followed by the getTime() methods, the StopWatch class also provides methods for splitting the time, suspend and resuming the stopwatch. You can use the split(), suspend() and resume() method respectively. To get the split time you can call the toSplitString() method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.StopWatch;

public class StopWatchAnotherExample {
    public static void main(String[] args) {
        StopWatchAnotherExample demo = new StopWatchAnotherExample();
        demo.timingTwo();
    }

    private void timingTwo() {
        // Create an instance of StopWatch and start the stopwatch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Do some task and split the stopwatch time.
        doSomeTask(3000);
        stopWatch.split();
        System.out.println("Split 1: " + stopWatch.toSplitString());

        // Suspend the stopwatch and resume the stopwatch.
        stopWatch.suspend();
        doSomeTask(4000);
        stopWatch.resume();

        // Do some task and split the stopwatch time.
        doSomeTask(2500);
        stopWatch.split();
        System.out.println("Split 2: " + stopWatch.toSplitString());

        // Do some task and split the stopwatch time.
        doSomeTask(1000);
        stopWatch.split();
        System.out.println("Split 3: " + stopWatch.toSplitString());

        // Stop the stopwatch and the total execution time.
        stopWatch.stop();
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The code snippet above will output something like this:

Split 1: 00:00:03.004
Split 2: 00:00:05.518
Split 3: 00:00:06.522
Time: 6522

Another method that you can find in the StopWatch class is the getStartTime() which will return the stopwatch start time. The reset() method will reset the stopwatch. To remove a split, you can call the unsplit() method.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I clone an array variable?

You have an array variable, and you want to make a clone of this array into a new array variable. To do this, you can use Apache Commons Lang ArrayUtils.clone() method. The code snippet below demonstrates the cloning of a primitive array that contains some integer elements in it.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class PrimitiveArrayClone {
    public static void main(String[] args) {
        int[] fibonacci = new int[]{1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
        System.out.println("fibonacci = " + ArrayUtils.toString(fibonacci));

        int[] clone = ArrayUtils.clone(fibonacci);
        System.out.println("clone = " + ArrayUtils.toString(clone));
    }
}

The fibonacci array contents were cloned into the clone array, and we print out the content using ArrayUtils.toString() method.

fibonacci = {1,1,2,3,5,8,13,21,34,55}
clone = {1,1,2,3,5,8,13,21,34,55}

In the code snippet above the clone() method create a reference to a new array. The clone() method itself doesn’t change the original array. In addition to clone primitive arrays, the clone() method also work for cloning an array of objects.

As an example we will create an array of String objects and clone it using the ArrayUtils.clone() method. To display the contents of the array, we will again use the ArrayUtils.toString() method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ObjectArrayClone {
    public static void main(String[] args) {
        String[] colors = new String[]{"Red", "Green", "Blue", "Yellow"};
        System.out.println("colors = " + ArrayUtils.toString(colors));

        String[] clone = ArrayUtils.clone(colors);
        System.out.println("clone = " + ArrayUtils.toString(clone));
    }
}

And here is the result:

colors = {Red,Green,Blue,Yellow}
clone = {Red,Green,Blue,Yellow}

The only different between cloning a primitive array and object array using the ArrayUtils.clone() method is that when cloning an object such as String, Date, etc. we need to cast the result of the clone() method into the targeted object type.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I print the contents of an array variable?

You need to print the contents of an array variable. The long way to it is to user a loop to print each element of the array. To simplify this, you can use the Apache Commons Lang ArrayUtils.toString() method. This method can take any array as a parameter and print out the contents separated by commas and surrounded by curly brackets. When you need to print a specific string when the array is null, you can provide the second string argument to this method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtilsToString {
    public static void main(String[] args) {
        // Print an int array as string.
        int[] numbers = {1, 2, 3, 5, 8, 13, 21, 34};
        System.out.println("Numbers = " + ArrayUtils.toString(numbers));

        // Print string array as string.
        String[] grades = {"A", "B", "C", "D", "E", "F"};
        System.out.println("Grades = " + ArrayUtils.toString(grades));

        // Print a multidimensional array as string.
        int[][] matrix = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}};
        System.out.println("Matrix = " + ArrayUtils.toString(matrix));

        // Return "Empty" when the array is null.
        String[] colors = null;
        System.out.println("Colors = " + ArrayUtils.toString(colors, "None"));
    }
}

The output of the code snippet above:

Numbers = {1,2,3,5,8,13,21,34}
Grades = {A,B,C,D,E,F}
Matrix = {{0,1,2},{1,2,3},{2,3,4}}
Colors = None

If you are using the JDK 1.5, or later, you can actually use the java.util.Arrays class to do the same thing as the org.apache.commons.lang.ArrayUtils class does.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How to implement the hashCode and equals method using Apache Commons?

package org.kodejava.commons.lang;

public class ObjectHashCodeDemo {

    public static void main(String[] args) {
        Book book1 = new Book(1L, "Spring Boot in Action", "Craig Walls");
        Book book2 = new Book(2L, "Docker in Action", "Jeff Nickoloff");
        Book book3 = book1;

        System.out.println("book1.hashCode() = " + book1.hashCode());
        System.out.println("book2.hashCode() = " + book2.hashCode());
        System.out.println("book3.hashCode() = " + book3.hashCode());
    }
}
package org.kodejava.commons.lang;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.io.Serializable;

public class Book implements Serializable {
    private Long id;
    private String title;
    private String author;

    public Book(Long id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }

    //~ Implements getters and setters here.

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof Book)) {
            return false;
        }

        Book that = (Book) o;
        return new EqualsBuilder()
            .append(this.id, that.id)
            .append(this.title, that.title)
            .append(this.author, that.author)
            .isEquals();

        // You can also use reflection of the EqualsBuilder class.
        // return EqualsBuilder.reflectionEquals(this, that);
    }

    public int hashCode() {
        return new HashCodeBuilder()
            .append(id)
            .append(title)
            .append(author)
            .toHashCode();

        // Or even use the simplest method using reflection below.
        // return HashCodeBuilder.reflectionHashCode(this);
    }
}

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I checks if two dates are on the same day?

In this example, you will learn how to find out if two defined date objects are on the same day. It means that we are only interested in the date information and ignoring the time information of these date objects. We will be using an API provided by the Apache Commons Lang library. So here is the code snippet:

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.DateUtils;

import java.util.Calendar;
import java.util.Date;

public class CheckSameDay {
    public static void main(String[] args) {
        Date date1 = new Date();
        Date date2 = new Date();

        // Checks to see if the dates is on the same day.
        if (DateUtils.isSameDay(date1, date2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is on the same day.%n", date1, date2);
        }

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        // Checks to see if the calendars is on the same day.
        if (DateUtils.isSameDay(cal1, cal2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is on the same day.%n", cal1, cal2);
        }

        cal2.add(Calendar.DAY_OF_MONTH, 10);
        if (!DateUtils.isSameDay(cal1, cal2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is not on the same day.", cal1, cal2);
        }
    }
}

The example results produced by this snippet are:

31/10/2021 and 31/10/2021 is on the same day.
31/10/2021 and 31/10/2021 is on the same day.
31/10/2021 and 10/11/2021 is not on the same day.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central