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 ;
int d = 128 ;
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.
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 ;
int d = 128 ;
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!