Java Find Difference between two Strings using StringUtils Apache Commons Lang

Tags: Apache Commons Apache Commons Lang StringUtils String

Introduction

In this post we will show you Java example code how to find the difference between two Strings using StringUtils utility class of Apache Commons Lang library.

Setup Apache Commons Lang in Java project

If you are using Gradle build then add the following dependency configuration into build.gradle file.

compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.11'

Or add the following dependency XML tag to pom.xml file if you are using Maven build.

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

Or download commons-lang3-3.11.jar file from Apache Commons Lang download page at commons.apache.org

Compares Strings and reports on their differences

Example Java code org.apache.commons.lang3.StringUtils.difference()

import org.apache.commons.lang3.StringUtils;

public class StringUtilsDifferenceExample {
    public static void main(String[] args) {
        String result1 = StringUtils.difference(null, null);
        String result2 = StringUtils.difference("", "");
        String result3 = StringUtils.difference("", "simple solution");
        String result4 = StringUtils.difference("simple solution", "");
        String result5 = StringUtils.difference("simple solution", "simple example");

        System.out.println("result1: " + result1);
        System.out.println("result2: " + result2);
        System.out.println("result3: " + result3);
        System.out.println("result4: " + result4);
        System.out.println("result5: " + result5);
    }
}
Output:

result1: null
result2: 
result3: simple solution
result4: 
result5: example

Happy Coding 😊