Sunday, October 27, 2013

Type Conversion and casting

It is common to assign a value of one type to a variable of another type. if the two types are compatible, them java will perform will perform the conversion automatically.
Example
class type{
    public static void main(String[] args) {
        int i = 100;
        long l = i;
    }
}
It is always possible to assign an int value to long variable However, not all types are compatible. Therefore, not all conversions are compatible. Therefore not all conversions are implicitly allowed , Example there is no conversion allowed from double to byte. However conversion between incompatible types is also possible. For this, you must use a cast, which performs an explicit conversion between incompatible types.

Automatic Conversions

When one type of data is assigned to another type of variable, an automaric conversion will take place if the following are true.

  • The two types are compatible.
  • the destination type is larger than the source type.
When these are true, a widening conversion takes place Example the int type is always large enough to hold all valid byte values, so no explicit casting is required. For widening conversion, the numeric type, including Integer and floating point types,are compatible with each other, However, numeric types are not compatible with char or boolean.  Also char and boolean are also not compatible with each other. Also java performs an automatic conversion when storing a literal integer constant into variable of type byte, short or long.

Casting Incompatible types 

What if you want to assign an int value to byte variable? This conversion will not be performed automatically as a byte is smaller then an int. this type of conversion is called as narrowing conversion,since you are explicitly making the value narrower so that it will fit into the target type,
To create a conversion between two incompatible types, you must use a cast. A cast has Form:
Data_Type Variable_name = (Target_Data_Type) Value;
Here, target type is the desired type to convert the specified value to Example the following code fragment casts an int to a byte, it will be reduced to modulo byte's range.
class type{
    public static void main(String[] args) {
        int a = 258;
        byte b = (byte) a;
        System.out.println("b is : "+b);
    }
}
Output 
b is : 2

When a floating point value is assigned top an int, truncation will occur. Since integers do not have fraction parts, When a floating point is assigned to an int variable, the fractional part gets lost.
class Conversion {

    public static void main(String[] args) {
        byte b;
        int i = 257;
        double d = 323.142;
        System.out.println("Convert Int to byte");
        b = (byte) i;
        System.out.println("i and b : "+i+" "+b);
        System.out.println("Convert double to int ");
        i = (int) d;
        System.out.println("d and i : "+d+" "+ i);
        System.out.println("Convert double to byte ");
        b = (byte) d;
        System.out.println("d and b : "+d+" "+b);

    }
}

Output 
Convert Int to byte
i and b : 257 1
Convert double to int
d and i : 323.142 323
Convert double to byte

d and b : 323.142 67

When 257 is cast into a byte variable, the result is the remainder of the division of 257 by 256 (range of a byte) which is 1 in this case.When d is converted to an int, its fractional part is lost. When d is converted to a byte, its fractional part is lost, and the value is reduced modulo 256 which in this case is 67.

Automatic type promotion in expressions

In addition to assignments, conversions occur in expressions. Take a look at the following example.

class AutoCast{
    public static void main(String[] args) {
        byte a = 40;
        byte b = 50;
        byte c = 100;
        int d = a * b / c;
    }
}

The result of the intermediate term a * b is 2000, which exceeds the range of a byte. To handle this problem. Java automatically promotes each byte or short operand to int when evaluation an expression.This means that subexpression a*b is performed using integers, and not bytes.Therefore, The result of the intermediate expression, 50 * 40 is legal even though a and b are both specified as type byte.

Type Promotion Rules 

In addition to the promotion of bytes and shorts to int, defines several type promotion rules that apply to expression, 
  • All Byte and short values are promoted to int, as hast described.
  • if one operand is a long, the whole expression is promoted to long.
  • If one operand is a float, the entire expression is promoted to float.
  • If any of the operands is double, the result is double.
class Promote{

    public static void main(String[] args) {
        byte b = 42;
        char c = 'a';
        short s = 1024;
        int i = 50000;
        float f = 5.67f;
        double d = 0.1234;
        double result = (f*b)+(i/c)-(d*c);
        System.out.println((f*b)+"+"+(i/c)+"-"+(d*c));

    }
}
Lets Us take look at the following line
double result = (f*b)+(i/c)-(d*c);

In the first subexpression, f*b, b is promoted to a float and the result of the subexpression is float. Next in the subexpression i/c, c is promoted to int , and the result is of type int Then in d*s, the value of s is promoted to double , and the type of the subexpression is double.Finally, these three intermediate values, float, int  and double are considered.The Outcome of float plus an int is a float.Then the resultant float minus the last double,which is the type for the final result of the expression. 

No comments:

Post a Comment