Difference between parseInt() and valueOf() in Java?
Asked Answered
A

11

529

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?

Avina answered 3/2, 2009 at 19:56 Comment(0)
C
481

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.

Crissie answered 3/2, 2009 at 20:4 Comment(10)
Is there any Performance or Memory difference between the two approaches?Humfried
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.Tableland
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.)Festus
Integer.valueOf(String) does exactly the same caching as Integer.valueOf(int). In fact, it is implemented as Integer.valueOf(Integer.parseInt(…))Scarborough
At least in Java 1.8.0, Integer.valueOf(123) returns the primitive int. Testing showed that between [-127, 128] it returns the primitive not the object, which is exactly a signed byte.Conscionable
@Conscionable 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.Fulmer
Documentation bug. Love it.Lavonlavona
"valueOf(String) returns a new Integer() object" — Not entirely. At least in the Integer class implementation in Java 8, Integers with a value between -128 and 127 are cached. Integer.valueOf("42") == Integer.valueOf("42") returns true.Tonneson
Integer k = Integer.valueOf(Integer.parseInt("123")); is equivalent to Integer k = Integer.parseInt("123"); because autoboxing is done by calling Integer.valueOf anyway. But as noted, Integer.valueOf(String) does use the cache too.Berkey
Perhaps the documentation at the link has changed since you posted this, but the documentation does not say that it creates a new Integer. It says that it creates an Integer "equal to the value of: new Integer(Integer.parseInt(s))" (emphasis added). Whether that is a new instance or an existing instance is left unspecified.Iroquois
P
88

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.

Papist answered 3/2, 2009 at 20:1 Comment(7)
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 trueNickelic
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 objectsNickelic
@bassezero. Also, that pool has a limit. I think it was -127 to 127.Hispania
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.Ivers
@Hispania 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 : #29633658Dyan
No one has mentioned intValue, why does your answer mentions intValue?Roland
@Nickelic This is no longer true. At least since Java 8, the Integer.valueOf(String) simply combines Integer.parseInt(String) and Integer.valueOf(int).Trice
S
48
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.

Scythe answered 3/2, 2009 at 20:1 Comment(4)
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.Invalidity
Which one is used more often? Which one should I use the most?Avina
If you need an int, use parseInt(), if you need an Integer, use valueOf()Shelbyshelden
@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 argumentInconsiderate
S
27

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);
}
Snakebite answered 28/10, 2014 at 8:53 Comment(0)
A
6

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.

Adrianople answered 3/2, 2009 at 20:28 Comment(0)
M
5
  • 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.

Minette answered 15/2, 2019 at 14:9 Comment(1)
Please don't abuse bold formatting: it degrades the readability of your post.Euphroe
N
1

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.

Nickelic answered 3/2, 2009 at 20:2 Comment(2)
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.Arliearliene
You are correct for the String versions, I was thinking of the primitive versions. Long.valueOf(5) will always return the same object.Nickelic
F
0

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);
Ferromagnetic answered 16/12, 2010 at 9:5 Comment(0)
C
0

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

Covalence answered 23/7, 2014 at 17:58 Comment(0)
A
0

public static Integer valueOf(String s)

  1. The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseInt(java.lang.String) method.
  2. The result is an Integer object that represents the integer value specified by the string.

  3. In other words, this method returns an Integer object equal to the value of: new Integer(Integer.parseInt(s))

Assertion answered 29/9, 2015 at 3:31 Comment(0)
T
-2
  1. In case of ValueOf -> it is creating an Integer object. not a primitive type and not a static method.
  2. 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.

Thermit answered 26/8, 2009 at 7:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.