ChatGPT解决这个技术问题 Extra ChatGPT

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

How is parseInt() different from valueOf() ?

They appear to do exactly the same thing to me (also goes for parseFloat(), parseDouble(), parseLong() etc, how are they different from Long.valueOf(string) ?

Also, which one of these is preferable and used more often by convention?


Z
Zach Scrivena

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.


Is there any Performance or Memory difference between the two approaches?
Integer.valueOf(Integer.parseInt("123")) has no benefit over Integer.valueOf("123") or Integer.valueOf(123) aside from wasting cycles and the size of your program.
There is a difference - the new Object (potentially) allocated by valueOf comes with an overhead (memory for the object, handling, GC), while the plain int is extremely "lightweight". (For the most common values, you'll get references to pre-existing Objects, which helps a tiny bit.)
Integer.valueOf(String) does exactly the same caching as Integer.valueOf(int). In fact, it is implemented as Integer.valueOf(Integer.parseInt(…))
@Khez It is impossible for it to return a primitive int. The signature says it returns an Integer, and that is exactly what it does. This answer is also partially incorrect when it says it returns a 'new' Integer. That's not what it says in the Javadoc. It is free to return a cached Integer.
M
Michael Haren

From this forum:

parseInt() returns primitive integer type (int), whereby valueOf returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type. Of course, another obvious difference is that intValue is an instance method whereby parseInt is a static method.


Worth mentioning: valueOf versions will also use an internal reference pool to return the SAME object for a given value, not just another instance with the same internal value. This means that given two Longs returned in this way, a.equals(b) == true and a == b is true
As proven further down, You are correct for the String versions, I was thinking of the primitive versions. Long.valueOf(5) will always return the same object. String versions return new objects, primitive versions return the same objects
@bassezero. Also, that pool has a limit. I think it was -127 to 127.
The size of the reference pool is a true example of an implementation detail; it could even be increased in size in a patch release, and you should never rely on it for anything.
@OscarRyz Actually it's -128 to 127. Note that JVM offer a parameter to set the highest bound higher for the cache. However, you can't re-define the lowest bound : stackoverflow.com/questions/29633158/…
T
Thomas Dickey
Integer.valueOf(s)

is similar to

new Integer(Integer.parseInt(s))

The difference is valueOf() returns an Integer, and parseInt() returns an int (a primitive type). Also note that valueOf() can return a cached Integer instance, which can cause confusing results where the result of == tests seem intermittently correct. Before autoboxing there could be a difference in convenience, after java 1.5 it doesn't really matter.

Moreover, Integer.parseInt(s) can take primitive datatype as well.


valueOf() can return the same object for successive calls with the same argument (and is required to for arguments between -128 and 127 inclusive). new Integer() will always create a new object.
Which one is used more often? Which one should I use the most?
If you need an int, use parseInt(), if you need an Integer, use valueOf()
@Joan d Silva from your last line, I think Integer.parseInt(s) can only take as an String whereas Integer.ValueOf(s) can take both int and string as an input argument
P
Paul Verest

Look at Java sources: valueOf is using parseInt :

/**
 * Parses the specified string as a signed decimal integer value.
 *
 * @param string
 *            the string representation of an integer value.
 * @return an {@code Integer} instance containing the integer value
 *         represented by {@code string}.
 * @throws NumberFormatException
 *             if {@code string} cannot be parsed as an integer value.
 * @see #parseInt(String)
 */
public static Integer valueOf(String string) throws NumberFormatException {
    return valueOf(parseInt(string));
}

parseInt returns int (not Integer)

/**
 * Parses the specified string as a signed decimal integer value. The ASCII
 * character \u002d ('-') is recognized as the minus sign.
 *
 * @param string
 *            the string representation of an integer value.
 * @return the primitive integer value represented by {@code string}.
 * @throws NumberFormatException
 *             if {@code string} cannot be parsed as an integer value.
 */
public static int parseInt(String string) throws NumberFormatException {
    return parseInt(string, 10);
}

i
iny

Integer.parseInt can just return int as native type.

Integer.valueOf may actually need to allocate an Integer object, unless that integer happens to be one of the preallocated ones. This costs more.

If you need just native type, use parseInt. If you need an object, use valueOf.

Also, because of this potential allocation, autoboxing isn't actually good thing in every way. It can slow down things.


A
Andriy

valueOf - converts to Wrapper class

parseInt - converts to primitive type

Integer.parseInt accept only String and return primitive integer type (int).

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

Iteger.valueOf accept int and String. If value is String, valueOf convert it to the the simple int using parseInt and return new Integer if input is less than -128 or greater than 127. If input is in range (-128 - 127) it always return the Integer objects from an internal IntegerCache. Integer class maintains an inner static IntegerCache class which acts as the cache and holds integer objects from -128 to 127 and that’s why when we try to get integer object for 127 (for example) we always get the same object.

Iteger.valueOf(200) will give new Integer from 200. It's like new Integer(200) Iteger.valueOf(127) is the same as Integer = 127;

If you wont to convert String to the Integer use Iteger.valueOf.

If you wont to convert String to the simple int use Integer.parseInt. It works faster.

  public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

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

  private static class IntegerCache {
      static final int low = -128;
      static final int high;
      static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
  }

And comparing Integer.valueOf(127) == Integer.valueOf(127) return true

Integer a = 127; // Compiler converts this line to Integer a = Integer.valueOf(127);
Integer b = 127; // Compiler converts this line to Integer b = Integer.valueOf(127);
a == b; // return true 

Because it takes the Integer objects with the same references from the cache.

But Integer.valueOf(128) == Integer.valueOf(128) is false, because 128 is out of IntegerCache range and it return new Integer, so objects will have different references.


Please don't abuse bold formatting: it degrades the readability of your post.
b
basszero

The parse* variations return primitive types and the valueOf versions return Objects. I believe the valueOf versions will also use an internal reference pool to return the SAME object for a given value, not just another instance with the same internal value.


Actually, not quite true. I thought so myself at first, but the Javadocs for Integer.valueOf(String) clearly state that it is equivalent to new Integer(Integer.parseInt(String)). Integer.valueOf(int) does indeed cache, though.
You are correct for the String versions, I was thinking of the primitive versions. Long.valueOf(5) will always return the same object.
T
TheGraduateGuy

If you check the Integer class you will find that valueof call parseInt method. The big difference is caching when you call valueof API . It cache if the value is between -128 to 127 Please find below the link for more information

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html


m
melpomene

Because you might be using jdk1.5+ and there it is auto converting to int. So in your code its first returning Integer and then auto converted to int.

your code is same as

int abc = new Integer(123);

s
shuaihanhungry

public static Integer valueOf(String s)

The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseInt(java.lang.String) method. The result is an Integer object that represents the integer value specified by the string. In other words, this method returns an Integer object equal to the value of: new Integer(Integer.parseInt(s))


佚名

In case of ValueOf -> it is creating an Integer object. not a primitive type and not a static method. In case of ParseInt.ParseFloat -> it return respective primitive type. and is a static method.

We should use any one depending upon our need. In case of ValueOf as it is instantiating an object. it will consume more resources if we only need value of some text then we should use parseInt,parseFloat etc.