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

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.

Related

Difference between int and Integer

What is the difference between int and Integer. Yes, one is primitive and another one is wrapper, what is the situation to use them correctly.
Also what is the difference between :
int i=0;
++i
and
i++
part 1
One example .. you can use Integer as the key of HashMap but you can't use int. Because an Object is needed.
So where you need an int value as an object there you need to use Integer class.
part 2
++i is pre increment
i++ is post increment
for example
i = 0;
System.out.println(i++) //will print 0 then the i will be 1.
and
i = 0;
System.out.println(++i) // here i wil be incremented first then print 1.
Integer is a wrapper class for int which is a primitive data type. Integer is used when int can't suffice. For example: In generics, the type of the generic class, method or variable cannot accept a primitive data type. In that case Integer comes to rescue.
List<int> list; //Doesn't compiles
List<Integer> list; // Compiles
Moreover Integer comes with a plethora of static methods, like toBinaryString, toHexString, numberOfLeadingZeros, etc. which can come in very handy.
As already explained above
An Integer is an object, whereas an int is a primitive. So you can have a null reference to an Integer and a Set or List of them. You can not do that with an int
I find this null reference very useful, when i have to store int values in database. I can store a null value when I use Integer. But cannot do so when I use int.
An Integer is an object, whereas an int is a primitive. So you can have a null reference to an Integer and a Set or List of them. You can not do that with an int.
A basic explanation is an int is a primitive data type and literally is only a value stored in memory. An Integer is a Java object that wraps an int in a Class with lots of nice/helpful methods that can be called to work with that backing int hidden inside. This is the same with most of the primitive data types, such as boolean and Boolean, char and Character, etc. This is refereed to as Boxing a primitive. Unboxing being the opposite, taking an Object and extracting the backing primative.
Here's an example of how one may use Integer to convert a String into an int (boxed to an Integer)
String someString = "10";
Integer intObj = Integer.parseInt(someString);
System.out.println(intObj.toString());
You'll find that some of the data types have more helpful methods than others. Check the JavaDoc's for each of the types you are interested in, there are a lot of goodies in there!

Purpose of return new?

