Integer.Valueof() VS. Integer.Parseint()

Integer.valueOf() vs. Integer.parseInt()

Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:

public static int parseInt(String s) throws NumberFormatException {
return parseInt(s, 10);
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s, radix));
}

public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}

As for parsing with a comma, I'm not familiar with one. I would sanitize them.

int million = Integer.parseInt("1,000,000".replace(",", ""));

Different between parseInt() and valueOf() in java?

Well, the API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int.

If you want to enjoy the potential caching benefits of Integer.valueOf(int), you could also use this eyesore:

Integer k = Integer.valueOf(Integer.parseInt("123"))

Now, if what you want is the object and not the primitive, then using valueOf(String) may be more attractive than making a new object out of parseInt(String) because the former is consistently present across Integer, Long, Double, etc.

What is the difference between int parseInt(String s) and Integer.valueOf(String s)? Also What is radix with a numerical parameter {10 or etc}

The two methods are almost the same in terms of logic.

The difference is that valueOf returns an Integer and parseInt returns an int.

You can see that both call parseInt(s, 10), which means they treat the input String as a number of radix (base) 10 (i.e. a decimal number).

public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}

public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}

Which one is faster? Integer.valueOf(String string) or Integer.parseInt(String string)?

I would not look at performance. The API says that Integer.valueOf(String) is interpreted the same as if it has been passed to Integer.parseInt(String), except it is wrapped into an Integer. I would look at what you need: an Integer or an int.

Integer.valueOf returns an Integer.

Integer.parseInt returns an int.

Difference between Integer.parseInt(“10“); and Integer.valueOf(“10“);

valueOf returns Integer object but parseInt returns int primitive data type

Difference between Integer.parseint vs new Integer

They use the same implementation :

public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}

public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}

The main difference is that parseInt returns a primitive (int) while the Integer constructor returns (not surprisingly) an Integer instance.

If you need an int, use parseInt. If you need an Integer instance, either call parseInt and assign it to an Integer variable (which will auto-box it) or call Integer.valueOf(String), which is better than calling the Integer(String) constructor, since the Integer constructor doesn't take advantage of the IntegerCache (since you always get a new instance when you write new Integer(..)).

I don't see a reason to ever use new Integer("5"). Integer.valueOf("5") is better if you need an Integer instance, since it will return a cached instance for small integers.

Why do == comparisons with Integer.valueOf(String) give different results for 127 and 128?

There's a striking difference here.

valueOf is returning an Integer object, which may have its values cached between -128 and 127. This is why the first value returns true - it's cached - and the second value returns false - 128 isn't a cached value, so you're getting two separate Integer instances.

It is important to note that you are comparing references with Integer#valueOf, and if you are comparing a value that is larger than what the cache supports, it will not evaluate to true, even if the parsed values are equivalent (case in point: Integer.valueOf(128) == Integer.valueOf(128)). You must use equals() instead.

parseInt is returning a primitive int. This is why the third value returns true - 128 == 128 is evaluated, and is of course, true.

Now, a fair bit happens to make that third result true:

  • An unboxing conversion occurs with respect to the equivalence operator you're using and the datatypes you have - namely, int and Integer. You're getting an Integer from valueOf on the right hand side, of course.

  • After the conversion, you're comparing two primitive int values. Comparison happens just as you would expect it to with respect to primitives, so you wind up comparing 128 and 128.

What is performance difference between Integer.valueOf() and Autoboxing

This question is strongly related to this question. As already said in the comments and in the answer to the linked question,

autoboxing invokes the static method Integer.valueOf(), and autounboxing invokes intValue() on the given Integer object. There's nothing else, really - it's just syntactic sugar.

Obviously, the performance is the same. However, things are a bit more complicated as this answer says:

there is no guarantee of how autoboxing is internally implemented.

So, in theory, given some exotic java compiler, the implementation might differ and so might the performance. Practically, there's no reason for implementing autoboxing differently. Moreover, if there was a better implementation, it probably could be incorporated into Integer.valueOf(). So even then, the performance would be the same.


In Java, there's usually nothing to gain from using an alternate implementation doing the same. For example, there used to be performance differences between Arrays.copyOf and System.arraycopy, but AFAIK they were optimized away in the Oracle / OpenJDK JVM.

How do I convert a String to an int in Java?

String myString = "1234";
int foo = Integer.parseInt(myString);

If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which you can handle:

int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
foo = 0;
}

(This treatment defaults a malformed number to 0, but you can do something else if you like.)

Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)

Why does parseInt warn of using valueOf

Can someone explain what exactly the comment warns me about (and the context where valueOf shouldn't be used), and what could possibly go wrong.

The Integer class creates and maintains a cache of Integer objects representing small integer values; by default, values in the range -128 to 127 are covered (more discussion here, here, and many other places). Integer.valueOf() will return an object from this cache when its argument represents a number in the range. The comment is warning that parseInt() must not rely on valueOf() because the former may be invoked before that cache is populated.

The misbehavior that could be expected in that case is not specified, and conceivably might vary between Java versions, but plausible possibilities are that null would be returned or an exception (NullPointerException, IndexOutOfBoundsException, ...) would be thrown.

In any case, this is an internal comment in the implementation, not a comment to users of class Integer. By the time any user code runs, the necessary cache initialization is complete, and Integer.valueOf() can be relied upon to behave fully as its API documentation describes.



Related Topics



Leave a reply



Submit