compare an object whether it contains a string or an int

how to compare characters in a string in java
how to compare two strings in java
how to compare two strings in java using if
string > string java
almost equivalent strings java
java substring comparisons
compare two strings, and print the difference in java
write a program to compare two strings in java

I have two variables that are both of type object. They might contain ints or strings, but always both will be the same type. Is there a way I can compare them to see which is larger (or same).

I know I can test for equality like so:

if (a.Equals(b))

but how do I do the equivalent of:

if (a > b)

if (a < b)

object does not have a compareTo method

Test code:

int i1 = 7;
int i2 = 12;

int result = compareValues((object)i1, (object)i2);

string s1 = "abcd";
string s2 = "efg";

int result = compareValues((object)s1, (object)s2);


public int compareValues((object)a, (object)b)
    if (a.Equals(b))
        return 0;

    if (a < b)
        return -1;

    return 1;


I have no control over the variables - they come as object. The test script is purely for testing.

This is my proposition. You check if the value is comparable (int and string are comparable) if so, convert them to IComparable and use CompareTo

This fiddle works

public static int CompareValue(object a, object b)
    return (a as IComparable).CompareTo(b as IComparable);      

Comparing Strings and Portions of Strings, boolean startsWith(String, int), Returns true if this string ends with or begins with the The Object argument is converted to a string before the comparison takes place. boolean equalsIgnoreCase(String), Returns true if this string contains the  The Object argument is converted to a string before the comparison takes place. The com-pareToIgnoreCase method ignores case; thus, “a” and “A” are considered equal. boolean equals(Object) boolean equalsIgnoreCase(String) Returns true if this string contains the same sequence of characters as the argument. The Object argument is converted to a string before the comparison takes place.

In my opinion, you should check the data type first. You never know if you screwed up somewhere. (And that is exactly the problem with this design, can't you do this more type-safe?)

if (a is int ai && b is int bi)
    // now compare ai en bi
    return ai.CompareTo(bi);
else if (a is string astr && b is string bstr)
    // now compare astr en bstr
    return astr.CompareTo(bstr);
    // a or b is null or have different types.

compareTo() vs. equals(), What is difference between == equals () and compareTo () method? Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. public: int Compare(System::Object ^ x, System::Object ^ y); public int Compare (object x, object y);

The Int32 type has a CompareTo method ... you can either just use that or cast your int to it.

You can find out if you have a string or an int by using the GetType() of object

Right way to Compare String in Java, checks if two objects are the same or not and returns a boolean. compare () is a public member function of string class. It compares the value of the string object (or a substring) to the sequence of characters specified by its arguments. The compare () can process more than one argument for each string so that one can specify a substring by its index and by its length. Return type : compare () returns an

String.equals versus ==, here are many ways to compare String in Java e.g. you can use equals() and whether the value of given String is same i.e. they contain same characters in the It returns a negative integer if this String object lexicographically precedes the  If the IncludeEqual parameter is used, (==) indicates the value is in both objects. If the reference or the difference objects are null ($null), Compare-Object generates a terminating error. For simple objects, like strings or numbers, the cmdlet compares the values of the objects.

How do I compare strings in Java?, It contains well written, well thought and well explained computer science and Double equals operator is used to compare two or more than two objects, If they are referring Below example illustrate the use of == for string comparison in Java: In java Comparable interface compares values and returns an int, these int  When you compare Strings with the == operator, you are comparing their values, not their memory addresses. True When you must determine whether a String is empty, it is more efficient to compare its length to 0 than it is to use the equals () method.

5 ways to Compare String Objects in Java, The String class has a number of methods for comparing strings and portions of Returns an integer indicating whether this string is greater than (result is > 0), boolean equals(Object anObject), Returns true if and only if the argument is a  The contains() method is Java method to check if String contains another substring or not. It returns boolean value so it can use directly inside if statements. Syntax of String "Contain" method public boolean String.contains(CharSequence s)

  • May be if else conditions to check string or int, then compare accordingly.
  • In general, this is bad design -- why are they objects if you know they have a specific type? This is the sort of thing generics generally solve better. One "easy" workaround is to make the variables dynamic, leaving the runtime to sort out how comparisons are supposed to be done, but this has a performance impact. Another possible solution, depending on your scenario, is to get or require IComparer implementations for your objects or treat them as IComparable/IComparable<T>, meaning you don't have to know their type.
  • have you thought about making overloaded methods.. one for int and other for string ? and while calling those methods pass int or string instead of object type?
  • Assign them both to dynamic. Then compare as needed. Assuming they are both int or both string it will 'just work'.
  • "I have two variables that are both of type object" - No, you have two variables that are type int or type string. You're converting them to object (boxing). Don't do that. You already know their types, don't strip away that information. Either create two overloaded methods for comparison, or create a single generic method for comparison, or just compare them where they are (after all, what does this method actually give you that you don't already have?).
  • Returning -2 is not a good idea, since that is a legal "a is smaller than b" value for a CompareTo implementation, which is, at the very least, confusing even if you allow for different semantics. An exception is probably a better idea. (In which case this could also just be reduced to return Comparer.Default.Compare(a, b)).
  • you can shorten this by using the new language feature, there is no need to cast twice.if (a is IComparable first && b is IComparable second)
  • I agree with you. Because I focused on the principle question. The handle of the incorrect case, I let the OP trait it.
  • Anser updated. If it's not correct type, exception thrown automatically
  • I didn't know you could write a is int ai. Is this a new feature? This is really interesting. Also would it be possible to write something similar to if(a is int ai && b is int bi || a is string ai && b is string bi){ return ai.Compareto(bi); }?
  • It is called pattern matching @Rafalon. (And the answer to the second question is no.)
  • What about the strings?