Casting Primitive Data Types (CPDT)


CPDT:   SOLD       




Primitive type casting allows you to convert a value from one data type to another primitive type. This is common with numeric data types.

There is one primitive data type that we cannot cast, namely the boolean data type.


Get to know Primitive Type Casting

Example of typecasting int to double

When you store an integer in a variable of type double.

int numInt = 10;
double numDouble = numInt; //implicit cast

The example above explains implicitly that, even though the initial variable is of type integer, it can be converted to double, because the capacity of double is greater than integer.

Example of typecasting int to char or vice versa

Characters can be used as integers, because each character has a numeric value represented in the ASCII standard, and all programming languages ​​use this standard. For example, the letter "A" is coded 65.

char valChar = 'A';
int valInt = valChar;
System.out.print( valInt ); //casting explisit: keluaran 65

When we convert large data types to smaller data types, we must use explicit casts. Explicit casts follow the following form:

(dataType)value

Example:

double valDouble = 10.12;
int valInt = (int)valDouble; //men-convert valDouble ke tipe int
double x = 10.2;
int y = 2;
int result = (int)(x/y); //hasil typecast operasi ke int

Hope this is useful & happy learning!


Post a Comment

Previous Next

نموذج الاتصال