Post date: Jan 20, 2014 8:19:20 AM
The cast operator lets you manually convert a value, even if it means that a narrowing conversion will take place. Cast operators are unary operators that appear as a data type name enclosed in a set of parentheses. The operator precedes the value being converted.
Here is an example:
The cast operator in this statement is the word int inside the parentheses, It returns the value in number, converted co an int. This converted value is then stored in x. If number were a floating-point variable, such as a float or a double, the value that is returned would be truncated, which means the fractional part of the number is lost. The original value in the number variable is not changed, however.
several statements using cast operators.
littleNum = (short)bigNum; The cast operator returns the value in bigNum, converted to a short. The converted value is assigned to the variable littleNum.
x = (long)3.7; The cast operator is applied to the expression 3.7. The operator returns the value J, which is assigned to the variable x.
number = (int)72.567; The cast operator is applied to the expression 72.567. The operator returns 72, which is used to initialize the variable number.
value = (float)x; The cast operator returns the value in x, converted to a float. The converted value is assigned to the variable value.
value = (byte)number; The cast operator returns the value in number, converted to a byte. The converted value is assigned to the variable value.