num == Integer.parseInt(str) is going to faster than str.equals("" + num)

str.equals("" + num) will first convert num to string which is O(n) where n being the number of digits in the number. Then it will do a string concatenation again O(n) and then finally do the string comparison. String comparison in this case will be another O(n) - n being the number of digits in the number. So in all ~3*O(n)

num == Integer.parseInt(str) will convert the string to integer which is O(n) again where n being the number of digits in the number. And then integer comparison is O(1). So just ~1*O(n)

To summarize both are O(n) - but str.equals("" + num) has a higher constant and so is slower.

Answer from dhruv chopra on Stack Overflow
🌐
Coderanch
coderanch.com › t › 441470 › java › Compare-String-Integer
Compare String with Integer (Java in General forum at Coderanch)
lav ish wrote:In my knowledge I know, I can do with Integer.parseInt(mystr) But can anyone tell, can comparision od string with integer be done by any other way. using method below, you can convert any string to number, using the specified pattern. /** * (see java.text.NumberFormat for pattern description) */ public static Number toNumber(String numString, String numFormatPattern) throws ParseException { Number number = null; if (numFormatPattern == null) { numFormatPattern = "######.##"; } synchronized (numberFormat) { numberFormat.applyPattern(numFormatPattern); number = numberFormat.parse(numString); } return number; } private static DecimalFormat numberFormat = new DecimalFormat(); Hope it helps.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 181029 › how-to-compare-a-string-to-an-integer-in-java
how to compare a string to an integer in java
2. Java Strings are 16 bits per character · 3. To compare them or use the String in arithmetic expressions, you first need to convert the string to integer with something like int i = new Integer("12345"); — JamesCherrill 4,733 Jump to Post
🌐
W3Schools
w3schools.com › java › ref_string_compareto.asp
Java String compareTo() Method
Tip: Use the equals() method to compare two strings without consideration of Unicode values. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to ...
🌐
Coderanch
coderanch.com › t › 411964 › java › compare-String-int
How to compare String and int? (Beginning Java forum at Coderanch)
So, how do we use the same variable to compare 2 different things? Keep the input variable a String and parse it into an int.But be advised, since you will be using "quit", the parsing will throw an exception.You need to take care of this. Hope this helps · SCJP, SCWCD.
🌐
Know Program
knowprogram.com › home › how to compare string and integer in java
How To Compare String And Integer In Java - Know Program
November 23, 2022 - In order to compare two different types, we have to convert one of the types to another. For example, here we have to convert string to integer or integer to string and then perform the comparison.
🌐
Sentry
sentry.io › sentry answers › java › how to compare strings in java
How to compare strings in Java | Sentry
If you use == to compare strings, you might get unexpected results. Click to Copy · Click to Copy · public class Main { public static void main(String[] arg) { String str1 = new String("java"); String str2 = new String("java"); System.out...
Find elsewhere
🌐
Oracle
forums.oracle.com › ords › apexds › post › string-vs-integer-comparison-5073
STRING vs INTEGER Comparison! - Oracle Forums
October 31, 2008 - Hello everyone and sorry for the caps...just wanted to emphasize the "vs"!! As with many people this is my first post here and i will immediately cut to the chase! --When comparing integer...
🌐
Stack Overflow
stackoverflow.com › questions › 43269093 › comparing-string-to-int-java
Comparing String to int JAVA - Stack Overflow
NameArray[i].equalsIgnoreCase("")) || Integer.parseInt(NameArray[i]) >= 48 && Integer.parseInt(NameArray[i]) < 58 ... "48".equals(NameArray[i].trim()) or some such, this way you avoid the issues of parsing a String which is not a number ... @Evelyn, as per my understanding you need to check if the string has any numeric value in it. Kindly check my answer and let me know if it helps :) ... In Java 8+, you might use an IntStream to generate a range ([48, 58]) and then check if that as a String is equal to your NameArray.
Top answer
1 of 3
3
/**
 * Similar to compareTo method But compareTo doesn't return correct result for string+integer strings something like `A11` and `A9`
  */

private int newCompareTo(String comp1, String comp2) {
    // If any value has 0 length it means other value is bigger
    if (comp1.length() == 0) {
        if (comp2.length() == 0) {
            return 0;
        }
        return -1;
    } else if (comp2.length() == 0) {
        return 1;
    }
    // Check if first string is digit
    if (TextUtils.isDigitsOnly(comp1)) {
        int val1 = Integer.parseInt(comp1);
        // Check if second string is digit
        if (TextUtils.isDigitsOnly(comp2)) { // If both strings are digits then we only need to use Integer compare method
            int val2 = Integer.parseInt(comp2);
            return Integer.compare(val1, val2);
        } else { // If only first string is digit we only need to use String compareTo method
            return comp1.compareTo(comp2);
        }

    } else { // If both strings are not digits

        int minVal = Math.min(comp1.length(), comp2.length()), sameCount = 0;

        // Loop through two strings and check how many strings are same
        for (int i = 0;i < minVal;i++) {
            char leftVal = comp1.charAt(i), rightVal = comp2.charAt(i);
            if (leftVal == rightVal) {
                sameCount++;
            } else {
                break;
            }
        }
        if (sameCount == 0) {
            // If there's no same letter, then use String compareTo method
            return comp1.compareTo(comp2);
        } else {
            // slice same string from both strings
            String newStr1 = comp1.substring(sameCount), newStr2 = comp2.substring(sameCount);
            if (TextUtils.isDigitsOnly(newStr1) && TextUtils.isDigitsOnly(newStr2)) { // If both sliced strings are digits then use Integer compare method
                return Integer.compare(Integer.parseInt(newStr1), Integer.parseInt(newStr2));
            } else { // If not, use String compareTo method
                return comp1.compareTo(comp2);
            }
        }
    }
}
2 of 3
0
public static String extractNumber(final String str) {                

if(str == null || str.isEmpty()) return "";

StringBuilder sb = new StringBuilder();
boolean found = false;
for(char c : str.toCharArray()){
    if(Character.isDigit(c)){
        sb.append(c);
        found = true;
    } else if(found){
        // If we already found a digit before and this char is not a digit, stop looping
        break;                
    }
}

return sb.toString();
}

