Type Casting in Java

Type Casting:
============
Need of TypeCasting:
----------------------------
Consider a payroll system of an organization.  The gross salary of  an employee calculated and stored in varibles of float type.  Currently the output is shown as float values.  The payroll department wants the salary amount as  a whole number and thus wants any digits after the decimal point of the calculated salary to be ignored.  The programmer is able to  achieve this using the typecasting feature of Java.  Typecasting allows you to change the datatype of a variable.

Type Casting is of two types
1. Implicit TypeCasting
2. Explicit Type Casting

1. Implicit TypeCasting:
-------------------------------
Implicit typecasting refers to automatic conversion of datatypes.  This is done by JVM.  Implicit typecasting is done only when the destination and source data types belongs to same hierarchy.  In destination data type must hold a  larger range of values than the source data type.  So Implicit typecasting prevents the loss of data.  If you have int type value to, you can assign long type of variable.

int -----> Implicit Typecasting ------>long

Example:
-----------
//Implicit Conversion

class A29
{
public static void main(String args[])
{
long   a = 10, result;
int   b = 7;

result = a + b;

System.out.println("a + b = "+ result);
}
}

Explicit Typecasting:-
--------------------------
Explicit typecasting refers to changing a data type of  higher precision into a data type of lower precision.  For example, using  explicit typecasting, you can manually convert the value of float type into int type.  This typecasting might result in loss of data, the digits after the decimal point are lost.

float----->Explicit Conversion----->int

Example:
-----------
class A35
{
    public static void main(String args[])
    {
        int x = 25;
      byte y = (byte) x;
        //byte y=x;
        System.out.println("y is : "+y);
    }
}


Example:
-----------
class A35
{
    public static void main(String args[])
    {
//Explicit
        /*int x = 25;
      byte y = (byte) x;
        //byte y=x;
        System.out.println("y is : "+y);*/

//Implicit

byte x = 25;
      int y =  x;
     System.out.println("y is : "+y);

    }
}

No comments:

Post a Comment

PHP Notes

The Characteristics of PHP:- ----------------------------------- 1.PHP is a high level programming language. 2.It is a server-side scrip...