Different between parseInt() and valueOf() in java? - 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?

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.

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.

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.

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);
}

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.

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.

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.

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

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);

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.

Related

What is the difference between (Integer)y and new Integer(y) in java?

What is the difference between the following:
Integer in = (Integer)y;
and
Integer in = new Integer(y);
I want to convert int type to Integer type and vice versa. Here is my code for doing that:
public class CompareToDemo {
public static void main(String[] args) {
// Integer x=5;
int y=25;
System.out.println(y+" this is int variable");
Integer in = (Integer)y;
//Integer in = new Integer(y);
if(in instanceof Integer){
System.out.println(in +" this is Integer variable");
}
}
}
If all you want to do is to convert an int primitive to an Integer object,
you have four options
Integer in = (Integer)y; // 1 explicit cast
Integer in = y; // 2 implicit cast (autoboxing)
Integer in = new Integer(y); // 3 explicit constructor
Integer in = Integer.valueOf(y); // 4 static factory method
The most preferable way here is 2 (autoboxing). The explicit constructor (3) is the less preferable, as it might have some small performance hit.
Also, they are not strictly equivalent. Consider:
public static void main(String[] args) {
int x = 25;
Integer a = new Integer(x);
Integer b = new Integer(x);
System.out.println(a == b); // false
Integer c = Integer.valueOf(x);
Integer d = Integer.valueOf(x);
System.out.println(c == d); // true
Integer e = (Integer)x;
Integer f = (Integer)x;
System.out.println(e == f); // true
}
This is because small integers are cached (details here).
Briefly speaking,
The line Integer in = (Integer)y; uses an unnecessary cast.
The line Integer in = new Integer(y); creates an Integer instance.
Each case in detail
First, let's consider the case with explicit casting.
Integer i = (Integer)10;
The compiler understands that 10 is an int primitive type and the fact that it has to be wrapped by its Integer to make it compiles. It seems javac will make the following:
Integer i = (Integer)Integer.valueOf(10);
But the compiler is smart enough to do unnecessary casting, (Integer) just will be omitted:
Integer i = Integer.valueOf(10);
Next, there is the case with instance creation.
Integer i = new Integer(10);
Here is all simply. A new instance of Integer class will be created anyway. But, as the documentation says, usually, it is not appropriate way:
It is rarely appropriate to use these constructors. The static factories valueOf() are generally a better choice, as it is likely to yield significantly better space and time performance.
Conclusion
In everyday code writing, we usually use autoboxing and unboxing. They are automatic conversions between the primitive types and their corresponding object wrapper classes (has been introduced in Java 5). So you needn't think much about Xxx.valueOf(xxx) and .xxxValue() methods. It is so convenient, isn't it?
Integer i = 10; // autoboxing
int j = i; // unboxing
For every primitive type in java, there is a corresponding wrapper class. You can convert between these primitive type and corresponding wrapper class. This is called boxing and unboxing. When you write
Integer in = (Integer)y; //this is unnecessary casting
or
Integer in = new Integer(y); //create a new instance of Integer class
You're mainly converting between primitive type and wrapper class. But Java has a feature called Auto Boxing and Unboxing Where java will do these casting for you. Just write
int iPrimi = 20;
Integer iWrapper = iPrimi; //Autoboxing
int iPrimi2 = iWrapper; //Auto unboxing
Autoboxing and Unboxing decrease performance. Primitives seems to be 2-3 times faster then it’s Integer equivalent. So do not use them if you don't need to.

What will be the output of the below program? and HOW? [duplicate]

