Double vs double in java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java : different double and Double in comparison
In a sample java program for one of my labs, I have two different methods taking Double and double parameters respectively.
How do I differentiate between them when passing arguments to them?

Double parameter can be null when double can't.

First off you need to understand the difference between the two types.
double is a primitive type whereas Double is an Object.
The code below shows an overloaded method, which I assume is similar to your lab code.
void doStuff(Double d){ System.out.println("Object call"); }
void doStuff(double d){ System.out.println("Primitive call"); }
There are several ways you can call these methods:
doStuff(100);
doStuff(200d);
doStuff(new Double(100));
These calls will result in:
"Primitive call"
"Primitive call"
"Object call"

- double is a primitive type, where as Double is a wrapper object.
- One of the most common use of Wrapper objects is with Collection .
Eg:
List<Double> d = new ArrayList<Double>();
- In Java 5 a mechanism called Autoboxing has been introduced to convert between the two directly.
Eg:
double d = 10.41;
Double wrapper = d;

Double is reference type and double is value type.
The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double." link
As #Fess mentioned and because Double is reference type it can be null.
If you want you can explictly convert from Double to double with .doubleValue() method and viceverrsa with new Double(1.0).
Also as #millimoose said:
You should use X.valueOf() instead of new X(). The valueOf methods are allowed to cache the boxing types to reduce memory use. (Not sure this is done for Doubles but it's a good habit to get into.)"

// Method A
public static void foo(Double d) {...}
// Method B
public static void foo(double d) {...}
Evidently, if you pass a Double object then Method A will be called; i.e. if you had something like:
Double d = new Double(1.0);
Further, if you pass a double literal you will call Method B. What's interesting is if you have something like
double d = new Double(1.0);
In this case Method B will also be called, because the type of d is double; the Double object gets unboxed to a double. On the same note, if you had:
Double d = 1.0;
then Method A would be called, because the type of d would be Double (the double-literal gets autoboxed to a Double).

Double is a wrapper class while double is a primitive type like c/c++. As pointed out above, Double is mostly used in generics but also is useful anywhere there is a need for both numerical value and proper object encapsulation. In most cases the Double and double can be used interchangeably.

What you have is an example of method overloading. The good part is that the compiler and the JVM will select the correct method automatically based on the type of the arguments that is used when you call the method.

Related

How would I use a wrapper class to call methods within a main?

public static void main(String[] args) {
Double ans1 = add(5, 9);
Number ans2 = add(new Integer(3), new Double(2.4));
double ans3 = add(10, 3.2);
System.out.println(answer1 + " " + answer2 + " " + answer3);
}
Given the main method above, how would I create a static method (as opposed a set of overloaded methods) which in turn would could successfully call the methods within the main?
Thanks in advance!
write a single static method (not a set of overloaded methods) which
can be called successfully by all the methods in main.
It is very basic, you can simply do that by creating a new static add() method (a single method contains the code for all calls to different overloaded add methods) as below:
public static void main(String[] args) {
add();
}
public static void add() {
Double ans1 = add(5, 9);
Number ans2 = add(new Integer(3), new Double(2.4));
double ans3 = add(10, 3.2);
System.out.println(answer1 + " " + answer2 + " " + answer3);
}
OK. I think I understand what your teacher wants, despite the wrong terminology he's using. He wants you to write a unique static add() method. And the code should compile and run after this unique add() method is being added to the code.
Since the method is called with arguments that are of type int, Integer, Double and double, the argument types must be a parent class of all these types (after boxing/unboxing). For example Number, or Object.
Since the returned value is assigned to a variable of type Double, Number and double, the return type must be a common class or subclass subclass of all this (after boxing/unboxing).
A candidate would thus be, for example:
private static double add(Object i, Object i1) {
return 0;
}
Of course, the ansX variables need to be renamed to answerX, too, otherwise the code will never compile.
I guess we can also safely assume that add() should add the arguments. I leave that as an exercise for your.
In order for the add method to be called successfully by the main method, you need to figure out what types to use for the return value and the parameters.
Here's a template:
private static ??? add(??? a, ??? b) {
return a + b;
}
As you can see, main calls add with all kinds of arguments, and it stores the result in different types of variables as well.
If you analyze the main method, you will see that the add method must be able to accept the following types of parameters:
(int, int)
(Integer, Double)
(int, double)
It can be deduced that an int, a double, an Integer and a Double can be implicitly converted to the parameters' type. If you do a little bit of thinking, you will know that double is one of the types that satisfy this requirement. This means that the parameters can be of tyoe double!
And it must be able to return a value that's compatible with the following types:
Double
double
Number
It can be deduced that the return type must be able to be implictly converted to Double, double, or Number. double also satisfy this requirement. This means that the method returns a double as well!
Here's the completed method:
private static double add(double a, double b) {
return a + b;
}

The output of the following program is 1,3,3 can someone explain it how?

The output of the following program is 1,3,3 can someone explain it how?
will it consider 10.25 as a object to the method argument?
public class Test {
void methodOfTest(int i) {
System.out.println(1);
}
void methodOfTest(Integer I) {
System.out.println(2);
}
void methodOfTest(Object o) {
System.out.println(3);
}
public static void main(String[] args) {
Test t = new Test();
t.methodOfTest(10);
t.methodOfTest(10.25);
t.methodOfTest(new Double("25.25"));
}
}
t.methodOfTest(10);
10 is interpreted as int literal, so methodOfTest(int i) is called
t.methodOfTest(10.25);
There is no method, that takes a double, so the only method where 10.25 fits in is methodOfTest(Object o)
t.methodOfTest(new Double("25.25"));
Here we have a Double object, but again, no method is found that takes a Double, so the only method that takes this is again methodOfTest(Object o).
Therefore your output is 1,3,3.
It does not consider 10.25 to be an object. It does consider it to be assignment-convertible to an Object reference, by boxing conversion to a Double reference followed by widening reference conversion.
The boxing answers are absolutely correct.
I just wanted to add this: you were perhaps expecting an automatic (implicit) conversion from Double to Integer, but such a conversion must be declared explicitly (casting Double to Integer).
Without an explicit conversion, your Double value is interpreted as an Object (since you provided that method overload), which is the base class of about everything.
Hope this helps ;)
Because 10.25 can be converted to a Double. (boxing into Double)
So the constructor of Double will be called with 10.25 as parameter and will be passed to the method : void methodOfTest(Object o).

