This program explains type casting in Java:
public class Main {
public static void main(String[] args) {
int someNumber = 10; //Starting Point
float someFloat = someNumber; //Automatic Casting - conversion - int to float
System.out.println(someNumber);
System.out.println(someFloat);
//Manual Casting
double someDouble = 3.14; //Starting Point
int newIntFromDouble = (int) someDouble;
float newFloatFromInt = (float) newIntFromDouble;
System.out.println(someDouble);
System.out.println(newIntFromDouble);
System.out.println(newFloatFromInt);
}
}
Line by line:
int someNumber = 10; //Starting Point
This line declares an integer variable named someNumber
and initializes it to the value 10.
float someFloat = someNumber; //Automatic Casting - conversion - int to float
This line declares a floating-point variable named someFloat
and assigns it the value of someNumber
. This is an example of automatic casting, where the integer value is automatically converted to a floating-point value.
System.out.println(someNumber);
System.out.println(someFloat);
These lines print the values of someNumber
and someFloat
to the console using the System.out.println()
method.
double someDouble = 3.14; //Starting Point
int newIntFromDouble = (int) someDouble;
float newFloatFromInt = (float) newIntFromDouble;
These lines declare a double-precision floating-point variable named someDouble
and initialize it to the value 3.14.
The next line demonstrates manual casting, where the double
value is cast to an int
using the (int)
syntax. The resulting int
value is then assigned to a variable named newIntFromDouble
.
The third line demonstrates another manual cast, where the int
value is cast to a float
using the (float)
syntax. The resulting float
value is then assigned to a variable named newFloatFromInt
.
System.out.println(someDouble);
System.out.println(newIntFromDouble);
System.out.println(newFloatFromInt);
These lines print the values of someDouble
, newIntFromDouble
, and newFloatFromInt
to the console using the System.out.println()
method.
No comments:
Post a Comment