Computer Science
Java Type Casting
Java Type Casting is the process of converting one data type into another data type. It is used when a value is assigned to a variable of a different data type or when an operation is performed between two variables of different data types. Type casting can be either implicit or explicit.
Written by Perlego with AI-assistance
Related key terms
1 of 5
4 Key excerpts on "Java Type Casting"
- eBook - PDF
- Arvind Kumar Bansal(Author)
- 2013(Publication Date)
- Chapman and Hall/CRC(Publisher)
This notion of type conversion is called casting . Casting allows the use of an object of one type in place of another compatible type, among the objects permitted by class-inheritance rules. Casting should make sure that data-types are compatible. If data-types are not compatible, then casting would give an incorrect result. A type is compatible if there is no information loss. For example, an integer attribute is compatible with a long integer because there is no information loss. 416 ◾ Introduction to Programming Languages However, a long integer object cannot be transformed to an integer because of the infor-mation loss. There are two possibilities of type conversions involving the use of inherited member-entities in an instance of a subclass. Case 1: An inherited method is used on an object that is a subtype of an object originally used in the inherited method. This case is called upcasting . Case 2: A virtual method in a subclass uses an inherited data-entity such that the cor-responding data-entity in the subclass is a subtype of the inherited data-entity. This type of transformation is called downcasting . 11.4.2.1 Upcasting Upcasting allows the promotion of an attribute to the corresponding attribute in the ancestor-class of an object to utilize an inherited method declared in the corresponding ancestor-class of the object. Upcasting is a special case of coercion because it preserves the information during the transformation of the data-type of a data-entity declared in subclass to the corresponding data-entity in the parent-class. Upcasting is safe because a class contains all the attributes of the ancestor-class (parent-class or classes further up in the hierarchy), and a method in the ancestor-class will already have all the needed attributes. After upcasting, the corresponding methods available to the ancestor-class can be used. Upcasting can be done automatically by the compiler, or it could be user-defined. - eBook - PDF
- Todd Greanier(Author)
- 2006(Publication Date)
- Sybex(Publisher)
For example, to cast a float variable named x to an int , you wrote code such as the following: int y = (int)x; This code narrows the floating-point number to a whole integer, effectively chopping off everything after the decimal point. You always have to use the cast operator for primitives if you are downcasting. You can also perform casting on objects in a similar fashion. The concept is the same. If you have a reference to a Machine but the runtime type is actually Toaster2 , you can use casting to gain access to the Toaster2 -specific methods. Just like the situation with primitive casting, you must perform a cast if you are narrowing from a superclass to a subclass. You do not ever have to explicitly cast if you are widening from a subclass to a superclass. The following code shows you what I mean. Only the first statement actually works without generating an error. Machine m = new Toaster2(); // upcasting, works fine Toaster2 t = new Machine(); // downcasting, fails The first line works fine because you are upcasting from a Toaster2 to the Machine superclass. This works because all Toaster2 objects are Machine objects as well. However, the second line fails because you are trying to shove a Machine object into a Toaster2 reference. This is not possible because not all Machine objects are Toaster2 objects. The rule is that you can always assign a subclass object to a superclass refer-ence, but you cannot do the opposite unless you perform an explicit cast. The syntax for casting objects is the same as for casting primitives. You simply put the reference type inside the parentheses and place this right before the object you want to cast. The following revised code now works in both cases. Machine m = new Toaster2(); // upcasting, works fine Toaster2 t = (Toaster2) m; // casting makes this work now 198 Chapter 7 You have to be careful when you cast objects like this, however. - eBook - PDF
- Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser(Authors)
- 2014(Publication Date)
- Wiley(Publisher)
Operators on the same line are evaluated in left-to-right order (except for assign- ment and prefix operations, which are evaluated in right-to-left order), subject to the conditional evaluation rule for boolean && and || operations. The operations are listed from highest to lowest precedence (we use exp to denote an atomic or parenthesized expression). Without parenthesization, higher precedence operators are performed before lower precedence operators. We have now discussed almost all of the operators listed in Table 1.3. A notable exception is the conditional operator, which involves evaluating a boolean expres- sion and then taking on the appropriate value depending on whether this boolean expression is true or false. (We discuss the use of the instanceof operator in the next chapter.) 28 Chapter 1. Java Programming Basics 1.4.3 Type Conversions Casting is an operation that allows us to change the type of a value. In essence, we can take a value of one type and cast it into an equivalent value of another type. There are two forms of casting in Java: explicit casting and implicit casting. Explicit Casting Java supports an explicit casting syntax with the following form: (type) exp where type is the type that we would like the expression exp to have. This syntax may only be used to cast from one primitive type to another primitive type, or from one reference type to another reference type. We will discuss its use between primitives here, and between reference types in Section 2.5.1. Casting from an int to a double is known as a widening cast, as the double type is more broad than the int type, and a conversion can be performed without losing information. But a cast from a double to an int is a narrowing cast; we may lose precision, as any fractional portion of the value will be truncated. - eBook - PDF
- Joyce Farrell(Author)
- 2018(Publication Date)
- Cengage Learning EMEA(Publisher)
The word cast is used in a similar fashion when referring to molding metal, as in cast iron. In a Java arithmetic cast, a value is “molded” into a different type. Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 99 Understanding Type Conversion Implicit and Explicit Casting In this section, you explore the concepts of the unifying types and casting. 1. Open the ArithmeticDemo.java file that uses integer values to calculate a sum, difference, and average. Change the class name to ArithmeticDemo3, and immediately save the file as ArithmeticDemo3.java. 2. In the previous version of the program, the average was calculated without decimal places because when two integers are divided, the result is an integer. To compute a more accurate average, change the data type for the average variable from int to double. 3. Save, compile, and execute the program. As the sample execution in Figure 2-42 shows, the program compiles and executes, but the average is still not accurate. The average of 20 and 19 is calculated to be just 19.0 because when two integers are divided, the decimal portion of the arithmetic result is lost. 4. Change the statement that computes the average to include a cast as follows: average = (double) sum / 2; 5. Save, compile, and execute the program. As shown in Figure 2-43, now the program displays a more accurate average. The integer sum has been cast to a double, and when the double is divided by the integer, the result is a double, which is then assigned to average.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.



