| Author |
What do You Mean By Casting?
|
Arun Giridharan
Ranch Hand
Joined: Sep 30, 2010
Posts: 290
|
|
What Casting Really does!! Means if you convert int to float or to double ,what changes happens in memory ,the data allocated for int is transferred from to the memory allocated for float and the memory allocated for int is destroyed ??? Can someone guide me please!! (What's Happening in Memory)
ThankYou
|
 |
Kirstie Fran
Ranch Hand
Joined: Feb 16, 2011
Posts: 33
|
|
|
A typecast changes the type of a value to another type. It doesn't change the value in memory, but the type of value.
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12950
|
|
No, the memory allocated for the int is not destroyed. When you cast from int to float (or double), the value of the int is converted to the format for a float or double. Nothing happens to the original int value.
When you cast reference types (not primitive types), then not much at all happens. The cast is then just a way to tell the compiler: "look, I know that this variable refers to an object of type X, so I want you to treat it that way". It doesn't do any automatic conversion of objects. It does, however, at runtime perform a check to see if the variable really refers to an object of type X, and if it doesn't, you get a ClassCastException.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32830
|
|
|
It's when you do a narrowing primitive conversion that you are most likely to change the values
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
To expand on the change in format Jesper mentioned: An int and a float both require 32 bits, but an int is stored as a 32-bit signed two's complement integer, and a float is a single-precision 32-bit IEEE 754 floating point. Therefore, as detailed under JLS - 5.1.2 Widening Primitive Conversion...
Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (ยง4.2.4).
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
 |
|
|
subject: What do You Mean By Casting?
|
|
|