For input "123abc", the method above will return 123.

For "abc1000def", 1000.

For "555abc45", 555.

For "abc", will return an empty string.

// Then you can parse that to integer and then compare

Top answer
1 of 16
6152

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they contain the same data).

Objects.equals() checks for null before calling .equals() so you don't have to (available as of JDK7, also available in Guava).

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().

// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" // --> true 

// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true

// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true

From the Java Language Specification JLS 15.21.3. Reference Equality Operators == and !=:

While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters (§3.10.5, §3.10.6). The contents of two strings s and t can be tested for equality by the method invocation s.equals(t).

You almost always want to use Objects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.

From JLS 3.10.5. String Literals:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Similar examples can also be found in JLS 3.10.5-1.

Other Methods To Consider

String.equalsIgnoreCase() value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see this question.

String.contentEquals() compares the content of the String with the content of any CharSequence (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.

2 of 16
796

== tests object references, .equals() tests the string values.

Sometimes it looks as if == compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.

For example:

String fooString1 = new String("foo");
String fooString2 = new String("foo");

// Evaluates to false
fooString1 == fooString2;

// Evaluates to true
fooString1.equals(fooString2);

// Evaluates to true, because Java uses the same object
"bar" == "bar";

But beware of nulls!

== handles null strings fine, but calling .equals() from a null string will cause an exception:

String nullString1 = null;
String nullString2 = null;

// Evaluates to true
System.out.print(nullString1 == nullString2);

// Throws a NullPointerException
System.out.print(nullString1.equals(nullString2));

So if you know that fooString1 may be null, tell the reader that by writing

System.out.print(fooString1 != null && fooString1.equals("bar"));

The following are shorter, but it’s less obvious that it checks for null:

System.out.print("bar".equals(fooString1));  // "bar" is never null
System.out.print(Objects.equals(fooString1, "bar"));  // Java 7 required
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-compareto-method-with-examples
Java String compareTo() Method with Examples - GeeksforGeeks
January 20, 2025 - compareTo() function in Java is used to compare two strings or objects lexicographically. It returns a positive, zero, or negative integer.
Top answer
1 of 6
4

pls try this

 Collections.sort(data, new Comparator<TXCartData>() {
        @Override
        public int compare(TXCartData lhs, TXCartData rhs) {
            int n1=Integer.parseInt(lhs.rowId);
            int n2=Integer.parseInt(rhs.rowId);
            if (n1>=n2){
                return 1;
            }
            return -1;
        }
    });
2 of 6
2

Classes that has a natural sort order (a class Number, as an example) should implement the Comparable interface, whilst classes that has no natural sort order (a class Chair, as an example) should be provided with a Comparator (or an anonymous Comparator class).

public class Number implements Comparable<Number> {
    private int value;

    public Number(int value) { this.value = value; }
    public int compareTo(Number anotherInstance) {
        return this.value - anotherInstance.value;
    }
}

public class Chair {
    private int weight;
    private int height;

    public Chair(int weight, int height) {
        this.weight = weight;
        this.height = height;
    }
    /* Omitting getters and setters */
}
class ChairWeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getWeight() - chair2.getWeight();
    }
}
class ChairHeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getHeight() - chair2.getHeight();
    }
}

Usage:

List<Number> numbers = new ArrayList<Number>();
...
Collections.sort(numbers);

List<Chair> chairs = new ArrayList<Chair>();
// Sort by weight:
Collections.sort(chairs, new ChairWeightComparator());
// Sort by height:
Collections.sort(chairs, new ChairHeightComparator());

// You can also create anonymous comparators;
// Sort by color:
Collections.sort(chairs, new Comparator<Chair>() {
    public int compare(Chair chair1, Chair chair2) {
        ...
    }
});
🌐
Quora
quora.com › Is-it-faster-to-compare-two-integers-or-two-strings
Is it faster to compare two integers or two strings? - Quora
Answer (1 of 10): Generally speaking, it is faster to compare two integers. The ALU (Arithmetic Logic Unit) has comparators that are made to work with bits. Integers are arrays of bits, whereas strings are arrays of characters, and characters arrays of bits. That being said, in C / C++, integers ...
🌐
Oracle
docs.oracle.com › javase › tutorial › java › data › comparestrings.html
Comparing Strings and Portions of Strings (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)
public class RegionMatchesDemo { public static void main(String[] args) { String searchMe = "Green Eggs and Ham"; String findMe = "Eggs"; int searchMeLength = searchMe.length(); int findMeLength = findMe.length(); boolean foundIt = false; for (int i = 0; i <= (searchMeLength - findMeLength); i++) { if (searchMe.regionMatches(i, findMe, 0, findMeLength)) { foundIt = true; System.out.println(searchMe.substring(i, i + findMeLength)); break; } } if (!foundIt) System.out.println("No match found."); } } The output from this program is Eggs. The program steps through the string referred to by searchMe one character at a time.
🌐
Kaan Mutlu's Blog
kaanmutlu.wordpress.com › 2019 › 06 › 25 › compare-two-numeric-string-values
Compare two numeric String values | Kaan Mutlu's Blog
June 25, 2019 - ... As you know, these two strings are not equal so I created a method which converts numeric String values to numeric values and then checks if they are equal. When creating this method I thougt that I can use Integer.parseInt method to convert ...