Sunday, 29 January 2012

Type Conversion and Casting in Java

Type conversion:
•In some cases we might want to assign value of one type to variable of another type. If both the source and destination types are compatible, then java performs the conversion implicitly(automatically).
•Examples of compatible types are int, long, short and byte. Also float and double are compatible with each other.
•char and boolean are not compatible with each other.
•Implicit conversion is also called as coercion.
•Explicit conversion (casting incompatible types) is called casting.


Java’s automatic conversion (Coercion):
•Java automatically converts from one type to another only when the following two conditions are satisfied:
1) Both types are compatible with each other.
2) The size of destination type is more than the source type.
•When the above two conditions are satisfied, java performs an implicit conversion. This is also known as “Widening Conversion”.
•int can be auto converted to long since the size of long is 64, where as size of int is 32. Similarly a byte can be auto converted or implicitly converted to int.
•int can also be implicitly converted to float and double.

Type Casting (Explicit Conversion):
•If we want to convert two types which are incompatible or if the size of destination type is less than the size of source type, then we must do the conversion explicitly. This process is also called as “type casting”.
•For example if we want to convert a int value to byte, java cannot do this automatically as the size of int is 32 and size of byte is only 8. So, we must explicitly cast an int to byte. This is also known as “narrowing conversion”
•Syntax for type casting is:

(destination type) value;

Type promotion in expressions:
•Java’s automatic type conversion also occurs in the case of expressions.
•Expression is a statement which consists of operands and operators, used to compute a result.

Example:
d = a + b * c;

In the above expression, a,b,c and d are operands and +, *, = are operators.


•Java promotes various types in expressions based on the following rules:
1) byte, short and char values are converted into values of type int.
2) If one operand is long, entire expression is promoted to long.
3) If one operand is float, entire expression is promoted to float.
4) If one operand is double, entire expression is promoted to double.

1 comment:

  1. click here:http://java.meritcampus.com/t/69/Type-casting-in-java

    ReplyDelete