1、外文原文 Working with Objects Casting and Converting Objects and Primitive Types Sometimes in your Java programs you may have a value stored somewhere that is the wrong type. Maybe its an instance of the wrong class, or perhaps its a float and you want it to be an int, or its an integer and you want it
2、to be a string. To convert the value of one type to another, you use a mechanism called casting. New Term: Casting is a mechanism of converting the value of an object or primitive type into another type. The result of a cast is a new object or value; casting does not affect the original object or va
3、lue. Although the concept of casting is a simple one, the rules for what types in Java can be converted to what other types are complicated by the fact that Java has both primitive types (int, float, boolean), and object types (String, Point, Window, and so on). Because of these three types, there a
4、re three forms of casts and conversions to talk about in this section: Casting between primitive types: int to float to boolean Casting between object types: an instance of a class to an instance of another class Converting primitive types to objects and then extracting primitive values back out of those objects Casting Primitive Types Casting between primitive types enables you to “convert” the value of one type to another primitive typefor example, to assign a number of one type to a