Version Comparison in Java:

*@author Amsheer
class Main{
public static void main(String... args){ compare("1.0","1.1"); compare("1.0.1","1.1"); compare("1.9","1.10"); compare("1.a","1.9");
private static void compare(String v1,String v2){
String s1 = normalisedVersion(v1);
String s2 = normalisedVersion(v2);
int cmp = s1.compareTo(s2);
String cmpStr = cmp <0?"<": cmp >0?">":"==";
System.out.printf("'%s' %s '%s'%n", v1, cmpStr, v2);
public static String normalisedVersion(String version){
return normalisedVersion(version,".",4);
public static String normalisedVersion(String version,String sep,int maxWidth){
String[] split =Pattern.compile(sep,Pattern.LITERAL).split(version);
StringBuilder sb =newStringBuilder();
for(String s : split){ sb.append(String.format("%"+ maxWidth +'s', s));}return sb.toString();

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s