Type Conversion in Java

Discussion in 'Java' started by pradeep, Aug 30, 2006.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    Automatic Conversion

    In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
    byte -> short -> int -> long -> float -> double

    The -> symbol used here should be interpreted as "to a". For example:

    // 64 bit long integer
    long myLongInteger;     
    // 32 bit standard integer
    int  myInteger;        
    myLongInteger = myInteger;
    The extra storage associated with the long integer, in the above example, will simply be padded with extra zeros.

    Explicit Conversion (Casting)

    The above will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion (assuming of course that the long integer will fit into a standard integer). This is done using a process known as a type cast:

    myInteger = (int) myLongInteger
    This tells the compiler that the type of myLongInteger must be temporarily changed to a int when the given assignment statement is processed. Thus, the cast only lasts for the duration of the assignment.

    Java type casts have the following form:

    (T) N

    where T is the name of a numeric type and N is a data item of another numeric type. The result is of type T.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice