Casting

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Java Fundamentals


Introduction

When working with various data types in Java, it may be necessary to convert one type to another. Casting is what is used to do this. Depending of the types of data you are casting, you can get different results. For instance, casting a primitive floating point value (type float) to an integer value (type int) results in the decimal portion of the float being removed. This happens because the decimal portion cannot be represented by an int. As a general rule, casting will always try to preserve as much of the data as possible. See page 64 in the Gaddis text: http://tinyurl.com/gaddis64


Types of Casting

Java has two different types of casting. There is implicit and explicit casting. Implicit casting is when Java automatically changes the data for you. Explicit casting is when you have to tell Java what to change the variable's data type to. The two different types of casting are explained in detail below.


Explicit

An explicit cast occurs when the programmer writes out the type to be cast to as part of an expression. Explicit casts are easy to notice, because they use the following form:

 float floatingPoint = 30.5f;
  int integerValue = (int)floatingPoint; 

The data type we are casting to is placed in brackets before the variable we are casting from. In the above example, the float floatingPoint is cast to type int, and is assigned to the variable integerValue. This has the effect of assigning 30 to integerValue. Since int variables can not represent a decimal, the .5 gets omitted.


Implicit

An implicit cast happens when a value is converted to a different type automatically. Java does the cast without the programmer ever really caring.

This may happen during:

  • Assignment from one variable to another variable of a compatible type.
  • Conversion is required as part of an expression.

The following example code demonstrates the two cases of an implicit cast:

 float result = 50.0f + 5;
  double doubleResult = result; 

First, the integer 5 is implicitly cast to type float so it can be added to 50.0f, and then assigned to result. The float result is then implicitly cast to type double and assigned to doubleResult.

The main difference between Explicit and Implicit casting is you have to do the Explicit. Java takes care of all the implicit casting for you.


Casting Between Primitive Types

from\to int long float double
int OK OK 2 OK
long 1 OK 2 2
float 3 3 OK OK
double 3 3 1 OK

OK: All information is preserved in the cast.

1: There is a loss of information because the type being cast to cannot represent the full range of values of the original type. For example, a long can hold a much higher value than a int, so if a long is cast to type int and is holding a value an int cannot, the result will be meaningless.

2: Information may be lost since the type being cast to has less significant digits than the type being cast from.

3: Fractional values represented by floats or doubles are lost when casting to an integer type. Also, the range of values a float or double can represent is much larger than that of an int or long, so if value lies within this larger range, the result of the cast will be meaningless.


Summary

Casting is used to convert one data type to another. The two types of casting are explicit and implicit. Explicit casting is when you the programmer has to specifically say you want the conversion. Implicit casting is when Java does this automatically for you. You can use casting to change a variable from one data type to another data type.


Full program of Examples

 class Casting_Example 
{
    public static void main(String args[]) throws java.io.IOException
    {
        int intNumber;
        long longNumber;
        float floatNumber;
        double doubleNumber;
		
        System.out.println("Starting Casting_Example...");
        System.out.println("A series of casts with interesting results!\n");
		
		
/*** 1: Implicit cast example 1 ***********************************************/

        intNumber = 23;
        longNumber = intNumber; // Implicit cast example
        System.out.println("1: longNumber is now " + longNumber);
		
        System.out.println(); 	// New Line for formatting



/*** 2: Implicit cast example *************************************************/
		
        floatNumber = 2.2f; 	// The 'f' behind the 2.2 tells Java we want a 
                                // floating point number.
		
		
        floatNumber = floatNumber + 2; 	// Another Implicit cast example.
                                      // 2 is converted to a float automatically.
        System.out.println("2: floatNumber is now " + floatNumber);
		
        System.out.println();



/*** 3: Explicit cast example *************************************************/
		
        floatNumber = (float)2.2756; // Does this work?
        intNumber = (int)floatNumber; 	// Explicit Cast Example
		
        System.out.println("3: intNumber is now " + intNumber); // Is something
                                                      // missing in the result?
        System.out.println();



/*** 4: Explicit cast example *************************************************/

        doubleNumber = 2.25d; 
        floatNumber = (float)doubleNumber;
		
        System.out.println("4: floatNumber is now " + floatNumber); 
        System.out.println();



/*** 5: Explicit cast with a weird result *************************************/

        longNumber = Long.MAX_VALUE;
        intNumber = (int)longNumber;
		
        // What is intNumber?
		
        System.out.println("5: Explicit cast with a weird result");
		
        System.out.println("\tlongNumber = " + longNumber);
        System.out.println("\tintNumber = (int)longNumber;\n");
        System.out.println("What do you think the result of intNumber is?");
		
        System.out.print("Press Enter to see the result: ");
        System.in.read(); // Pay no attention to this line
        System.out.println("\tintNumber is now " + intNumber); 
        System.out.println("\nWere you close?");
    }
} 
 C:\>javac Casting_Example.java
C:\>java Casting_Example
Starting Casting_Example...
A series of casts with interesting results!

1: longNumber is now 23

2: floatNumber is now 4.2

3: intNumber is now 2

4: floatNumber is now 2.25

5: Explicit cast with a weird result
	longNumber = 9223372036854775807
	intNumber = (int)longNumber;

What do you think the result of intNumber is?
Press Enter to see the result: 
	intNumber is now -1
C:\> 
Previous Page: Strings Next Page: Named Constants