Java
version comparison
string manipulation
programming
Java tutorial

How do you compare two version Strings in Java?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

When dealing with software versioning, comparing version strings becomes crucial, especially for updating systems, dependency management, and feature roll-outs. A version string often follows the semantic versioning pattern, such as major.minor.patch, but it can also include additional qualifiers like build metadata. In Java, comparing these version strings accurately is essential for proper functionality. This article addresses methods to compare version strings reliably in Java.

String Splitting Technique

The simplest approach to compare two version strings in Java is the string splitting technique. This method involves the following steps:

  1. Split: Break down the version strings using a delimiter (usually a dot ".").
  2. Parse: Convert each segment into integers.
  3. Compare: Compare corresponding segments from major to minor to patch.

Here's a practical implementation:

java
1import java.util.Arrays;
2
3public class VersionComparator {
4
5    public static int compareVersion(String version1, String version2) {
6        String[] levels1 = version1.split("\\.");
7        String[] levels2 = version2.split("\\.");
8        
9        int length = Math.max(levels1.length, levels2.length);
10        for (int i = 0; i < length; i++) {
11            Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;
12            Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;
13            int comparison = v1.compareTo(v2);
14            if (comparison != 0) {
15                return comparison;
16            }
17        }
18        
19        return 0;
20    }
21
22    public static void main(String[] args) {
23        System.out.println(compareVersion("1.2", "1.10")); // Output: -1
24        System.out.println(compareVersion("2.0.1", "2.0")); // Output: 1
25        System.out.println(compareVersion("1.0.0", "1"));   // Output: 0
26    }
27}

Explanation

  • String Split: Using split("\\."), we split the version string wherever a dot occurs.
  • Zero-padding: The shorter version number is conceptually zero-padded to ensure comparison at each digit position.
  • Comparison: Converts each segment to an integer and uses the natural integer comparison to determine which version is newer.

Using Comparable Interface

For a more object-oriented approach, implement a custom version string class that makes use of the Comparable interface:

java
1public class Version implements Comparable<Version> {
2    private final String version;
3
4    public Version(String version) {
5        if (version == null)
6            throw new IllegalArgumentException("Version cannot be null");
7        if (!version.matches("\\d+(\\.\\d+)*"))
8            throw new IllegalArgumentException("Invalid version format");
9        this.version = version;
10    }
11
12    @Override
13    public int compareTo(Version other) {
14        String[] thisParts = this.version.split("\\.");
15        String[] otherParts = other.version.split("\\.");
16        int length = Math.max(thisParts.length, otherParts.length);
17        for (int i = 0; i < length; i++) {
18            int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0;
19            int otherPart = i < otherParts.length ? Integer.parseInt(otherParts[i]) : 0;
20            if (thisPart < otherPart) return -1;
21            if (thisPart > otherPart) return 1;
22        }
23        return 0;
24    }
25
26    @Override
27    public boolean equals(Object o) {
28        if (this == o) return true;
29        if (!(o instanceof Version)) return false;
30        Version version1 = (Version) o;
31        return version.equals(version1.version);
32    }
33
34    @Override
35    public int hashCode() {
36        return version.hashCode();
37    }
38    
39    public static void main(String[] args) {
40        Version v1 = new Version("1.2");
41        Version v2 = new Version("1.10");
42        System.out.println(v1.compareTo(v2)); // Output: -1
43    }
44}

Key Features

  • The Version class encapsulates the version string.
  • Implements Comparable<Version> to allow natural sorting of Version objects.
  • Adheres to the null and format check for robust comparisons.

Handling Pre-releases and Build Metadata

Semantic versioning often includes pre-releases and build metadata, formatted as major.minor.patch-prerelease+buildmetadata. To account for qualifiers, string comparison logic must be enhanced.

Key Considerations

  1. Pre-Releases: Identifiers such as beta, alpha, and RC may sort lexicographically.
  2. Build Metadata: Typically ignored in precedence comparison unless specifically required by the business logic.

Implementation Enhancement

java
1// Pseudo example for enhancements
2public class Version {
3    // existing fields and methods
4
5    private int comparePreRelease(String thisPre, String otherPre) {
6        // Implement lexicographical comparison
7        return thisPre.compareTo(otherPre);
8    }
9    
10    // Update compareTo to handle pre-release identifiers
11}
12

Table Summary

MethodAdvantageLimitation
String Splitting TechniqueSimple and quick to implementIgnores pre-release identifiers
Comparable InterfaceObject-oriented approachRequires additional validity checks
Enhanced ComparisonHandles pre-release identifiersMore complex implementation

Conclusion

Comparing version strings in Java involves understanding both basic numerical comparison and advanced semantic parsing for complex strings. While simple version numbers can be compared via string splitting, comprehensive approaches involve implementing object-oriented designs or using libraries that handle semantic versioning. Always consider edge cases like pre-releases and metadata when designing your comparison logic.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions