Reputation: 851
I have a simple doubt. Would be great if anyone helps me.
I have two strings:
String string1 = "4"; // and
String string2 = "04";
Both the values are equal but how to compare them in java? We have equals
and equalsIgnoreCase
for comparing String alpha values, similarly how to compare numeric values.
Upvotes: 19
Views: 135812
Reputation: 1297
The comparison happens on chacracter basis. so '2' > '12' is true because the comparison will happen as '2' > '1' and in alphabetical way '2' is always greater than '1' as unicode. SO it will comeout true.
Upvotes: 1
Reputation: 4506
Skipping parsing it to an int at all to handle arbitrarily large numbers, only comparing the strings. As a bonus it also works for decimal numbers (unless there are trailing zeroes, where you probably can do similar thing with anchoring end of string instead).
You can omitt the trim if you are sure there are no whitespace characters
String string1 = "4"; // and
String string2 = "04";
String noLeadingZeroes1 = string1.trim().replaceFirst("^0+(?!$)", "");
String noLeadingZeroes2 = string2.trim().replaceFirst("^0+(?!$)", "");
System.out.println(noLeadingZeroes1.equals(noLeadingZeroes2));
Upvotes: 4
Reputation: 22025
Don't forget the BigInteger
for very long values.
return new BigInteger(s1).compareTo(new BigInteger(s2));
Upvotes: 17
Reputation: 5661
Use the Integer class to convert the strings to integers.
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29
Integer.parseInt(string1) == Integer.parseInt(string2)
Upvotes: 3
Reputation: 213401
Integer.parseInt("4") == Integer.parseInt("04")
That is it. You can convert a numeric string into integer using Integer.parseInt(String)
method, which returns an int
type. And then comparison is same as 4 == 4
.
Upvotes: 24