Java overload confusion

java is not able to call any overload method as shown below :-
class LspTest{
public void add(int a, float b){
System.out.println("First add");
}
public void add(float a, int b){
System.out.println("second add");
}
public static void main(String [] a){
LspTest test = new LspTest();
test.add(1,1);
}
}
Please explain i am confused in this.
In your methods you are having parameters (int, float) and (float, int) but when calling the method you are passing both the int (1,1) values. The Java complier can auto type cast float to int whenever needed. But in this case compiler cannot decide auto type cast which int to float. Therefore it shows ambiguity.
You need to call it test.add(1f, 1); or test.add(1,1f); i.e. specify which value is int and which value is float.
P.S. To specify a value to be float you can write f with it.
When you initialise with literal values, in this case, compiler won't be able to infer the exact type. Therefore, it does not know which overload to call and returns the error that the reference to add is ambiguous. You can fix this by casting the arguments to the appropriate type, or even better, creating typed local variables initialised with 1 and passing the variables as parameters, like so:
int a = 1;
float b = 1;
LspTest test = new LspTest();
test.add(a,b);
There is an ambiguity here, and the Java compiler cannot figure out which method to call. Use test.add((float) 1, 1) or test.add(1, (float) 1) to explicitly tell which method you want.
This is the clear case of ambiguity which leads to a Compile Error.
Java compiler supports the type promotion. First of all, it'll checks for more specific data type if not match then it'll promote to next data type.
Java compiler will supports the type promotion in following order.
byte --> short --> int --> long --> float --> double
As your parameters (int,int) can be auto-promoted to float, java compiler can't decide in which one to invoke as both of your methods accepts the (1,1)

Overloading methods