public Double squareRoot(Double d)
{
return new Double (Math.sqrt(d.doubleValue()));
}
What is the purpose of "return new"? Would it still work if "new" was removed?
Yes, in fact you can remove even more code:
public Double squareRoot(Double d)
{
return Math.sqrt(d);
}
Even though Math.sqrt returns a double and not a Double. This is done by a java feature called Autoboxing.
But as #assylias pointed out, you asked if it is ok to just remove the new keyword. The answer to that is no. This does not compile:
public Double squareRoot(Double d)
{
return Double (Math.sqrt(d.doubleValue()));
}
The error is "Method call expected". You can't call a class' constructor as a method. You can only call a constructor by putting a new keyword in front of it.
You are not using something called 'return new', instead, the following code:
return new Double (Math.sqrt(d.doubleValue()));
actually does
new Double (Math.sqrt(d.doubleValue())) (which creates a new Double object with the value of Math.sqrt(d.doubleValue())
return value of step 1
Java also has a concept called autoboxing which allows for automatic conversion between objects of type Double and values of the type double. As result you don't need to explicitly create an object using new Double(...) because Math.sqrt(...) returns a value of double. Java will do that automagically for you. Same applies to the parameter d: you don't need to call doubleValue() on it.
So you can change the code to:
public Double squareRoot(Double d) {
return Math.sqrt(d);
}
Or better yet use the primitive double as an object of type Double is not really necessary here:
public double squareRoot(double d) {
return Math.sqrt(d);
}
Or better yet (as forivall pointed out in comments to another answer) don't bother with this method and simply call Math.sqrt(...) directly.
This new Double (Math.sqrt(d.doubleValue())); involves converting a primitive type double to its wrapper class Double, and the other way round. But it's unnecessary. Instead, you can do return Math.sqrt(d), which is an example of both autoboxing and unboxing.
"Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing."
http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
Yes, it would still work (provided you also remove the brackets around Math.sqrt(d)) - as long as you're using Java 5 or newer. That feature is called autoboxing / auto-unboxing, meaning the JVM will automatically wrap a primitive in it's corresponding wrapper type.
However, the disadvantage of writing return new Double(Math.sqrt(d)) is that is slightly less efficient. If you use return Double.valueOf(Math.sqrt(d)) (or just return Math.sqrt(d); is that the first option will create a new Double object, whereas the latter two options will try to re-use an earlier created Double instance.
See the Double.valueOf() Javadoc for details.

Java: many ways of casting a (long) Object to double

I have an Object obj that I know is actually a long.
In some Math code I need it as double.
Is it safe to directly cast it to double?
double x = (double)obj;
Or should I rather cast it first to long and then to double.
double x = (double)(long)obj;
I also found another (less readable) alternative:
double x = new Long((long)obj).doubleValue();
What are the dangers/implications of doing either?
Solution Summary:
obj is a Number and not a long.
Java 6 requires explicit casting, e.g.: double x = ((Number)obj).doubleValue()
Java 7 has working cast magic: double x = (long)obj
For more details on the Java6/7 issue also read discussion of TJ's answer.
Edit: I did some quick tests. Both ways of casting (explicit/magic) have the same performance.
As every primitive number in Java gets cast to its boxing type when an object is needed (in our case Long) and every boxed number is an instance of Number the safest way for doing so is:
final Object object = 0xdeadbeefL;
final double d = ((Number)object).doubleValue();
The danger here is, as always, that the Object we want to cast is not of type Number in which case you will get a ClassCastException. You may check the type of the object like
if(object instanceof Number) ...
if you like to prevent class cast exceptions and instead supply a default value like 0.0. Also silently failing methods are not always a good idea.
I have an Object obj that I know is actually a long.
No, you don't. long is a primitive data type, and primitive types in Java are not objects. Note that there's a difference between the primitive type long and java.lang.Long, which is a wrapper class.
You cannot cast a Long (object) to a long (primitive). To get the long value out of a Long, call longValue() on it:
Long obj = ...;
long value = obj.longValue();
Is it safe to directly cast it to double?
If it's actually a primitive long, then yes, you can cast that to a double. If it's a Long object, you don't need to cast, you can just call doubleValue() on it:
double x = obj.doubleValue();
Simple casting should work perfectly fine. This will be faster than going via the wrapper classes, getting string representation and then parsing to double, create new instance again using the long value - and more importantly, it's more readable.
double d = (double)15234451L;
You can cast it to a Long (since the Object is not a long but a Long), and then cast the Long to a double:
double d = (double)(Long)obj;
For instance, this has the expected output of 2.6666666666666665:
public class CastDouble {
public static final void main(String[] args) {
Object o = 15L;
System.out.println(40 / (double)(Long)o);
}
}
You only need one cast, from Object to Long or long (which implicitly casts to Long then applies unboxing):
Object o = 5L;
double d = (long) o; //Apparently only works on Java 7+
//or
double d = (Long) o;

confusion about doublevalue() in hash tables

// Demonstrate a Hashtable
import java.util.*;
class HTDemo {
public static void main(String args[]) {
Hashtable balance = new Hashtable();
Enumeration names;
String str;
double bal;
balance.put("John Doe", new Double(3434.34));
balance.put("Tom Smith", new Double(123.22));
balance.put("Jane Baker", new Double(1378.00));
balance.put("Todd Hall", new Double(99.22));
balance.put("Ralph Smith", new Double(-19.08));
// Show all balances in hash table.
names = balance.keys();
while(names.hasMoreElements()) {
str = (String) names.nextElement();
System.out.println(str + ": " +
balance.get(str));
}
System.out.println();
// Deposit 1,000 into John Doe's account
***bal = ((Double)balance.get("John Doe")).doubleValue();***
balance.put("John Doe", new Double(bal+1000));
System.out.println("John Doe's new balance: " +
balance.get("John Doe"));
}
}
In line bal = ((Double)balance.get("John Doe")).doubleValue(); What is the use of doubleValue? (i know it converts object to double value ) but program runs okay if i run without this.
(correct me if i am wrong) balance.get get here a double object of value 3434.34 and (double ) in front of it does unboxing and converts it into double object in double value then how and why does doubleValue() treats this double 3434.34 as object?????
I am not sure if I got your questions correctly. I will try to explain from the perspective of what I understood your questions to be.
Yes, you are right, you do not need doubleValue(). It is just a way of explicitly telling Java to unbox. If you do not use doubleValue(), Java will unbox it automatically. So, in case if Java had no support for automatically [un]boxing primitive types to the corresponding Object types, then you will need doubleValue() as (Double)balance.get("John Doe") will return an Object while bal is a variable of primitive type.
For the second part of your question, in Java double is a primitive data type and Double is an object type. The Java collections API and hence Hashtable only store objects. They do not store primitive types. Hence, balance.get() returns an object. You cast it into another object of type Double. The doubleValue() method is optional here due to the automatic boxing/unboxing provided by Java.
Hope this helps!
Collections work Only with OBJECT types and not the primitive ones, One of the reasons why the wrapper classes were created, you cannot store 3.4 but u can store new Double(3.4), Yes as you said, you can use the value without its doubleValue but its a standard way of doing things. And for the Implicit calls and conversions, there is a risk of different version of jvms/jre behaving slightly different in such cases, in order to avoid them you would like to do it the standard way , so that it doesnt get impacted
In line bal = ((Double)balance.get("John Doe")).doubleValue(); what is the use of doubleValue (know it converts object to double value )
but program runs okay if i run without this.
Correct.
(correct me if I am wrong) balance.get() gets a double object of value 3434.34 and (double) in front of it does unboxing
No. There is no (double). There is (Double). That typecasts it from Object to Double.
and converts it into double object
Yes.
in double value
No. It is an object not a value. This phrase is meaningless.
then how and why does doubleValue() treats this double 3434.34 as object?
It doesn't. It calls Double.doubleValue() which returns a double.
This code doesn't use autoboxing at all. The doublevalue() calls in this code have been obsolete since Java 1.5 came out about 5 years ago. It also doesn't use Generics. I suspect you are looking at some very old code.

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?
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.

Categories

Resources