Convert Long Values into Byte Using Explicit Casting in Java
In Java, a byte can contain only values from -128 to 127, if we try to cast a long value above or below the limits of the byte then there will be a precision loss.
1. byte: The byte data type is an 8-bit signed two’s complement integer.
Syntax:
byte varName; // Default value 0
Values:
1 byte (8 bits) : -128 to 127
2. long: The long data type is a 64-bit two’s complement integer.
Syntax:
long varName; // Default value 0
Values:
8 byte (64 bits): -9223372036854775808 to 9223372036854775807
Example 1: In limits
Java
// Java Program to Convert Long (under Byte limit) // Values into Byte using explicit casting import java.io.*; class GFG { public static void main(String[] args) { long firstLong = 45 ; long secondLong = - 90 ; // explicit type conversion from long to byte byte firstByte = ( byte )firstLong; byte secondByte = ( byte )secondLong; // printing typecasted value System.out.println(firstByte); System.out.println(secondByte); } } |
Output
45 -90
Example 2: Out of limits
Java
// Java Program to Convert Long (out of the // limits of Byte) Values into Byte using // explicit casting import java.io.*; class GFG { public static void main(String[] args) { long firstLong = 150 ; long secondLong = - 130 ; // explicit type conversion from long to byte byte firstByte = ( byte )firstLong; byte secondByte = ( byte )secondLong; // printing typecasted value System.out.println(firstByte); System.out.println(secondByte); } } |
Output
-106 126
Contact Us