jaaavaaaa .. interview ... sup
- Get link
- X
- Other Apps
.........JAVA INTERVIEW .............
https://www.youtube.com/user/naveenanimation20
CASTING OPERATIONS, INT TO OTHER
int to byte Java
AFTER KNOWING PRIMITIVE DATA TYPES AND JAVA RULES OF DATA TYPE CASTING (TYPE CONVERSION), LET US CAST INT TO BYTE.
The byte takes 1 byte of memory and int takes 4 bytes of memory. Assigning 4 bytes of memory to 1 byte of memory requires explicit casting.
The left-side value can be assigned to any right-side value and is done implicitly. The reverse like int to byte requires explicit casting.
Examples of implicit casting
int x = 10;
long y = x;byte x = 10;
int y = x;
FOLLOWING PROGRAM ON INT TO BYTE EXPLAINS EXPLICIT CASTING, OBSERVE JAVA STYLE OF EXPLICIT CASTING.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Conversions
{
public static void main(String args[])
{
int i1 = 10;
// byte b1 = i1; // compilation error
byte b1 = (byte) i1;
System.out.println("int value: " + i1); // prints 10
System.out.println("Converted byte value: " + b1); // prints 10
}
}
|
Output screenshot of int to byte Java
byte b1 = i1;
The above statement raises a compilation error "possible loss of precision".
byte b1 = (byte) i1;
The int i1 is explicitly type casted to byte b1. Observe, the syntax of explicit casting. On both sides, it should be byte only.
Comments
Post a Comment