0 and 1’s

Comparing Version Numbers

Posted in Java by Rama Krishna on July 5, 2008

I have written a small code snippet in Java for comparing the version numbers. Sample version numbers are 1.0, 2.2, 1.3.4, etc…

Just decided to share it.


import java.util.Scanner;

public class CompareVersion {

    final static int LESSER = -1;        //versionA is lesser than versionB
    final static int EQUALS = 0;        //versionA equal to versionB
    final static int GREATER = 1;        //versionA is greater then versionB

    public static int compareVersions(String versionA, String versionB) {
        Scanner a = (new Scanner(versionA)).useDelimiter("\\.");
        Scanner b = (new Scanner(versionB)).useDelimiter("\\.");
        int i, j;
        while (a.hasNext() && b.hasNext()) {
            i = Integer.parseInt(a.next());
            j = Integer.parseInt(b.next());
            if (i > j) {
                return CompareVersion.GREATER;
            } else if ( i < j) {
                return CompareVersion.LESSER;
            }
        }
        if (a.hasNext() && !b.hasNext()) {
		return CompareVersion.GREATER;
	}
	else if (!a.hasNext() && b.hasNext()) {
	        return CompareVersion.LESSER;
	}
	else {
		return CompareVersion.EQUALS;
	}
    }
}

Sample Usage Scenarios..

CompareVersion.compareVersions(“1.1″, “1.1″);
CompareVersion.compareVersions(“1.1″, “2.1″);
CompareVersion.compareVersions(“1.4.3″, “1.1″);

The code snippet can be included as part of a larger toolset to compare versions in different environments.

The code confirms to Java 1.4
The code uses the class java.util.Scanner and this this class is available in Java Version 5 and above. Hence, the code works only with Java 5 and above. Also, the code has been updated. The previous code missed an scenario.

I have rewritten the code for Java 1.4. I have used String manipulation method instead of using java.util.Scanner. The code is as follows.

public class CompareVersion {

	final static int LESSER = -1; // versionA is lesser than versionB
	final static int EQUALS = 0; // versionA equal to versionB
	final static int GREATER = 1; // versionA is greater then versionB

	public static int compareVersions(String versionA, String versionB) {
		String[] a = versionA.split("\\.");
		String[] b = versionB.split("\\.");
		int i, j;
		int index = 0;
		while ((index < a.length) && (index < b.length)) {
			i = Integer.parseInt(a[index]);
			j = Integer.parseInt(b[index]);
			if (i > j) {
				return CompareVersion.GREATER;
			} else if (i < j) {
				return CompareVersion.LESSER;
			}
			index++;
		}
		if ((index < a.length) && (index == b.length)) {
			return CompareVersion.GREATER;
		} else if ((index == a.length) && (index < b.length)) {
			return CompareVersion.LESSER;
		} else {
			return CompareVersion.EQUALS;
		}
	}
}


Tagged with: ,