Calculate Timings using Commons Lang StopWatch

You need to calculate timings of your code execution so you know how long a particular method or some block in your code take to finish it execution. Basically you can do this by capturing the start time and the end time using System.currentTimeMillis() and find the different. Another way to do it is to use the StopWatch class from Apache Commons Lang library. The StopWatch class can be found in the org.apache.commons.lang.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.example.commons.lang;

import org.apache.commons.lang.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

Beside 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.example.commons.lang;

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

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatchExample demo = new StopWatchExample();
        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 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: 0:00:03.000
Split 2: 0:00:05.525
Split 3: 0:00:06.525
Time: 6525

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.

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 integers elements in it.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.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 it self doesn’t not change the original array. In addition to clone primitive arrays the clone() method also work for cloning 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.example.commons.lang;

import org.apache.commons.lang.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 = (String[]) 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 from the when 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.

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 user Apache Commons Lang ArrayUtils.toString() method. This method can takes 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.example.commons.lang;

import org.apache.commons.lang.ArrayUtils;

public class ArrayUtilsToString {
    public static void main(String[] args) {
        //
        // Print 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 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.

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

This code snippet show you how to use HashCodeBuilder and EqualsBuilder class from the Apache  Commons Lang library to implement the hashCode() and equals() method of an object. To use both of these classes we just need to create instance of these class and append the properties that we will use the calculate the hashcode and to test for equality.

Implementing the hashCode() method first by creating the hashCode() method. Add the @Override annotation to make sure that we’ve override the correct method. Then we create an instance of HashCodeBuilder. Append the fields we’re gonna use to calculate the hashcode. The final result of the actual hashcode can be obtained by calling the toHashCode() from the instance of HashCodeBuilder.

/**
 * Implement the hashCode method using HashCodeBuilder.
 */
@Override
public int hashCode() {
    return new HashCodeBuilder().append(id).append(name).toHashCode();
}

We do the same to create the equals() method. First create the method, it takes a single argument type of java.lang.Object. Add the @Override annotation to make sure we override the correct method. On the first line you can check to see if the passed object is an instance of the same object, we use the instanceof operator. We then compare the values stored in both object using the EqualsBuilder class. To get the equality result you must remember to call the isEquals() method.

/**
 * Implement the equals method using the EqualsBuilder.
 */
@Override
public boolean equals(Object obj) {
    if (!(obj instanceof DummyUser)) {
        return false;
    }
    DummyUser that = (DummyUser) obj;
    return new EqualsBuilder().append(this.id, that.id)
            .append(this.name, that.name).isEquals();
}

Here the complete look of the snippet.

package org.kodejava.example.commons.lang;

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

public class DummyUser {
    private Long id;
    private String name;

    /**
     * Constructor to create an instance of this class.
     */
    public DummyUser() {
    }

    public static void main(String[] args) {
        DummyUser user1 = new DummyUser();
        user1.setId(10L);
        user1.setName("Carol");

        DummyUser user2 = new DummyUser();
        user2.setId(10L);
        user2.setName("Carol");

        System.out.println("user1.hashCode() = " + user1.hashCode());
        System.out.println("user2.hashCode() = " + user2.hashCode());

        System.out.println("user1.equals(user2) = " + user1.equals(user2));
    }

    //
    // Getters & Setters
    //
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * Implement the hashCode method using HashCodeBuilder.
     */
    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(id).append(name).toHashCode();
    }

    /**
     * Implement the equals method using the EqualsBuilder.
     */
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof DummyUser)) {
            return false;
        }
        DummyUser that = (DummyUser) obj;
        return new EqualsBuilder().append(this.id, that.id)
                .append(this.name, that.name).isEquals();
    }
}

The result of our code are:

user1.hashCode() = 64902380
user2.hashCode() = 64902380
user1.equals(user2) = true

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

In this example you’ll 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’ll be using an API provided by the Apache Commons Lang in this example. So here is the code snippet:

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.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 result produced by this snippet are:

15/06/2012 and 15/06/2012 is on the same day.
15/06/2012 and 15/06/2012 is on the same day.
15/06/2012 and 25/06/2012 is not on the same day.

How do I capitalize each word in a string?

This examples show you how to capitalize a string. We use methods from WordUtils class provided by the Apache commons-lang. We can use the WordUtils.capitalize(str) or WordUtils.capitalizeFully(str).

Let’s see an example below:

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.WordUtils;

public class WordCapitalize {
    public static void main(String[] args) {
        //
        // Capitalizes all the whitespace separated words in a string,
        // only the first letter of each word is capitalized.
        //
        String str = WordUtils.capitalize(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);

        //
        // Capitalizes all the whitespace separated words in a string
        // and the rest string to lowercase.
        //
        str = WordUtils.capitalizeFully(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);
    }
}

And here are the result of the program:

str = The Quick Brown Fox JUMPS OVER The Lazy Dog.
str = The Quick Brown Fox Jumps Over The Lazy Dog.

How do I generate a random alpha-numeric string?

The code below show you how to use the commons-lang RandomStringUtils class to generate some random string data.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.RandomStringUtils;

