user18280260
user18280260

Reputation: 11

Casting datatypes

// ( i'm trying to cast From Float to Integer Value )

public class Genark
{
static <T extends Number , E extends Number > void add ( T o2 )
{
@SuppressWarnings("unchecked")
E e2 = (E) o2; // it is must be casted to integer ( but something went wrong )

System.out.println( e2.getClass().getName() ); // java.lang.Float ( it is not casted )
}

public static void main(String[] args)
{

Genark.<Float , Integer>add( 6.2f );

}

/**************************** I want to do something like that ************************/

float y = 6.2f;
int x = (int) y;
System.out.println( x);   // here it is casted to Integer Successfully

}
}

Upvotes: 1

Views: 57

Answers (1)

Sweeper
Sweeper

Reputation: 272845

float -> int and Float -> Integer are two different conversions that involves different types. Note that Float and Integer are the boxed versions of float and int respectively. In a casting context, the former is allowed and the latter is not:

float x = 0f;
Float y = 0f;
int a = (int)x; // OK
Integer b = (Integer)y; // error;

The Float -> Integer conversion actually consists of 3 smaller conversions - the Float needs to be unboxed, narrowed, then boxed again.

Float -unbox-> float -narrowing-> int -box-> Integer

This is not allowed in a casting context. See a list of allowed conversions here.

On the other hand, float -> int is just a simple narrowing conversion.


That said, this doesn't really matter in your code because you wrote a unchecked cast (notice the unchecked warning!), which does nothing at runtime. This is because you are casting to the generic type parameter E, and the JVM won't know what the actual type for E is at runtime because of type erasure. This is why there is no error at runtime or compile time.

The cast will only happen when you do some Integer-specific things to e2, but there is no way to do that within add, and you don't return e2 either, so nothing substantial happens.

For the sake of illustration, let's say you have:

public static void main(String[] args) {
    Integer x = add(1f);
    System.out.println(x.compareTo(2));
}

static <T extends Number , E extends Number > E add ( T o2 )
{
    @SuppressWarnings("unchecked")
    E e2 = (E) o2;
    return e2;
}

Then it will crash at runtime when trying to call x.compareTo(2), an Integer-specific method.

Upvotes: 1

Related Questions