Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaConverting Integer Data Type to Byte Data Type Using Typecasting in Java

Converting Integer Data Type to Byte Data Type Using Typecasting in Java

In primitive casting, we can convert the byte data type information into the integer data type information by using implicit typecasting. When we try to convert the integer data type information into the byte data type information that time explicit type casting takes place. 

Explicit Type of Casting

Converting higher data type information into lower data type information.

Syntax:

Datatype1 variable1 = information;

Datatype2 Variable2 = (Datatype2) Variable1 

Here

Datatype1 = Higher Data type

Datatype2 = Lower Data type

In this article, we are going to convert integer to byte.

Example 1:

Given int a = 1000, when we convert it to byte data type information it will show the output -24, it is due to the byte range being from -128 to 127.

Java




public class IntToByte {
    public static void main(String args[])
    {
        int a = 1000;
        byte b = (byte)a;
        System.out.println(b);
    }
}


Output:

-24

Explanation:

Java




public class IntegerByte {
    public static void main(String args[])
    {
        int c = 1000;
          // as byte range from -128 to 127
        int d = 128
        
          // Conditions if our value 
          // is positive or negative
        int x = c / d; 
        int f = x + 1;
        int g = x - 1;
        int e = (c > 0) ? f : g;
  
        if (x % 2 == 0) {
            System.out.println(c - d * x);
        }
        else {
            System.out.println(c - d * (e));
        }
    }
}


Output:

-24

Here we divided the byte range into two parts. 

  • -128 to 0
  • 0 to 127

And we have given conditions in two parts by using the if-else statement. Let’s see one more example.

Example 2:

Java




public class IntegerByte {
    public static void main(String args[])
    {
        int c = -2000;
        // as byte range from -128 to 127
        int d = 128
          // Conditions if our value
          // is positive or negative
        int x = c / d; 
        int f = x + 1;
        int g = x - 1;
        int e = (c > 0) ? f : g;
        if (x % 2 == 0) {
            System.out.println(c - d * x);
        }
        else {
            System.out.println(c - d * (e));
        }
    }
}


Output:

48

RELATED ARTICLES

Most Popular

Recent Comments