Java Programming

Type Conversion In Java (Super Easy)

Sometimes there is a need to convert one data type into another i.e., we need to store data from one variable to another variable into a different data type. In this situation, we need to convert these data type into another data type.

Please refer – ⇒ Data Types in Java ( int, float, char )

Type Conversion In Java

Type Conversion in Java allows us to convert one form of a datatype into another form. For example- conversion of int data type into the float.

Suppose we want to store any fractional value and the data type which we are using to store that data is “int” then there is a need to convert the “int” data type into “float” data type because “int” data type can not store fractional value.

CONVERSION TABLE ( Without any Loss in Data )

Data Type Conversion
Byte Short, char, int, long, double, float
Short int, long, double, float
Char int, long, double, float
int long, double, float
long float, double
float double

Java Language Supports two type of conversions,

  1. Automatic Conversion
  2. Explicit Conversion ( Type Casting )

AUTOMATIC CONVERSION

Automatic Conversion refers to the type of conversion which has to be done automatically i.e., we don’t need to add an extra line of code to convert it into another type of data. Automatic conversion generally occurs when the data type exceeds the limit of storing the value, so it automatically gets converted to its higher data type.

For Example-

byte a=98,768;

 

In above statement, byte datatype exceeded its limit of storing the value so it automatically gets converted into an integer type.

EXPLICIT CONVERSION ( TYPE CASTING )

Type Casting refers to the process of conversion of one type of data into another forcefully using predefined syntax. The need for typecasting arises when we need to store a different value other than the predefined datatype can store.

It can be done using a predefined syntax,

type variable1=(type) variable2;

For example,

int num1=50;

byte num2=(byte)num1;

 

ALSO READ

Leave a Reply