JAVA

Type Conversion and Casting.

There are two kind of type conversion in Java:

  1. Implicit type-conversion:
  2. Explicit type-casting:

1. Implicit type-conversion:

Implicit type-conversion performed by the compiler automatically; if there will be no loss of precision.

Example:

int i = 3;
double f;
f = i;// it is ok, no explicit type casing required.
// here, f = 3.0

Widening Conversion:

The rule is to promote the smaller type to bigger type to prevent loss of precision, known as Widening Conversion (as above example).


2. Explicit type-casting:

  • Explicit type-casting performed via a type-casting operator in the prefix form of (new-type) operand.
  • Type-casting forces an explicit conversion of type of a value. Type casting is an operation which takes one operand, operates on it and returns an equivalent value in the specified type.

Syntax:

newValue = (typecast)value;

Example:

double f = 3.5;
int i;
i = (int)f;	// it cast double value 3.5 to int 3.

Narrowing Casting:

Explicit type cast is requires to Narrowing conversion to inform the compiler that you are aware of the possible loss of precision (as above example).




Subscribe us on Youtube

Share This Page on


Ask Question