This question already has answers here:
Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java?
(8 answers)
Closed 7 years ago.
public class MainClass
{
public static void main(String[] args)
{
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2);
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i3 == i4);
}
}
i1,i2,i3,i4 are not objects I guess they are only reference variables. So how they work differently from class variables?
Answer I heard is
true
false
But how? Why is it different for 127 and 128?
Since Java 5, wrapper class caching was introduced. The following is an examination of the cache created by an inner class, IntegerCache, located in the Integer cache. For example, the following code will create a cache:
Integer myNumber = 10
or
Integer myNumber = Integer.valueOf(10);
256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array. This caching functionality can be seen by looking at the inner class, IntegerCache, which is found in Integer:
So when creating an object using Integer.valueOf or directly assigning a value to an Integer within the range of -128 to 127 the same object will be returned. Therefore, consider the following example:
Integer i = 100;
Integer p = 100;
if (i == p)
System.out.println("i and p are the same.");
if (i != p)
System.out.println("i and p are different.");
if(i.equals(p))
System.out.println("i and p contain the same value.");
The output is:
i and p are the same.
i and p contain the same value.
It is important to note that object i and p only equate to true because they are the same object, the comparison is not based on the value, it is based on object equality. If Integer i and p are outside the range of -128 or 127 the cache is not used, therefore new objects are created. When doing a comparison for value always use the “.equals” method. It is also important to note that instantiating an Integer does not create this caching.
Remember that “==” is always used for object equality, it has not been overloaded for comparing unboxed values
Also see Integer wrapper objects share the same instances only within the value 127?
Integer is an object and hence the == check if the variables refer to the exact same instance. Equality of objects can be checked using the myObject.equals(otherObject)
int is the primitive type of Integer and in that case the == would return true if both the ints have the same value
update: please note that in some case, as for String for example, two variables can share the same reference depending from the code and the compiler but still it is not something you should base your code logic on.

What is .intValue() in Java?

What is the difference between them?
l is an arraylist of Integer type.
version 1:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i);
}
return a;
version 2:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i).intValue();
}
return a;
l.get(i); will return Integer and then calling intValue(); on it will return the integer as type int.
Converting an int to Integer is called boxing.
Converting an Integer to int is called unboxing
And so on for conversion between other primitive types and their corresponding Wrapper classes.
Since java 5, it will automatically do the required conversions for you(autoboxing), so there is no difference in your examples if you are working with Java 5 or later. The only thing you have to look after is if an Integer is null, and you directly assign it to int then it will throw NullPointerException.
Prior to java 5, the programmer himself had to do boxing/unboxing.
As you noticed, intValue is not of much use when you already know you have an Integer. However, this method is not declared in Integer, but in the general Number class. In a situation where all you know is that you have some Number, you'll realize the utility of that method.
The Object returned by l.get(i) is an instance of the Integer class.
intValue() is a instance method of the Integer class that returns a primitive int.
See Java reference doc...
http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#intValue()
Java support two types of structures first are primitives, second are Objects.
Method that you are asking, is used to retrieve value from Object to primitive.
All java types that represent number extend class Number. This methods are in someway deprecated if you use same primitive and object type since [autoboxing] was implemented in Java 1.5.
int - primitive
Integer - object
Before Java 1.5 we was force to write
int i = integer.intValue();
since Java 1.5 we can write
int i = integer;
Those methods are also used when we need to change our type from Integer to long
long l = integer.longValue();
Consider this example:
Integer i = new Integer(10);
Integer j = new Integer(10);
if (!(i == j)) {
System.out.println("Surprise, doesn't match!");
}
if (i.intValue() == j.intValue()) {
System.out.println("Cool, matches now!");
}
which prints
Surprise, doesn't match!
Cool, matches now!
That proves that intValue() is of great relevance. More so because Java does not allow to store primitive types directly into the containers, and very often we need to compare the values stored in them. For example:
oneStack.peek() == anotherStack.peek()
doesn't work the way we usually expects it to work, while the below statement does the job, much like a workaround:
oneStack.peek().intValue() == anotherStack.peek().intValue()
get(i) will return Integer object and will get its value when you call intValue().In first case, automatically auto-unboxing happens.
They are exactly the same. As other posters have mentioned, you can put either the Integer object or the int primitive into the array. In the first case, the compiler will automatically convert the Integer object into a primitive. This is called auto-boxing.
It's just a convenience method for getting primitive value from object of Number: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Number.html
Consider the code:
Integer integerValue = Integer.valueOf(123);
float floatValue = integerValue.floatValue();
The last line is a convenient method to do:
float floatValue = (float)(int)integerValue;
Since any numeric type in Java can be explicitly cast to any other primitive numeric type, Number class implements all these conversions. As usual, some of them don't make much sense:
Integer integerValue = Integer.valueOf(123);
int intValue = integerValue.intValue();
int intValue2 = (int)integerValue;
int intValue3 = integerValue;

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

