Data conversion with Java

Type conversion is a process of converting one type of data to another. There are three ways of doing it, namely implicit explicit and user defined.

  • Implicit : Automatic conversion:

    •  If one type of data is automatically converted into another type of data, it is known as implicit conversions. There is no loss of data resulted from implicit conversion.
  • Explicit : Defined or Enforcing Conversion) :

    • when you force the data to convert from one form to other. But explicit conversion is a forced conversion and there may be a data loss.
      int i = (int) f1;
      • where f1 is a float data type has value like 12.24
      • After conversion, integer data type will display 12, and the decimal values will be lost.
  • User defined:

    • Enumeration: like enum month { Jan=1, Feb==2 };
    • Structured:
      • slass, struct, union


Implicit Conversions in C# 

The implicit conversions, otherwise known as automatic conversion, would occur in numerous operation like invoking a function, cast expressions, assignments etc. The implicit conversions can be further classified into different categories. 

Implicit Numerical Conversions 

The possible implicit numerical conversions in C# are shown below. 
long x;
int y = 25;
x = y; //implicit numerical conversion

An implicit enumeration conversion permits the decimal integer literal 0 to be converted to any enum type. 

Implicit Reference Conversion 

The possible implicit reference conversions are

  1. From any reference type to object.
  2. From any class type D to another  class type B, provided D is inherited from B.
  3. From any class type A to interface type I, provided A implements I.
  4. From any interface type I2 to any other interface type I1, provided I2 inherits I1.
  5. From any array type to System.Array.
  6. From any array type A with element type a  to an array type B with element type b provided A & B differ only in element type (but the same number of elements) and both a and b are reference types and an implicit reference conversion exists between a & b.
  7. From any delegate type to System.Delegate type.
  8. From any array type or delegate type to System.ICloneable
  9. From null type to any reference type.

Boxing Conversions

Boxing is the conversion of any value type to object type. Boxing is an implicit conversion. Boxing a value of value type like int consists of allocating an object instance and copying the value of the value type into that object instance. An example for boxing is shown below. 

int x = 10;
object o = x; //Boxing
if(o is int)
Console.WriteLine(“o contains int type”);

A boxing conversion making a copy of the value being boxed. But when we convert a reference type to object type, the object continues to reference the same instance.