I saw below question posted on this site.
"What happens when we pass int arguments to the overloading method having float as a parameter for one method and another having double param".
I thought I understood the concept and wrote this code:
public class TestClass {
public static void main(String args[])
{
TestClass t=new TestClass();
t.sum(1/4);
}
void sum(double d)
{
System.out.println("Double==="+d);
}
void sum(int i)
{
System.out.println("Integer==="+i);
}
void sum(short s)
{
System.out.println("Short==="+d);
}
}
According to my understanding explained on this site (as mentioned above), I thought it will print Short===0, but to my surprise it prints Integer===0. Can any one explain this to me?
First of all, these are overloaded methods, not overridden methods.
1 and 4 are integers. Therefore 1/4 is an integer division, returning 0.
Therefore, the method being called is sum(int i).
sum(short s) would never be called for an int parameter, since that would require a narrowing primitive conversion (JLS 5.1.3), that may cause data loss, and is not allowed in method invocation conversion (JLS 5.3). Such a conversion can be done with an explicit cast.
If you remove the int version, sum(double d) would be called, and if you remove the double version, the code won't compile.
In order to call the short version, you must cast the parameter to short :
t.sum ((short)(1/4));
If you don't explicitly tell the compiler what are the types of 1 and 4, it assumes they are of type int. Then, / operator will apply integer division and will produce another int (which will be 0.)
After that, the method with the most specific to integer parameter type will be invoked. In your case, this will be sum(int i).
If you want to invoke some of the other overloaded methods, you will have to explicitly:
do a cast. For example, sum((short) (1/4)); will invoke sum(short s) due to the cast.
point the type of the operands. For example, sum(1d/4) will invoke sum(double d), since 1d/4 will result to double
For integer number, the type int is a default choice. So, although 1 and 4 can be defined as both int or short, since you did not defined anything, the compiler identified 1 and 4 as int and therefore it entered into the function for 1/4 division (0), which took the parameter int.

Wrapper class as method return type

Can someone please explain how/why is this allowed in Java?
public class Test {
private int text;
public Integer getText() {
return text;
}
I am basically having the wrapper class as the return type, while I am infact returning a primitive.
Because Java supports Autoboxing and Unboxing in versions 5 and up. That is an example of the former, but the later is equally important (and the reverse conversion). Per the link,
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
Consider the following code: (From: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html)
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(i);
Although you add the int values as primitive types, rather than Integer objects, to li, the code compiles. Because li is a list of Integer objects, not a list of int values, you may wonder why the Java compiler does not issue a compile-time error. The compiler does not generate an error because it creates an Integer object from i and adds the object to li. Thus, the compiler converts the previous code to the following at runtime:
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(Integer.valueOf(i));
Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is:
Passed as a parameter to a method that expects an object of the corresponding wrapper class.
Assigned to a variable of the corresponding wrapper class.
From javadocs : Since java 5 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.
The java compiler applies autoboxing usually when -
Passed as a parameter to a method that expects an object of the
corresponding wrapper class.
Assigned to a variable of the corresponding wrapper class.
For the sake of performance, not everything in Java is an object. There are also primitives, such as int, long, float, double, etc.
For example java.lang.Integer class :-
It wraps an int.
Has two static final fields of type int: MIN_VALUE and MAX_VALUE.
MIN_VALUE contains the minimum possible value for an int (-2^31) and MAX_VALUE the maximum possible value for an int (2^31 - 1).
It also has two constructors - public Integer (int value) & public Integer (String value).
Integer has the no-arg byteValue, doubleValue, floatValue, intValue, longValue, and shortValue methods that convert the wrapped value to a byte, double, float, int, long, and short, respectively.
In addition, the toString method converts the value to a String.
Static methods parse a String to an int (parseInt) and convert an int to a String (toString).
class AutoBox {
public static void main(String args[]) {
// autobox an int
Integer a = 100;
// auto-unbox
int b = a;
System.out.println(b + " " + a); // displays 100 100
}
}
This feature has been added in Java 5.
text gets converted automatically into Integer by compiler. So basically its a syntactic sugar that can shorten your code (otherwise you would do conversions back and forth by yourself). Of course it has its price and if this happens a lot (I mean really a lot, big loops, frequent invocations and so forth), it can become a performance issue, so when using it, just remember the it happens under the hood and you'll be fine.
Integer.valueOf(text)
is called under the hood
The feature is called autoboxing btw
Hope this helps

Categories