I want to convert String to a Double data type. I do not know if I should use parseDouble or valueOf.
What is the difference between these two methods?
parseDouble returns a primitive double containing the value of the string:
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
valueOf returns a Double instance, if already cached, you'll get the same cached instance.
Returns a Double instance representing the specified double value. If
a new Double instance is not required, this method should generally be
used in preference to the constructor Double(double), as this method
is likely to yield significantly better space and time performance by
caching frequently requested values.
To avoid the overhead of creating a new Double object instance, you should normally use valueOf
Double.parseDouble(String) will return a primitive double type.
Double.valueOf(String) will return a wrapper object of type Double.
So, for e.g.:
double d = Double.parseDouble("1");
Double d = Double.valueOf("1");
Moreover, valueOf(...) is an overloaded method. It has two variants:
Double valueOf(String s)
Double valueOf(double d)
Whereas parseDouble is a single method with the following signature:
double parseDouble(String s)
parseDouble() method is used to initialise a STRING (which should contains some numerical value)....the value it returns is of primitive data type, like int, float, etc.
But valueOf() creates an object of Wrapper class. You have to unwrap it in order to get the double value. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.
Observe the following conversion.
int k = 100;
Integer it1 = new Integer(k);
The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.
The following code can be used to unwrap (getting back int from Integer object) the object it1.
int m = it1.intValue();
System.out.println(m*m); // prints 10000
//intValue() is a method of Integer class that returns an int data type.
They both convert a String to a double value but wherease the parseDouble() method returns the primitive double value, the valueOf() method further converts the primitive double to a Double wrapper class object which contains the primitive double value.
The conversion from String to primitive double may throw NFE(NumberFormatException) if the value in String is not convertible into a primitive double.
Documentation for parseDouble() says "Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.", so they should be identical.
If you want to convert string to double data type then most choose parseDouble() method.
See the example code:
String str = "123.67";
double d = parseDouble(str);
You will get the value in double. See the StringToDouble tutorial at tutorialData.

Integer.toString(int i) vs String.valueOf(int i) in Java

