Witscale Test Center

10.3 Type conversion in primitives


10.3 Type conversion in primitives

Sometimes Java allows you to assign a value of one type to a variable of different type. In such cases, Java converts the type implicitly. For example, following code assigns an int value to a double variable.

 

int intNumber = 5;

double doubleNumber;

doubleNumber = intNumber;  // type conversion, int ==> double

 

The doubleNumber is variable of type double and hence it can hold only double values. It cannot hold an int value as it is. Therefore, Java converts it first into a double value. Therefore 5 becomes 5.0d and then it is stored in the double variable doubleNumber. However, Java will not always convert the dissimilar types. For example, if you reverse the assignment and try to store the double value into the int variable as:

 

int intNumber;

double doubleNumber = 5.112132334;

intNumber = doubleNumber;       // Compiler Error

 

This code will not compile. Compiler will flag an error saying something like "Type mismatch: cannot convert from double to int" or "possible loss of precision"   This error is flagged because Java considers double as wider data type than int. When you try to store a double value in an int, it is like pouring a 1 quart coffee in 8 ounce coffee cup. You may not spill the coffee (if the coffee is less) but there is good chance that you will.  On the other hand, if you are storing an int value in double variable, it is considered as perfectly legal.  The table 10.1 illustrates the difference between these two cases metaphorically.


 

Table 10.1 Possible loss of information while storing a wider value in a narrower type

 

Storing narrower int value to a wider datatype double

(No spilling)

Storing wider double value to a narrower datatype int

(Spilling is possible)



 

Thus, Java allows you to store the narrower int value to a wider datatype double. It will perform the type change on your behalf. However, you cannot store the wider value into a narrower data type. Java compiler predicts the possible loss of information when you store say for example, a double value into an int variable. The compiler prefers to be safe and warns you right away by flagging an error. Thus, conversion does not take place when you try to store a value of a wider data type into a variable of narrower data type. If you want to do it, you need to change the type explicitly using the casting, which we will discuss later.

 

Java does not change a primitive type to object reference or vice versa. Primitives and object references are incompatible types and cannot be converted or even cast to each other. The only exception to this rule is the string concatenation with + where a primitive operand is converted into a String object when the other operand is of type String.