Why can't I use the Byte object / byte value for Double Object? Does conversion from byte to double affect accuracy?

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 of preventing byte casting in Double? .. I know Double to Byte for the exact reasons, if I'm not mistaken.

+6
source share
5 answers

Because it works both boxing and boxing.

This code works fine:

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

Reason: boxing conversion card primitives and their wrappers directly. I only say that a byte can be converted to a byte without explicit type casting. If you need to convert byte to 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 Double .

+3
source

The answer is how primitive types are automatically boxed into wrapper types in Java. You can also do something like

 Double y = Byte.valueOf(x).doubleValue(); Double z = (double) x; 
+1
source

You tried to apply a byte primitive to a Double class that you cannot do. If you try the following code instead, you will not have a problem:

 byte x=5; double y = (double)x; // No error 

If you want to use the Double class instead of the primitive Double , you can try the following:

 byte x=5; Double y = Double.valueOf(x).doubleValue(); 
0
source

The capitalized double is a class, not a primitive.

What you want to do is

  byte x=5; double y=(double)x; byte n=7; double m=(double)n; double c=n; 

Specifying a double byte with loss of precision (you lose all decimal numbers). A byte is like an int, but 8-bit.

0
source

You can look at this documentation of autoboxing and unpacking.

Autoboxing and unboxing allows developers to write cleaner code, making it easier to read. The following table lists the primitive types and their corresponding wrapper classes that are used by the Java compiler for autoboxing and unpacking:

enter image description here

Thus, based on this table, you cannot directly use autobox, nor can you drop into Double from byte. And also you cannot unpack twice from byte.


But you can apply the primitive to the primitive type, and then automatically translate it into an object of the Wrapper class. And you can unzip the Wrapper class object to its primitive type, and then pass it to other primitive types.

 byte x = 5; double temp = x; Double y = temp; // Can be written as byte x1 = 5; Double y1 = (double) x1; // ================ Byte n = 7; byte byteVal = n; double doubleVal = byteVal; Double m = doubleVal; // Can be written as Byte n1 = 7; Double m1 = (double) (byte) n1; // ================= // But I still wonder how below code is working double c = n; 
0
source

Source: https://habr.com/ru/post/985565/


All Articles