
Patrick B. answered 05/09/20
Math and computer tutor/teacher
coercion is changing from one data type to another....
the act of doing so is called TYPE CASTING
integers can be changed to long integers naturally, which is called PROMOTION
integers can be changed to decimals also by promotion...
because all integers are decimals and long integers by definition...
integers are SUBSETS of longs and decimals...
but changing a decimal to integer requires COERCION
Coercion is usually required when you are changing an element of a parent
set, to a child set. In this case, the parent set is the set of decimals, while
the child set is the set of integers. That is every integer is also a decimal but
not vice versa. So changing from decimal to integer requires coercion via
type casting.
The compiler will complain (possible loss of data) if you try to do this
without type casting.
Here is an example: generating a random integer between 1 and 100:
int x = ( (int) (Math.random()* 99) )+1; // type casts random decimal to int ; 1 < x < 100
Math.random() returns an decimal number between 0 and 1
it gets multiplied by 99, so the result is a decimal number between 0 and 99
that gets coerced to an integer, so now it is an integer between 0 and 99...
then adds 1
Objects can be coerced too, especially if they are related via inheritance...
Any object is a descendant of type Object...
For Strings to primitive types I use the wrapper classes Integer, Double, Long:
Ex. String str = "12345";
Integer myInt = Integer.parseInt(str); ' 12345