Casting - AnsuDennis/Java GitHub Wiki
Casting is used when we want to convert on data type to another. There are two types of Casting • Implicit Casting • Explicit Casting
Implicit Casting is done by the compiler. Good examples of implicit casting are all the automatic widening conversions i.e. storing smaller values in larger variable types.
int value = 100; long number = value; //Implicit Casting float f = 100; //Implicit Casting
Explicit Casting is done through code. Good examples of explicit casting are the narrowing conversions. Storing larger values into smaller variable types;
long number1 = 25678; int number2 = (int)number1;//Explicit Casting //int x = 35.35;//COMPILER ERROR int x = (int)35.35;//Explicit Casting
Explicit casting would cause truncation of value if the value stored is greater than the size of the variable.
int bigValue = 280; byte small = (byte) bigValue; System.out.println(small);//output 24. Only 8 bits remain.
When you assign value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and if not then they need to be casted or converted explicitly. For example, assigning an int value to a long variable.
Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This happens when:
The two data types are compatible. When we assign value of a smaller data type to a bigger data type. For Example, in java the numeric data types are compatible with each other but no automatic conversion is supported from numeric type to char or boolean. Also, char and boolean are not compatible with each other.
Byte > Short > Int > Long > Float > Double
Narrowing or Explicit Conversion
If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or narrowing.
This is useful for incompatible data types where automatic conversion cannot be done. Here, target-type specifies the desired type to convert the specified value to. Char and number are not compatible with each other. Let’s see when we try to convert one into other.
Double > Float > Long > Int > Short > Byte
Type promotion in Expressions
While evaluating expressions, the intermediate value may exceed the range of operands and hence the expression value will be promoted. Some conditions for type promotion are:
Java automatically promotes each byte, short, or char operand to int when evaluating an expression. If one operand is a long, float or double the whole expression is promoted to long, float or double respectively.
Explicit type casting in Expressions
While evaluating expressions, the result is automatically updated to larger data type of the operand. But if we store that result in any smaller data type it generates compile time error, due to which we need to type cast the result.