1

This may be the simple answer but I want to know the detail.

// Narrowing Conversion float ff = Integer.MAX_VALUE; int ii = (int)ff; System.out.println("float: " + ff + " int: " + ii); // Reference Conversion Integer integer; Float floatt = 100F; integer = (Integer) floatt; 

In the above example the narrowing conversion works properly but the same with reference conversion is not working. Detail explanation is highly appreciable.

4
  • 2
    It is not possible because Integer does not inherit from Float. Autocasting on object does only work from sub- to superclasses, no exception. Explicit casting is not possible because Integer and Float do not have direct connection (the common superclass is not enough for typecasting). Commented Jul 19, 2015 at 3:17
  • Ok make sense. So for all the numeric type direct conversion is only possible to Number type. Number number = floatt // because Number is a super type for Float class. Commented Jul 19, 2015 at 3:29
  • 2
    Just to be practical, you can use floatt.intValue() to convert a float to an int. Commented Jul 19, 2015 at 3:36
  • I saw you asked a lot of questions without accepting one. If some answer help you, just click the green mark beside it Commented Jul 19, 2015 at 6:15

2 Answers 2

2

You can cast floats to ints, but you cannot cast the wrapper objects to different types. You must first unwrap the Float wrapper and then you can cast the primitive float to an int.

Java will auto box/unbox primitives and their wrapper types, java will also widen primitive types automatically. But it won't do both.

Sign up to request clarification or add additional context in comments.

Comments

2

Let's see the bytecode for details. Use javap -c to see the byte codes. The code

float ff = Integer.INT_MAX; int ii = (int)ff; 

compiles to

 0: ldc #3 // float 2.14748365E9f 2: fstore_1 3: fload_1 4: f2i 5: istore_2 

If it's primitive type cast, as you can see from bytecode, f2i is inserted by the compiler. (as line 4 shows).

On the other hand, if you use wrapper class, compiler doesn't insert any type conversion instruction.

That's why you cannot cast them.

1 Comment

Thanks for a providing a different perspective

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.