Difference between revisions of "Casting"

From CompSciWiki
Jump to: navigation, search
(converted code and outputs to use codeblock and output block templates)
 
(8 intermediate revisions by 5 users not shown)
Line 1: Line 1:
{{Template:1010Topic|Chapter_TOC=[[Java Fundamentals]]|Introduction=Typecasting is the act of converting between different variables types during runtime, while preserving the content of the original. This is necessary when doing arithmetic between different types, or when using code that expects a types different than the ones you are using.|Overview=This article will introduce you to the concept of [[Casting]], and explain when and why it is done. In addition, there is a reference table that explains the effects of casting between the different primitive types.}}
+
{{Template:1010Topic
 +
|Chapter_TOC=[[Java Fundamentals]]
 +
|Previous=[[Strings]]
 +
|Next=[[Named Constants]]
 +
|Body=
  
== Introduction to Casting ==
 
  
When working with various data types in Java, it may be necessary to convert between them. Casting attempts to convert from one data type to another. You get different results based on the data types you are casting. For instance, casting a primitive floating point value (type <code>float</code>) to an integer value (type <code>int</code>) results in the decimal portion of the <code>float</code> being ignored. This happens because the decimal portion cannot be represented by an <code>int</code>.  As a general rule, casting will always try to preserve as much of the data as possible. Converting from one data type to another can be done by the use of casting in Java.
+
== 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 <code>float</code>) to an integer value (type <code>int</code>) results in the decimal portion of the <code>float</code> being removed. This happens because the decimal portion cannot be represented by an <code>int</code>.  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 ==
 
== 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.
 
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 ===
 
=== Explicit ===
Line 13: Line 21:
 
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:
 
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:
  
<code>
+
{{CodeBlock
 +
|Code=
 
   float floatingPoint = 30.5f;
 
   float floatingPoint = 30.5f;
 
   int integerValue = (int)floatingPoint;
 
   int integerValue = (int)floatingPoint;
</code>
+
}}
  
 
The data type we are casting to is placed in brackets before the variable we are casting from. In the above example, the <code>float</code> ''floatingPoint'' is cast to type <code>int</code>, and is assigned to the variable ''integerValue''. This has the effect of assigning <code>30</code> to ''integerValue''. Since <code>int</code> variables can not represent a decimal, the <code>.5</code> gets omitted.
 
The data type we are casting to is placed in brackets before the variable we are casting from. In the above example, the <code>float</code> ''floatingPoint'' is cast to type <code>int</code>, and is assigned to the variable ''integerValue''. This has the effect of assigning <code>30</code> to ''integerValue''. Since <code>int</code> variables can not represent a decimal, the <code>.5</code> gets omitted.
 +
  
 
=== Implicit ===
 
=== Implicit ===
Line 29: Line 39:
  
 
The following example code demonstrates the two cases of an implicit cast:
 
The following example code demonstrates the two cases of an implicit cast:
<pre>
+
{{CodeBlock
 +
|Code=
 
   float result = 50.0f + 5;
 
   float result = 50.0f + 5;
 
   double doubleResult = result;
 
   double doubleResult = result;
</pre>
+
}}
  
 
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 [[Common Primitive Variables|double]] and assigned to ''doubleResult''.
 
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 [[Common Primitive Variables|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.
 
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 ==
 
== Casting Between Primitive Types ==
 
+
<table cellpadding = "20" border = "1">
{|border="1"
+
<tr>
!from\to!!int!!long!!float!!double
+
<td>from\to
|-
+
<td>int
!int
+
<td>long
  |OK||OK||2||OK
+
<td>float
|-
+
<td>double
!long
+
<tr>
  |1||OK||2||2
+
<td>int
|-
+
<td>OK
!float
+
<td>OK
  |3||3||OK||OK
+
<td>2
|-
+
<td>OK
!double
+
<tr>
  |3||3||1||OK
+
<td>long
|}
+
<td>1
 +
<td>OK
 +
<td>2
 +
<td>2
 +
<tr>
 +
<td>float
 +
<td>3
 +
<td>3
 +
<td>OK
 +
<td>OK
 +
<tr>
 +
<td>double
 +
<td>3
 +
<td>3
 +
<td>1
 +
<td>OK
 +
</tr>
 +
</table>
  
 
'''OK''': All information is preserved in the cast.
 
'''OK''': All information is preserved in the cast.
Line 63: Line 92:
  
 
'''3''': Fractional values represented by <code>float</code>s or <code>double</code>s are lost when casting to an integer type. Also, the range of values a <code>float</code> or <code>double</code> can represent is much larger than that of an <code>int</code> or <code>long</code>, so if value lies within this larger range, the result of the cast will be meaningless.
 
'''3''': Fractional values represented by <code>float</code>s or <code>double</code>s are lost when casting to an integer type. Also, the range of values a <code>float</code> or <code>double</code> can represent is much larger than that of an <code>int</code> or <code>long</code>, so if value lies within this larger range, the result of the cast will be meaningless.
 +
  
 
== Summary ==
 
== 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.
 
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 ==
 
== Full program of Examples ==
  
<PRE>
+
{{CodeBlock
 +
|Code=
 
class Casting_Example  
 
class Casting_Example  
 
{
 
{
Line 148: Line 180:
 
     }
 
     }
 
}
 
}
</PRE>
+
}}
 +
 
 +
{{OutputBlock
 +
|Code=
 +
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:\>
 +
}}
 +
 
  
 
[[Category:Java]]
 
[[Category:Java]]
 
[[Category:COMP_1010]]
 
[[Category:COMP_1010]]
 +
}}

Latest revision as of 11:56, 4 December 2011

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