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
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.
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;
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
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
I come from Python background and taking a dive into Java world.
I am trying to convert Float to int in Java. Something we do like this in Python int_var = int(float_var)
public class p1 {
public static void main(String args[]) {
Integer a = new Integer(5);
Float b;
b = new Float(3.14);
a = (int)b;
System.out.println(a);
}
}
Yields the following error -
p1.java:7: error: inconvertible types
a = (int)b;
^
required: int
found: Float
1 error
You can do it like
a = b.intValue()
That's one of the annoying things in Java. Fix your problem with this:
a = (int)(float)b;
Unboxing will require that you cast from Float to float and then to int
Use primitives types, and you will be fine:
int a = 5;
float b = 3.14f; // 3.14 is by default double. 3.14f is float.
a = (int)b;
The reason it didn't work with Wrappers is those types are non-covariant, and thus are incompatible.
And if you are using Integer types (Which you really don't need here), then you should not create Wrapper type objects using new. Just make use of auto-boxing feature:
Integer a = 5; // instead of `new Integer(5);`
the above assignment works after Java 1.5, performing auto-boxing from int primitive to Integer wrapper. It also enables JVM to use cached Integer literals if available, thus preventing creation of unnecessary objects.
Since you're using boxed primitive, a = b.intValue(); should suit your needs.
float a =10.0f;
int k=(int)a;
Use this code
a = b.intValue();
Use Math.round method:-
int a = Math.round(b);
for the best always use:
Math.floor(d)
Math.round(d)
Math.abs(d)
These are meant for conversions.
You can simply use the Use Math.round() as,
int a = Math.round(14.32f)