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.
Related
public static void main(String []args){
Integer a = new Integer(9);
d(a);
System.out.print(a) ;
}
public static void d(int z){
z=z+2;
}
or suppose I write
public static void main(String []args){
int a = 9;
d(a);
System.out.print(a) ;
}
public static void d(int z){
z=z+2;
}
but the output is the same for both: 9. Can anyone explain me in detail why?
Because JAVA is PASS BY VALUE not PASS BY REFERENCE.
Let us understand it this way,
Your main function has a local variable z whose scope is limited to main only
and your d function has another local variable z whose scope is limited to d only
So, in your d fucntion, you are basically creating a new integer literal 11 and putting it to local variable z whose scope is limited to d function only and not the variable z of main.
In your code with Integer a process called unboxing occurs. The Integer-instance is unboxed to a primitive int when calling your method d. See this to better understand how autoboxing and unboxing works.
As for your z=z+2 inside the method d. Java objects are passed-by-reference, but Java primitives or Immutable objects (like Strings) are passed-by-value. Since your method d has a primitive parameter int it's passed-by-value in this case. Your z=z+2 isn't returned however.
If you would add System.out.println(z); right after z=z+2 it will indeed print 11. So why isn't the a in your main-method changed to 11 and how can you accomplish this? As I mentioned, it's passed-by-value for primitives. You'll need to return the new value and set the a in the main method with it. If you change your code to this it will work:
public static void main(String []args){
int a = 9;
a = d(a);
System.out.print(a);
}
public static int d(int z){
return z+2;
}
Try it online.
As you can see, the void d is changed to int d, and we return the result of z+2. We then overwrite the value of a with this new result with a = d(a); in the main-method.
Java has a concept of AutoBoxing and Auto unboxing for primitive datatypes.
Since primitves like int, float double, long etc are technically not objects, they have their corresponding Classes which can be instantiated with the primitive value to treat them as objects.
So to reduce the pain, java automatically converts int to Integer and Integer to int where ever applicable.
If you are wondering why the addition value has not reflected, though it is an Integer object on performing addition, a new int object will be resulted. so it wont reflect directly. You can return the value from the method you call and assign to it.
Java passes variables by value, not by reference. If you think that passing an object and changing the value of its data member would work, it won't. In that case, too, a copy of that object will be passed, not the original object. The only solution is to declare the variable as static that can be changed from anywhere.
it's all because of Autoboxing and Unboxing feature of java which provide the functionality of converting primitive to object(Wrapper) type and vice-versa. for better understanding you can check here
. I hope it will clear all your doubts.
Which of the following ways is better to convert Integer, Double to String in Java.
String.valueOf(doubleVal)
doubleVal + ""
doubleVal.toString()
Thanks.
doubleVal + "" is most likely the worst since it has to do a concatanation with an empty string. However, the other two are equivalent. The source code from OpenJDK:
// java.lang.String
public static String valueOf(double d) {
return Double.toString(d);
}
// java.lang.Double
public static String toString(double d) {
return new FloatingDecimal(d).toJavaFormatString();
}
I don't think there's a performance difference. Go for the most readable!
The first one is exactly equivalent to doublevar.toString() (check the javadoc). The second one is more suited for concatenating longer strings.
If you need to format the way your number is represented as a String, you anyway need to look into other classes
The first and the third are good, the second is bad.
The reason that the second is bad is because the code doesn't show what you want to do. The code says that you want to concatentate the value with an empty string, when you actually want only the conversion that happens before the concatenation.
I prefer to use Integer.toString(int), when you use String.valueOf(int), it internally calls to Integer.toString(int) (same with long, float and double). But for readability, it would be better to use String.valueOf()
There are slight semantic differences depending on whether you're using the primitive double type, or its object wrapper Double.
Anything that will work for a primitive double will also work for the object wrapped Double, but the opposite will not work. (That is, a primitive double will not be accepted if the parameter is of type Double.)
Also, the Double type's value may be null, but the primitive double type cannot.
Beyond that, there isn't much difference at all. For the code snippets you've provided, there isn't any worth really talking about.
i) String.valueOf(int i)
ii) Integer.toString(int i)
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)
Just two different ways of doing the same thing
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 double
Double.toString(dobule d)
and so on
In my opinion this is not some historical thing, but is more useful for developer to use the method valueOf from String class than from proper type, because is less changes to make when we want to change the type that we operate on.
Sample 1:
public String doStaff(int num) {
//Do something with num
return String.valueOf(num);
}
Sample2:
public String doStaff(int num) {
//Do somenthing with num
return Integer.toString(num);
}
As we see in sample 2 we have to do two changes, in contrary to sample one.
My conclusion is that using the valueOf method from String class is more flexible and that why is available there.
From the official source:
public static String valueOf(double d) {
return Double.toString(d);
}
So the first and the third are not really different, as long as doubleVal is double and not Double. This is because in the case of a Double, you will call
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
The second is certainly worse because of the need to concatenate.
CONCLUSION:
Following the question, I must assume that the most efficient way is to call the toString() method.
Java string.valueOf() method converts different types of value such as long,int,double,float into String.
Double double_val=45.9;
String string_conversion=String.valueOf(double_val);
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.
// 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.
I have a long piece of code that calculates two values (doubles) for me, I use this piece of code in a few places - to stick with DRY principles I should refactor this bit of code to a nice unit testable method. However I cant make it return two doubles, and doubles are primitive so cannot be passed by value and manipulated. The cleanest way I can think of doing this is by making this method return an double[]. Can anyone think of a better way?
Thanks
Firstly, all variables are passed by value in Java, not just primitives. It's just that objects can be mutable. It's important to understand that. For example:
public void addHour(Date date) {
date.setTime(date.getTime() + 3600 * 1000);
}
The date is passed by value but Date is mutable so it can be modified but try and do this:
public void addHour(Date date) {
date = new Date(date.getTime() + 3600 * 1000);
}
and it won't change the date. Why? Because date is a reference but is passed by value.
Secondly, do these doubles relate to each other in some way? If so wrap them in a class than describes this relationship like:
public class Coordinate {
private final double x;
private final double y;
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() { return x; }
public double getY() { return y; }
}
You could encapsulate them in a class for this purpose.
You could also give a double[] parameter to the method that calculates them and where it will put the calculated values in. This can be rather efficent as the caller code can reuse this array for successive invocations if performance is important.
A class (immutable) with two double fields? Might even want to add some interesting methods to the class.
The other way around is to have the method take a callback object.
double[] arr = {val1, val2};
return arr
or go with a Pair-like class that encapsulates 2 values...
If the two doubles can be thought of as a logical pairing of values, then it might make sense to bundle them in a simple object?
I'm more of a C++ guy, but creating an object of your own called Pair which can hold 2 doubles and can be passed by reference makes sense to me.
Create an new class that has two double properties with getters and setters and constructor if you like (and equals and hashcode...) and make the method return that type of object. A generic way to do that would be a Pair class. This is a common pattern and you should find code snippets everywhere (e.g. in the netbeans code base).
You have several options:
Return an array
Return a List<double>
Return an object of a class that wraps your two doubles
And by the way, Java does not pass objects by reference. It passes pointers to objects by value.
http://javadude.com/articles/passbyvalue.htm
A double array is the most obvious answer. You can make it a bit safer by having a wrapper object like this:
public class MyTwoDoubles {
public MyTwoDoubles(double one, double two) { ... }
public double getOne() { ... }
public double getTwo() { ... }
}
You can rather use Wrapper classes which are of reference types
For every value type you can find a wrapper class.
for your case java.lang.Double can be used,hope this solves the purpose
But still as a good design i suggest you not to alter the object value inside the method.
Instead refactor the code in such a way you call it twice and return two different values then assign it to the original.
As a good practice its not advisible to alter object value inside a method