I am wondering why the method String.valueOf(int i) exists ? I am using this method to convert int into String and just discovered the Integer.toString(int i) method.
After looking the implementation of these methods I saw that the first one is calling the second one. As a consequence all my calls to String.valueOf(int i) involve one more call than directly calling Integer.toString(int i)
In String type we have several method valueOf
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
As we can see those method are capable to resolve all kind of numbers
every implementation of specific method like you have presented: So for integers we have
Integer.toString(int i)
for double
Double.toString(double d)
and so on
In my opinion this is not some historical thing, but it is more useful for a developer to use the method valueOf from the String class than from the proper type, as it leads to fewer changes for us to make when we want to change the type that we are operating on.
Sample 1:
public String doStuff(int num) {
// Do something with num...
return String.valueOf(num);
}
Sample2:
public String doStuff(int num) {
// Do something with num...
return Integer.toString(num);
}
As we see in sample 2 we have to do two changes, in contrary to sample one.
In my conclusion, using the valueOf method from String class is more flexible and that's why it is available there.
One huge difference is that if you invoke toString() in a null object you'll get a NullPointerException whereas, using String.valueOf() you may not check for null.
Just two different ways of doing the same thing. It may be a historical reason (can't remember if one came before the other).
The String class provides valueOf methods for all primitive types and Object type so I assume they are convenience methods that can all be accessed through the one class.
NB Profiling results
Average intToString = 5368ms, Average stringValueOf = 5689ms (for 100,000,000 operations)
public class StringIntTest {
public static long intToString () {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
String j = Integer.toString(i);
}
long finishTime = System.currentTimeMillis();
return finishTime - startTime;
}
public static long stringValueOf () {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
String j = String.valueOf(i);
}
long finishTime = System.currentTimeMillis();
return finishTime - startTime;
}
public static void main(String[] args) {
long intToStringElapsed = 0;
long stringValueOfElapsed = 0;
for (int i = 0; i < 10; i++) {
intToStringElapsed += intToString();
stringValueOfElapsed+= stringValueOf();
}
System.out.println("Average intToString = "+ (intToStringElapsed /10));
System.out.println("Average stringValueOf = " +(stringValueOfElapsed / 10));
}
}
From the Java sources:
/**
* Returns the string representation of the {#code int} argument.
* <p>
* The representation is exactly the one returned by the
* {#code Integer.toString} method of one argument.
*
* #param i an {#code int}.
* #return a string representation of the {#code int} argument.
* #see java.lang.Integer#toString(int, int)
*/
public static String valueOf(int i) {
return Integer.toString(i);
}
So they give exactly the same result and one in fact calls the other. String.valueOf is more flexible if you might change the type later.
If you look at the source code for the String class, it actually calls Integer.toString() when you call valueOf().
That being said, Integer.toString() might be a tad faster if the method calls aren't optimized at compile time (which they probably are).
The implementation of String.valueOf() that you see is the simplest way to meet the contract specified in the API: "The representation is exactly the one returned by the Integer.toString() method of one argument."
To answer the OPs question, it's simply a helper wrapper to have the other call, and comes down to style choice and that is it. I think there's a lot of misinformation here and the best thing a Java developer can do is look at the implementation for each method, it's one or two clicks away in any IDE. You will clearly see that String.valueOf(int) is simply calling Integer.toString(int) for you.
Therefore, there is absolutely zero difference, in that they both create a char buffer, walk through the digits in the number, then copy that into a new String and return it (therefore each are creating one String object). Only difference is one extra call, which the compiler eliminates to a single call anyway.
So it matters not which you call, other than maybe code-consistency. As to the comments about nulls, it takes a primitive, therefore it can not be null! You will get a compile-time error if you don't initialize the int being passed. So there is no difference in how it handles nulls as they're non-existent in this case.
You shouldn't worry about this extra call costing you efficiency problems. If there's any cost, it'll be minimal, and should be negligible in the bigger picture of things.
Perhaps the reason why both exist is to offer readability. In the context of many types being converted to String, then various calls to String.valueOf(SomeType) may be more readable than various SomeType.toString calls.
my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.
There have no differences between Integer.toString(5) and String.valueOf(5);
because String.valueOf returns:
public static String valueOf(int i) {
return Integer.toString(i);
}
public static String valueOf(float f) {
return Float.toString(f);
}
etc..
Using the method, String.valueOf() you do not have to worry about the data(whether it is int,long,char,char[],boolean,Object), you can just call :
static String valueOf()
using the only syntax String.valueOf() can whatever you pass as a parameter is converted to String and returned..
Otherwise, if you use Integer.toString(),Float.toString() etc.(i.e. SomeType.toString()) then you will have to check the datatype of parameter that you want to convert into string.
So, its better to use String.valueOf() for such convertions.
If you are having an array of object class that contains different values like Integer,Char,Float etc. then by using String.valueOf() method you can convert the elements of such array into String form easily. On contrary, if you want to use SomeType.toString() then at first you will need to know about there their datatype classes(maybe by using "instanceOf" operator) and then only you can proceed for a typecast.
String.valueOf() method when called matches the parameter that is passed(whether its Integer,Char,Float etc.) and by using method overloading calls that "valueOf()" method whose parameter gets matched, and then inside that method their is a direct call to corresponding "toString()" method..
So, we can see how the overhead of checking datatype and then calling corresponding "toString()" method is removed.Only we need is to call String.valueOf() method, not caring about what we want to convert to String.
Conclusion: String.valueOf() method has its importance just at cost of one more call.

Categories

Resources