This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Just to add on top of what Jesper has clearly explained, Casting is a process in which the programmer requests the compiler to treat one type/kind of data (object) to be of another kind so as to avoid any errors during compilation. Otherwise, the compilation would not succeed as the compiler is not instructed to do so.
One example is, when you have an integer whose value is less and trying to assign it into a byte variable. Let's say,
int i = 5; byte b = i;
Even though the actual value in 'i' is less than or allowed to get stored into a variable of type byte, the compiler can't check and ensure the same during the runtime. So, just to prevent the errors thrown by JVM at the runtime, the compiler gives an error and does not let the program compile successfully.
To proceed further, we do request the compiler by making an explicit typecast or cast as follows.
int i = 5; byte b = (byte) i;
This way the program is compiled and run successfully. However, if the value stored in 'i' is more than the maximum limit of byte's, the value is truncated accordingly. [ July 10, 2008: Message edited by: Raghavan Muthu ]
Also note that it is never necessary, nor does it ever make any sense, to cast the result of a "new" expression this way. Casting makes sense only when the compiler doesn't already know the exact class of an object. Here, the cast cannot add any new information, since the compiler knows the exact type of the object being created.
This will never throw a ClassCastException. If the cast is invalid, the code will not compile.