Concept Flow - Type casting
Start with a value
Check target type
Perform cast
Use casted value
End
Type casting changes a value from one type to another, either automatically or by explicit instruction.
int i = 100; byte b = (byte) i; System.out.println(b);
| Step | Action | Value Before | Cast Type | Value After | Output |
|---|---|---|---|---|---|
| 1 | Declare int i | N/A | int | 100 | N/A |
| 2 | Cast int i to byte b | 100 | byte | 100 | N/A |
| 3 | Print byte b | 100 | byte | 100 | 100 |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| i | undefined | 100 | 100 | 100 |
| b | undefined | undefined | 100 | 100 |
Type casting changes a value's type. Implicit cast happens automatically if safe. Explicit cast uses (type) before value. Casting from larger to smaller type may lose data. Example: byte b = (byte) intValue;
What is type casting in Java?
Which of the following is the correct syntax for explicit type casting from double to int in Java?
int x = (int) 3.14;. Others are invalid in Java.What is the output of the following Java code?
double d = 9.99; int i = (int) d; System.out.println(i);
Identify the error in the following Java code snippet:
byte b = 130;
Given the code below, what will be the output?
int a = 300; byte b = (byte) a; System.out.println(b);
Note: byte range is -128 to 127.
Pass the test and this pattern moves unknown