Can you please explain me this question? | Core Java Forum
H
Harika Posted on 14/06/2023

please explain me the question which is in documentation.


Y
Yogesh Chawla Replied on 20/06/2023

See byte data ranges between -127(-2^7 -1) to 128(2^7)

In this example, double is 295 which is atleast 2 times bigger than byte range(128) so we will have to subtract to reach to the byte possible range

//128+128 which is 256, substract 295 - 256 which will come to be 39, this is after converting double to byte that fits in byte range

//Similary int value in this example is also bigger than byte so 300 - (128+128) = 44
//Here we are basically trying to understand the data that fits in its byte range after conversion.

public class Sample {
    public static void main( String args[] ) {
        
    	double a = 295.04;
    	int b = 300;
    	byte c = (byte)a;
    	byte d = (byte)b;
    	System.out.println(c+ " " + d);
    	
    }

}