Witscale Test Center

10.2 Data types and contexts of type change


10.2 Data types and contexts of type change

Java value can be either of primitive data type or of an object reference type. The type conversion and casting is applicable to both the data types. Hence, there are four kinds of type change:

 

         Primitive conversion

         Primitive casting

         Object reference conversion

         Object reference casting

 

Java has premeditated rules for all the four kinds of type change. Since these rules of type changes are relevant only in particular situations, we will study them in the context of these situations. In case of primitives, the type change may occur during any of the following situations:

 

         Assigning a primitive value to a variable

         Passing primitive as argument during a method call

         Arithmetic promotion during a binary operation

         Concatenating primitive with string reference using + operator

 

Object references also participate in assignments, method calls and string concatenations. Object reference’s type conversion takes place at compile time. The type may be changed in any of the following situations:

 

         Assigning an object reference to a variable

         Passing object reference as argument during a method call.

         Concatenating object reference with string reference using + operator

 

Note that arithmetic promotions do not take place for object references, as object references cannot act as arithmetic operands.

 

Let us start our discussion with the automatic type change in primitives. Next section discusses how the type conversion of primitive takes place in the various contexts such as assignment and method call.