confusion about doublevalue() in hash tables - java

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

Related

Can i sum two String values without using Wrapper Class in java if yes than how ?

String result = "";
try{
int value = Integer.parseInt(a)+Integer.parseInt(b);
result = ""+value;
}catch(NumberFormatException ex){
//either a or b is not a number
result = "Invalid input";
}
MyStringSum.show(null,a+b);
I am using Wrapper Class but i want to sum two String values without using
Wrapper Class , can i do this?
You should not worry about the efficiency of your implementation, because it is not using any wrapper objects.
java.lang.Integer plays several roles:
It holds several important constants, such as MIN_VALUE and MAX_VALUE,
It serves as a helper class for working with primitive ints by providing class methods for parsing and manipulating them, and
Its instances serve as Object wrappers for primitive ints, and providing instance methods for it.
Because you use only parse(...), which is a class method, your code uses the class in its capacity #2, ignoring the #1 and #3. In other words, you are not using Integer in its "wrapper for int" capacity.
Try exp4j. Example(from the link):
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
Another option is Javaluator. See the link for example.
And there's EvalX. See below example(from the link):
Expression expression = new Expression("1+1/3");
result = expression.eval():
expression.setPrecision(2);
result = expression.eval():
I hope this helps!

Why can the immutable class Integer have its value reset?

I was reading earlier that wrapper classes are all immutable. Immutable means that the value cannot be changed. Below I tried this simple example that can just be pasted in to any main method. first I create a Integer that wraps the value five. Immutable means that they cannot be changed so why can I set I to 89. I think that it is because it changes where (I) points to but I am not certain why this is the case.
In my next little example i create an Integer of x which will throw an error if I try and change it. The x seems to be immutable in this specific case but not in the case of the (i) variable.
It seems that I can change the value of (i) whenever I want to so in reality Integer without the final keyword is not immutable???? If i can be set to 89 then to me this seems that the variable can be changed.
I have read other post on this and I still am not certain why i can be changed to another variable. Also in writing code what is the best way to declare primitive types. Why not use the wrapper classes all of the time to create variables.
int y = 5;
Integer i = new Integer(y);
i = 89;
final Integer x = Integer.valueOf(5);
System.out.println("Integer:(i) " + i.intValue());
System.out.println("Integer:(i) " + i.byteValue());
System.out.println("Integer:(x) " + x.intValue());;
System.out.println("Integer:(x) " + x.byteValue());;
i = i - 5;
Using all wrapper classes to declare variables: (Would this be better than declaring these variable with the primitive variable types)
Integer a = new integer(MyNewValue);
Integer b = new integer(MyNewValue);
Integer c = new integer(MyNewValue);
Integer d = new integer(MyNewValue);
Float fa = new integer(MyNewValue);
You are conflating two things: changing the value of an "object" itself and changing the object a reference points to. Saying i = 89 just points the variable i to a new object; it doesn't change the Integer object which originally was pointed to by i.
Pre-pending variable declarations with final just ensures that reassigned is prohibited, it is in no way a declaration of the mutability/immutability of the object it points to. Maybe off-topic, but I personally think the article Java is Pass-by-Value, Dammit! is a good read.
When you call i = 89;, your not changing the value of the Integer object stored in memory. Instead, you're assigning a brand new int with value 89 to i. So the immutable rule isn't being broken.
Remember that i is simply a reference that points to the Integer, not the actual Integer itself.
Yes, it does look like the integer is changing, but all that is happening on line 3 is its being converted to i = new Integer(89) by the compiler. If you wanted to see, you could do
Integer i1 = i;
i = 83;
println(i); \\ prints out the original value 5
println(i1); \\ prints out a new value, 83
When you declare something as final, you cannot change the definition of the variable, though you can still mutate anything inside it. JavaRanch has a very nice analogy to help
You should not use wrapper objects when you can avoid it because they are a small amount less efficient to than primitives and take up a few extra bytes.

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;

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.

Categories

Resources