Data Type Conversion
Type casting is process to convert a variable from one data type to another data type. For example if we want to store a integer value in a float variable then we need to typecast integer into float.
If information is lost in an assignment, the programmer must confirm the assignment with a typecast.
The assignment between short and char requires an explicit cast.
long bigValue = 99L;
int squashed = (int)(bigValue);
long bigval = 6; // 6 is an int type, OK
int smallval = 99L; // 99L is a long, illegal
Promotion and Casting of Expressions
Variables are automatically promoted to a longer form (such as int to long).
Expression is assignment compatible if the variable type is at least as large (the same number of bits) as the expression type.
double z = 12.414F; // 12.414F is float, OK
float z1 = 12.414; // 12.414 is double, illegal
Java : Data Type Conversion Program List
Write a program to average of 36,45 and 53 using variables of adequate data type.
Write a program to input a floating point number and round it off to the nearest integer.
INPUT: Enter a floating point number: 12.3
OUTPUT: Rounded off to nearest integer:12
INPUT: Enter a floating point number: 14.5
OUTPUT: Rounded off to two places of decimal:15