Professional Documents
Culture Documents
Java p4
Java p4
Java p4
1 Introduction
Type Casting: In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing casting, the
destination data type may be smaller than the source data type when converting the data
type to another data type, that’s why it is also called narrowing conversion or Explicit
Conversion.
Syntax/Declaration:-
float x;
byte y;
y=(byte)x;
Type conversion : In type conversion, a data type is automatically converted into another
data type by a compiler at the compiler time. In type conversion, the destination data type
cannot be smaller than the source data type, that’s why it is also called widening
conversion or Implicit Conversion. One more important thing is that it can only be
applied to compatible data types.
int x=30;
float y;
y=x; // y==30.000000.
class Implicit{
/*Output
Implicit Conversion: 90
*/
Narrowing or Explicit conversion involves casting a higher data type into a lower one.
This type of conversion is not done automatically, and the desired data type needs to be
explicitly mentioned within ( ). Data types need not be compatible with each other for
explicit typecasting.
Class Explicit
}
/*Output
*/
The condition for type conversion in Java is that both of the datatypes should be
compatible with each other. For example, we can convert the byte to int but not byte to
float data type or string as it is not a valid conversion.
Type conversion that is not accepted in Java is when there is a conversion between two
incompatible datatypes. For example, converting int to a string data type is not accepted.
We need typecasting in Java to ensure the compatibility between the data types of the
operands. Type casting in Java helps in the prevention of errors and makes the program
to run as expected.