Type Conversion – Casting

It is sometimes necessary to convert a data item of one type to another type. For example when it is necessary to perform some arithmetic using data items of different types (so called mixed mode arithmetic). Under certain circumstances Type conversion can be carried out automatically, in other cases it must be "forced" manually (explicitly). Automatic Conversion

In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign: byte -> short -> int -> long -> float -> double The -> symbol used here should be interpreted as "to a". For example:

// 64 bit long integer
long myLongInteger;
// 32 bit standard integer
int myInteger;
myLongInteger = myInteger;
The extra storage associated with the long integer, in the above example, will simply be padded with extra zeros.

Explicit Conversion (Casting)

The above will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion (assuming of course that the long integer will fit into a standard integer). This is done using a process known as a type cast: myInteger = (int) myLongInteger

This tells the compiler that the type of myLongInteger must be temporarily changed to a int when the given assignment statement is processed. Thus, the cast only lasts for the duration of the assignment. Java type casts have the following form: (T) N where T is the name of a numeric type and N is a data item of another numeric type. The result is of type T.

Distinction Between Casting and Rounding

Given a data item of type double or a float we can change the type of this item so that it becomes a data item of type long or int using a cast operation as described above. What happens in this case is that the exponent part of the real number is simply omitted. For example 99.9999 will become 99. In cases such as this it might be more desirable to say that the integer equivalent of 99.9999 is 100 (i.e. round up). We cannot achieve this using a cast, however the Java Math class contains methods to achieve this, namely the methods rint and round.

The first rounds a double up or down to its nearest integer equivalent (without converting the type). The second has two versions, one to round and convert a float to an int, and one to round and convert a double to a long. Consider the Java code given in Table 1. The code allows a user to input a double which is then output; first as an integer using a cast, then as an integer using the round method, and then as double rounded to the nearest integer.

import java.io.*;
class RoundingEx {
//Create BufferedReader class instance
public static InoutStreamReader input = new InputStreamReader(System.in);
public static BufferedReader keyboardinput = new Buffered Reader(input);
  public static void main(String[]args) throws IO Exception {
    double inputDouble;
      System.Out.PrintIn(" Input a double precision number =   ");
      inputDouble = Double.parseDouble(keyboardInput.readLine());
      System.Out.PrintIn("Input converted to an int using " +
      		     "cast     ="(int)inputDouble);
      System.Out.PrintIn("Input converted to an int using 'round'" +
      		     "method = "+ Math.round(inputDouble));
      System.Out.PrintIn("Input converted to an \"int\" using 'rint'" +
		     "method = "+ Math.rint(inputDouble));
      }
}     


OUTPUT
$ java RoundingEx
Input a double precision number = 1.2
input converted to an int using a cast = 1
Input concered to an int using 'round' method = 1
Input converted to an "int" using 'rint' method = 1.0  
$ java RoundingEx
Input a double precision numbe = 1.8
Input converted to an int using a cast = 1
Input converted to an int using 'round' method = 2
Input converted to an "int" using 'rint' method = 2.0
$ java RoundingEx
Input a double precision numbe = 1.5
Input converted to an int using a cast = 1
Input converted to an int using 'round' method = 2
Input converted to an "int" using 'rint' method = 2.0


FAQ Home

 
Printer friendly version of the FAQ-JAVA-Type-Conversion-Casting page


Sponsored links

Build IT Knowledge with Current & Trusted Content
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.
Check Out IT Certification Preparation Materials
Sign Up With SkillSoft & Get Access to Training Materials for Over 50 Professional Certifications.
SFTP components for .NET
Add complete SSH and SFTP support to your .NET framework application
Virtual File System SDK
Create your own file systems in Windows and .NET applications
PureCM Software Configuration Management
Version control and integrated issue tracking - powerful and easy to use. Get your FREE trial now!

Advertisement



Free Magazine

Free Magazines
eWeek The essential technology information source for builders of e-business.... subscribe now

Newsletter | Submit Content | About | Advertising | Awards | Contact Us | Link to us |
© 1996-2008 Community Networks Ltd All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Synchron Data - .NET development.