Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can not cast a Byte object/byte value to Double object? does conversion from Byte to Double affect precision?

public class Primitive {
    public static void main(String []args) {


    byte x=5;
    Double y=(Double)x;  //Error :  Cannot cast from byte to Double.

    Byte n=7;
    Double m=(Double)n; //Error : cannot cast from Byte to Double.

    double c=n; //working right ..."double is primitive and Byte is object ".
    }
}

What is the point from preventing casting Byte to Double? .. i know Double to Byte for precision reasons if i am not wrong.

like image 502
Spmmr Avatar asked Apr 21 '15 05:04

Spmmr


People also ask

Can a byte value be cast to a double value?

Casting double to byte Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.

Can a byte object be cast to a double object?

No, an object cannot be cast to a primitive value.

Can a byte object be cast to a double value in Java?

Casting Byte object to double Unboxed as primitive byte value. And, implicitly casted to double (widening).

How do you convert an object to a double value?

There are three ways to convert a String to double value in Java, Double. parseDouble() method, Double. valueOf() method and by using new Double() constructor and then storing the resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time.


1 Answers

Because that's how auto-boxing and un-boxing works.

This code works fine :

    byte x = 5;
    Integer i = (int) x;

Reason : boxing conversion map primitives and their wrappers directly. What I am saying is only a byte can be converted to a Byte without explicit type-casting. If you need to convert a byte to a Double, you need to explicitly use something like this :

    byte x = 5;
    Double d = (Double) (double) x; 

because only a double can be converted to a Double.

like image 169
TheLostMind Avatar answered Oct 19 '22 23:10

TheLostMind