Assignment: Module 02 - Part 01
![]() |
Assignment: Module 02 - Part 01 |
04. Write a class TypeCasting to show the type casting of byte,int,float and long variables with any values.
Note: use type casting conversions. (e.g.) int c = 9; byte b = (byte) c;
Here is an example of a Java program called "TypeCasting" that demonstrates type casting of byte, int, float, and long variables:
package com.grazitti;
public class TypeCasting {
public static void main(String[] args) {
int c = 9;
byte b = (byte) c;
System.out.println("c = " + c + " , b = " + b);
float f = 9.5f;
int i = (int) f;
System.out.println("f = " + f + " , i = " + i);
long l = 99999999;
float f2 = (float) l;
System.out.println("l = " + l + " , f2 = " + f2);
double d = 9.99;
long l2 = (long) d;
System.out.println("d = " + d + " , l2 = " + l2);
}
}
Explanation:
In the above code, we are first casting int variable c to byte variable b.
Then we are casting float variable f to int variable i.
Then we are casting long variable l to float variable f2.
And lastly, we are casting double variable d to long variable l2.
To run the program:
- Open the Eclipse, create a new Java project.
- Right-click on the src folder in the project and select "New" > "Package".
- In the "Name" field, enter "com.grazitti"
- Right-click on the newly created package and select "New" > "Class".
- In the "Name" field, enter "TypeCasting" and click "Finish".
- copy paste the above code in the TypeCasting.java file
- Save the file and run the program by right-clicking on the TypeCasting.java file and selecting "Run As" > "Java Application"
Note: You need to make sure that the path of JDK is added to the system's environmental variables in order to run the program.