Skip to content
Related Articles

Related Articles

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output

45
-90

Example 2: Out of limits

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output

-106
126

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :