DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Java Code to Handle Versions and Their Comparisons [Snippet]

Java Code to Handle Versions and Their Comparisons [Snippet]

Take a look at this quick piece of code to help you manage version strings and their comparisons within your Java projects.

Namit Sharma user avatar by
Namit Sharma
·
Nov. 15, 17 · Code Snippet
Like (6)
Save
Tweet
Share
12.14K Views

Join the DZone community and get the full member experience.

Join For Free

Hello, buddies.

I'm sharing a small but useful piece of code that can help you in handling version strings and comparisons in day-to-day coding.

Often, we struggle while comparing and transcoding versions, which might take some time and can be frustrating as well.

So for your reference and my own, I am keeping this snippet handy.

Check out the full project here, or you may refer to the code shared below.

Happy coding!

package versionCheckDemo;
/**  
 * @author namit  
 * @version 2.0  
 *   
 * re-checking-in for testing develop branch  
 *   
 * */
public class VersionTester {
    public static void main(String[] args) {
        System.out.println("Part 1 - Generalize the version numbers to a standard format - a.b.c");
        String input = "1.1";
        update(input);
        input = "1.1.1";
        update(input);
        input = "1";
        update(input);
        System.out.println("Part 2 - Get the main digit representing the version number ");
        input = "1.0.1";
        findVersion(input);
        input = "54.1";
        findVersion(input);
        input = "100";
        findVersion(input);
        input = "100.c.c";
        findVersion(input);
        input = "100.cc.&@!#$$";
        findVersion(input);
        System.out.println("Part 3 - Comparing the versions, under the format a.b.c ");
        String versionX = "2.3";
        String minVersion = "2.5.5";
        checkVersion(versionX, minVersion);
        versionX = "2.7.9";
        minVersion = "2.5.5";
        checkVersion(versionX, minVersion);
    }
    /**  
     * Method to update the version numbers to a uniform pattern  
     * */
    private static void update(String input) {
        System.out.println("incoming >> " + input);
        int occurence = countMatches(input, '.');
        if (occurence == 0)
            input += ".0.0";
        else if (occurence == 1)
            input += ".0";
        System.out.println("outgoing >> " + input);
        System.out.println("---------------");
    }
    public static int countMatches(final CharSequence str, final char ch) {
        if (null == str) {
            return 0;
        }
        int count = 0;
        char[] arr = ((String) str).toCharArray();
        for (char c: arr) {
            if (c == ch)
                count++;
        }
        // likewise you can go for  
        // org.apache.commons.lang3.StringUtils.StringUtils.countMatches(str, ch)  
        // for saving time of writing the count logic  
        return count;
    }
    /**  
     * Method to find the main version number  
     * */
    private static void findVersion(String input) {
        System.out.println("Incoming >> " + input);
        String inputWithoutDots = input.replace(".", "");
        if (inputWithoutDots.matches("[0-9]+")) {
            int version = 0;
            String[] arr = input.split("\\.");
            version = Integer.valueOf(arr[0]);
            System.out.println("Success! outgoing >> " + version);
        } else {
            System.out.println("error!");
        }
        System.out.println("---------------");
    }
    /**  
     * Method to compare the given version with a minimum accepted version  
     * */
    private static void checkVersion(String versionX, String minVersion) {
        String minVersionFormatted = String.format("%-4s", minVersion.replace(".", "")).replace(' ', '0');
        int minVersionNum = Integer.valueOf(minVersionFormatted);
        String formattedVersion = String.format("%-4s", versionX.replace(".", "")).replace(' ', '0');
        int versionXNum = Integer.parseInt(formattedVersion);
        System.out.println("Min Version - " + minVersion);
        System.out.println("You provided - " + versionX);
        if (versionXNum >= minVersionNum) {
            System.out.println("Version Accepted!");
        } else {
            System.out.println("Version Rejected!");
        }
        System.out.println("---------------");
    }
}


Output:

 Part 1 - Generalize the version numbers to a standard format - a.b.c  
 incoming >> 1.1  
 outgoing >> 1.1.0  
 ---------------  
 incoming >> 1.1.1  
 outgoing >> 1.1.1  
 ---------------  
 incoming >> 1  
 outgoing >> 1.0.0  
 ---------------  
 Part 2 - Get the main digit representing the version number   
 Incoming >> 1.0.1  
 Success! outgoing >> 1  
 ---------------  
 Incoming >> 54.1  
 Success! outgoing >> 54  
 ---------------  
 Incoming >> 100  
 Success! outgoing >> 100  
 ---------------  
 Incoming >> 100.c.c  
 error!  
 ---------------  
 Incoming >> 100.cc.&@!#$$  
 error!  
 ---------------  
 Part 3 - Comparing the versions, under the format a.b.c   
 Min Version - 2.5.5  
 You provided - 2.3  
 Version Rejected!  
 ---------------  
 Min Version - 2.5.5  
 You provided - 2.7.9  
 Version Accepted!  
 ---------------  


Comparison (grammar) Snippet (programming) Java (programming language)

Published at DZone with permission of Namit Sharma, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Load Balancing Pattern
  • Top 5 PHP REST API Frameworks
  • The Importance of Delegation in Management Teams
  • Beginners’ Guide to Run a Linux Server Securely

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: