Can anyone tell why the auto boxing is not working, and why with constructor it works fine:
int intValue = 12;
Double FirstDoubleValue = new Double(intValue);
Double SecondDoubleValue = intValue; // ==> Error
Thanks for advance :)
The constructor expects a double, a primitive type, in which case, through widening primitive conversion, an int can be used.
However, in
Double SecondDoubleValue = intValue; // ==> Error
you're trying to assign an int to a Double. Those are incompatible types.
Note that boxing conversion
converts expressions of primitive type to
corresponding expressions of reference type
so an int would become an Integer, but Integer is still not compatible with Double.
Try
Double SecondDoubleValue = (double)intValue;
Java cannot cast int to Double. It can cast int to double, which is what is happening on your second line.
Look here for some in depth answers about conversions.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
Related
I have the following code in Java :
class Boxing
{
public static void main(String args[])
{
short s = 10;
Integer iRef = s;
}
}
Why does it produce an error in compilation? If I explicitly typecast the short to an integer in the expression, it compiles successfully. Since I'm using a short in an expression isn't the type of that supposed to be an integer by default without requiring the explicit case?
You want to have two things happening here: widening and auto-boxing.
Unfortunately, Java does only one of the two automatically. The reason for that is most likely that autoboxing was introduced fairly late (in Java5), and they had to be careful to not break existing code.
You can do
int is = s; // widening
Short sRef = s; // autoboxing
Integer iRef = (int) s; // explicit widening, then autoboxing
Here´s the documentation from JLS 5.1.7
Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:
From type boolean to type Boolean
From type byte to type Byte
From type short to type Short
From type char to type Character
From type int to type Integer
From type long to type Long
From type float to type Float
From type double to type Double
From the null type to the null type
Basicly the direct conversion from short to Integer is not part of the autoboxing process of Java.
The autoboxing, as provided above, is only able to implicity cast the representing primitive type to it´s representing Wrapper class. Since this is not the case it will cause a compile time error.
Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:
From type boolean to type Boolean
From type byte to type Byte
From type short to type Short
From type char to type Character
From type int to type Integer
From type long to type Long
From type float to type Float
From type double to type Double
From the null type to the null type
Reference: Conversions and Promotions Reference
In the code considered.
class Boxing
{
public static void main(String args[])
{
short s = 10;
Integer iRef = s;
}
}
Integer extends java.lang.Number. And java.lang.Short also extends java.lang.Number. But Short and Integer are not directly related if you wanted you can run the following program.
class Boxing
{
public static void main(String args[])
{
short s = 10;
Number iRef = s;
}
}
It will run without producing any error.
Java attempts to perform auto-widening, then auto-boxing, then auto-upcasting, but will not perform two of these for the same assignment. This is explained and diagrammed here, for the related case of method parameter assignment.
I am new to java. I am now learning the non-primitive Integer type in java.
I know the following comparison is not valid and throws a compilation error -
String str = "c";
Char chr = 'c';
if(str == chr) return true;
The above code snippet gives me the - "Test.java:lineNumber: incomparable types: java.lang.String and char" errors.
But I found the following code snippet compiles fine -
int a = 1234;
Integer aI = 1234;
if(a==aI) return true;
Here, a is primitive int and aI is non-primitive. So how they are comparable? I am new to programming, may be is there any thing I don't know.
Thanks
The second snippet demonstrates an unboxing conversion. Boxing conversion allows a primitive type to be converted implicitly to a specific object wrapper type, e.g. int <-> Integer.
When comparing with the == operator, if one operand is a primitive type and the other is such a wrapper type, an unboxing conversion is performed so the 2 primitive values can be compared.
The first snippet doesn't compile because there is no boxing/unboxing relationship between String and char -- the relevant relationship is Character <-> char.
Section 5.1.8 of the JLS specifies all unboxing conversions:
From type Boolean to type boolean
From type Byte to type byte
From type Short to type short
From type Character to type char
From type Integer to type int
From type Long to type long
From type Float to type float
From type Double to type double
Section 5.1.7 specifies all boxing conversions, all of which are the reverse of the above.
This is called unboxing. Here aI is non-primitive/reference type. Here Integer is an wrapper of primitive int. Its gives some extra easy to use manipulations over primitive int. Each primitive type for example (boolean, byte, char, short, int, long, float, double) has a corresponding wrapper type (Boolean, Byte, Character, Short, Integer, Long, Float, Double).
So when a is compared with aI, first aI is unboxed and become a primitive int and it's value is compared with the primitive int. That means it is equivalent to -
int a = 1234;
Integer aI = 1234;
int a2 = aI.intValue();
if(a == a2) return true;
And for the first comparison the comparison occurred between completely two different data types - String and char. In this case there is no rule defined in java to convert char to String or String to char by default.
In first case the two data type are different. So they can not be compared.
And in second case, the two data type also different, but the wrapper Integer is made to support primitive int. So JVM automatically done the conversion of wrapper (unboxing) Integer to int and then compare. So actually in the second case two primitive int are compared to each other at the end.
With Possible Un-boxing in Java Why can't I Downcast With Integer Class.
double a=20.3;
int b=(Integer)a;
It gives me error incompatible Type Conversion. My question is why Integer class is not able to Downcast it like
int b=(int)a;
Does Casting works with class for primitive type in Java?
double can't autobox into Integer. However, int can autobox into Integer. See docs here.
double a=20.3;
Integer b = (int) a;
int c = b; // c = 20;
Why is it possible to pass a primitive to a method that takes an object? Is the primitive turned into an object? like int = Integer and boolean = Boolean?
I can call the following function:
hash(41, 0);
public static int hash(int seed, Object object)
{
int result = seed;
if(object == null)
{
return hash(result, 0);
}
else if(!isArray(object))
{
result = hash(result, object.hashCode());
}
else
{
int length = Array.getLength(object);
for(int index = 0; index < length; ++index)
{
Object item = Array.get(object, index);
// prevent looping if item in array references the array itself
if(!(item == object))
{
result = hash(result, item);
}
}
}
return result;
}
Yes, this is called a boxing conversion. The int value is "boxed" into an Integer, which is an Object. It has been available in Java since 1.5.
The JLS, Section 5.1.7 lists available boxing conversions:
Boxing conversion converts expressions of primitive type to
corresponding expressions of reference type. Specifically, the
following nine conversions are called the boxing conversions:
From type boolean to type Boolean
From type byte to type Byte
From type short to type Short
From type char to type Character
From type int to type Integer
From type long to type Long
From type float to type Float
From type double to type Double
From the null type to the null type
Additionally, the boxing conversion is allowed during method invocation conversion, which is really what's going on here. The value is being converted to another type because the int 0 is being passed to a method that expects an Object. The JLS, Section 5.3, lists boxing conversion as one method of method invocation conversion:
Method invocation contexts allow the use of one of the following:
an identity conversion (§5.1.1)
a widening primitive conversion (§5.1.2)
a widening reference conversion (§5.1.5)
a boxing conversion (§5.1.7) optionally followed by widening reference
conversion
an unboxing conversion (§5.1.8) optionally followed by a widening
primitive conversion.
Yes you can. Something called autoboxing/unboxing is done by the compiler automatically. Here is an excerpt from the docs.
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.
int i = 1;
Integer boxI = i; // Autoboxing is performed automatically by the compiler
Integer ii = 1;
int i = ii; // Auto(un)boxing is performed automatically by the compiler
Yes, primitive is converted to Object and vice versa, and this concept is called boxing and unboxing. In newer versions of java this is done automatically, hence called, auto-boxing and auto-unboxing.
Oracle doc for Boxing and UnBoxing
Each primitive has corresponding Wrapper class.
int -> Integer
boolean -> Boolean
char -> Character
and so on.
Look at this... this evening I was trying to cast some primiteves to wrappers when I found that:
Integer i = (Integer)4;
Integer i = (Integer)4f; // Doesn't compile!
But if I rewrite the second line:
Integer i2 = (int)4f; // Then it compiles
What's the difference? Why should I be able to cast with a wrapper class in the first case, but not in the second?
here
Integer i = (Integer)4f;
youre casting a float primitive to an Integer wrapper - they dont fit. this has nothing to do with autoboxing either. even with explicit boxing, this still wont compile:
Integer i = (Integer)(Double.valueOf(4f));
while here:
Integer i2 = (int)4f;
you casting a float primitive to an int primitive (truncating in the process) and then java auto-boxes that into an Integer for you