Witscale Test Center

10.1 Type changes in Java


10.1 Type changes in Java

All java values, whether stored in a variable or returned by an expression, has a type. You can decide the type from the type of variables, literals and methods mentioned in that expression. We already know the two broad categories of Java types, the primitives and object references. The value can have any of these two types. Sometime you may use a value in a context where the type of that value is not appropriate. In that case, the type needs to be changed. In java, the types are changed in either of the following two ways:

        1.Type Conversion: Java implicitly changes the type.

Java implicitly changes the type of an expression in some situations. For instance, if you are adding a float and int value as:


int a = 9;

float b = 8.4f;

float summation = a + b;  // conversion

 

The value 9 implicitly changes its type from int to float and then the addition of two float numbers takes place. This automatic change of type is called as conversion.


2. Type Casting: You can explicitly change the type.

Sometimes Java cannot determine appropriate type change for the given situation. In that case, you can change the type of a value explicitly using the cast operator. To cast an expression or variable to another type, just prefix it with the cast operator and specify the new type within the round parentheses. For example, the following code reads an object from a Hashtable collection birthdates, and then casts it to the type Date.

 

Date dob = (Date) birthdates.get("JohnQ"); //casting

System.out.println("John’s birthday month " + dob.getMonth());

 

The call birthdates.get("JohnQ") returns an object of type Object. The cast operators will change this object type to Date so that it can be stored in a variable dob that is of Date type. You can then treat that object as Date and call Date object’s methods such as getMonth().

 

There is more to type changing than just the syntax. Java imposes strict compile-time and runtime rules that govern which types need to be explicitly cast and which are implicitly converted. You need to know them. Fortunately, most of these rules can be generalized. They are easy to remember once you learn the common concept behind it. We will study these rules in different contexts of type change.