public class RandomStringUtilsDemo {
    public static void main(String[] args) {
        //
        // Creates a 64 chars length random string of number.
        //
        String result = RandomStringUtils.random(64, false, true);
        System.out.println("random = " + result);

        //
        // Creates a 64 chars length of random alphabetic string.
        //
        result = RandomStringUtils.randomAlphabetic(64);
        System.out.println("random = " + result);

        //
        // Creates a 32 chars length of random ascii string.
        //
        result = RandomStringUtils.randomAscii(32);
        System.out.println("random = " + result);

        //
        // Creates a 32 chars length of string from the defined array of
        // characters including numeric and alphabetic characters.
        //
        result = RandomStringUtils.random(32, 0, 20, true, true, "qw32rfHIJk9iQ8Ud7h0X".toCharArray());
        System.out.println("random = " + result);
    }
}

The example of our program result are:

random = 2377316738997278218735578855577798247976319451877477254850564896
random = wwqbLxlRynIdptAoxuSIfbABRoOFHLyKaFEscrUoBQjAHPOkcIqfHuMnhXVzaLCf
random = 6nQ0PJf<#VgIi='&d`*`Ru#i_exMoHXb
random = ZGbelXYEiLrlLBXKroCIDJPrevZPIGkD

How do I find text between two strings?

In this example we’ll use the StringUtils.substringBetween() method. Here we’ll extract the title and body of our HTML document. Let’s see the code.

package org.kodejava.example.commons.lang;

import java.util.Date;
import org.apache.commons.lang.StringUtils;

public class NestedString {
    public static void main(String[] args) {
        String helloHtml = "<html>" +
                "<head>" +
                "   <title>Hello World from Java</title>" +
                "<body>" +
                "Hello, today is: " + new Date() +
                "</body>" +
                "</html>";

        String title = StringUtils.substringBetween(helloHtml, "<title>", "</title>");
        String content = StringUtils.substringBetween(helloHtml, "<body>", "</body>");

        System.out.println("title = " + title);
        System.out.println("content = " + content);
    }
}

By print out the title and content we’ll see something similar to:

title = Hello World from Java
content = Hello, today is: Tue Apr 08 07:02:39 ICT 2008

How do I check for an empty string?

StringUtils.isBlank() method check to see is the string contains only whitespace characters, empty or has a null value. If these condition is true that the string considered blank.

There’s also a StringUtils.isEmpty(), only these method doesn’t check for whitespaces only string. For checking the oposite condition there are StringUtils.isNotBlank() and StringUtils.isNotEmpty().

Using this methods we can avoid repeating the code for checking empty string which can include more code to type then using these handy method.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class CheckEmptyString {
    public static void main(String[] args) {
        String var1 = null;
        String var2 = "";
        String var3 = "    ttt";
        String var4 = "Hello World";

        System.out.println("var1 is blank? = " + StringUtils.isBlank(var1));
        System.out.println("var2 is blank? = " + StringUtils.isBlank(var2));
        System.out.println("var3 is blank? = " + StringUtils.isBlank(var3));
        System.out.println("var4 is blank? = " + StringUtils.isBlank(var4));

        System.out.println("var1 is not blank? = " + StringUtils.isNotBlank(var1));
        System.out.println("var2 is not blank? = " + StringUtils.isNotBlank(var2));
        System.out.println("var3 is not blank? = " + StringUtils.isNotBlank(var3));
        System.out.println("var4 is not blank? = " + StringUtils.isNotBlank(var4));

        System.out.println("var1 is empty? = " + StringUtils.isEmpty(var1));
        System.out.println("var2 is empty? = " + StringUtils.isEmpty(var2));
        System.out.println("var3 is empty? = " + StringUtils.isEmpty(var3));
        System.out.println("var4 is empty? = " + StringUtils.isEmpty(var4));

        System.out.println("var1 is not empty? = " + StringUtils.isNotEmpty(var1));
        System.out.println("var2 is not empty? = " + StringUtils.isNotEmpty(var2));
        System.out.println("var3 is not empty? = " + StringUtils.isNotEmpty(var3));
        System.out.println("var4 is not empty? = " + StringUtils.isNotEmpty(var4));
    }
}

The result of our program are:

var1 is blank? = true
var2 is blank? = true
var3 is blank? = true
var4 is blank? = false

var1 is not blank? = false
var2 is not blank? = false
var3 is not blank? = false
var4 is not blank? = true

var1 is empty? = true
var2 is empty? = true
var3 is empty? = false
var4 is empty? = false

var1 is not empty? = false
var2 is not empty? = false
var3 is not empty? = true
var4 is not empty? = true

How do I get the nearest hour, minute, second of a date?

This example demonstrate how to use the DateUtils.round() method to get the nearest hour, minute and second of a date.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.FastDateFormat;

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

public class DateRounding {
    public static void main(String[] args) {
        FastDateFormat formatter = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT;

        Date now = new Date();
        System.out.println("now = " + formatter.format(now));

        // Get nearest second
        Date nearestSecond = DateUtils.round(now, Calendar.SECOND);
        System.out.println("nearestSecond = " + formatter.format(nearestSecond));

        // Get nearest minute
        Date nearestMinute = DateUtils.round(now, Calendar.MINUTE);
        System.out.println("nearestMinute = " + formatter.format(nearestMinute));

        // Get nearest hour
        Date nearestHour = DateUtils.round(now, Calendar.HOUR);
        System.out.println("nearestHour = " + formatter.format(nearestHour));
    }
}

Here are the program results:

now = 2008-04-05T00:34:55+07:00
nearestSecond = 2008-04-05T00:34:56+07:00
nearestMinute = 2008-04-05T00:35:00+07:00
nearestHour = 2008-04-05T01:00:00+07:00