Convert Long Values into Byte Using Explicit Casting in Java
Last Updated :
29 Oct, 2020
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
import java.io.*;
class GFG {
public static void main(String[] args)
{
long firstLong = 45 ;
long secondLong = - 90 ;
byte firstByte = ( byte )firstLong;
byte secondByte = ( byte )secondLong;
System.out.println(firstByte);
System.out.println(secondByte);
}
}
|
Example 2: Out of limits
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
long firstLong = 150 ;
long secondLong = - 130 ;
byte firstByte = ( byte )firstLong;
byte secondByte = ( byte )secondLong;
System.out.println(firstByte);
System.out.println(secondByte);
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...