Type Casting in Practice
Apply type casting in real-world scenarios including numeric calculations and OOP hierarchies.
Type Casting in Practice is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Type Casting in Practice
Type casting is used everywhere in real Java code: numeric calculations, OOP hierarchies, generic collections, and legacy APIs. This lesson covers practical patterns and pitfalls.
Upcast: Polymorphism
An upcast converts a subtype to a supertype. It is always safe and implicit — no cast operator needed. This enables polymorphism.
class Payment {}
class CreditCardPayment extends Payment {
public void authorizeCard() {}
}
CreditCardPayment cc = new CreditCardPayment();
Payment p = cc; // implicit upcast — always safe
// p.authorizeCard(); // Compile error — Payment doesn't have this method
// need downcast to access subclass methodsDowncast: Accessing Subtype Members
A downcast converts a supertype reference back to the original subtype. It requires an explicit cast and throws ClassCastException if the object is not actually that subtype.
Payment p = new CreditCardPayment();
// Downcast to access CreditCardPayment-specific method
if (p instanceof CreditCardPayment cc) {
cc.authorizeCard(); // safe with pattern matching
System.out.println("Card authorized");
}
// Unsafe downcast without check:
try {
BankTransfer bt = (BankTransfer) p; // ClassCastException!
} catch (ClassCastException e) {
System.out.println("Wrong type!");
}Numeric Casting in Calculations
Integer division truncates. Cast to double before dividing to get a precise result. This is one of the most common arithmetic bugs in Java.
int totalRevenue = 1000;
int months = 3;
// Integer division — truncates!
double wrong = totalRevenue / months;
System.out.println(wrong); // 333.0 (not 333.33)
// Correct: cast one operand to double first
double correct = (double) totalRevenue / months;
System.out.println(correct); // 333.3333333333333Casting in Collections (Pre-Generics)
Legacy code often stores objects in raw collections. Downcasting is necessary to retrieve typed values — always check with instanceof first.
import java.util.*;
// Legacy raw list (pre-Java 5 style)
List legacyList = new ArrayList();
legacyList.add("Alice");
legacyList.add(42);
for (Object item : legacyList) {
if (item instanceof String s) {
System.out.println("Name: " + s.toUpperCase());
} else if (item instanceof Integer n) {
System.out.println("Score: " + (n * 2));
}
}Casting with Interfaces
An object can be cast to any interface it implements, allowing you to use it in contexts that require that interface.
interface Printable { void print(); }
interface Saveable { void save(); }
class Report implements Printable, Saveable {
public void print() { System.out.println("Printing report"); }
public void save() { System.out.println("Saving report"); }
}
Object obj = new Report();
if (obj instanceof Printable p) p.print();
if (obj instanceof Saveable s) s.save();Casting with Arrays
Array types form their own hierarchy. A String[] is a subtype of Object[]. Casting arrays follows the same rules as objects.
String[] names = {"Alice", "Bob"};
Object[] objs = names; // upcast — implicit
objs[0] = "Charlie"; // OK — still a String
try {
objs[0] = 42; // ArrayStoreException at runtime!
} catch (ArrayStoreException e) {
System.out.println("Cannot store Integer in String[]");
}
// Downcast back
String[] restored = (String[]) objs;E-Commerce Example: Payment Dispatch
A real-world example: dispatching to the right payment processor based on the runtime type of the payment.
interface Payment { double amount(); }
record CreditCard(String last4, double amount) implements Payment {}
record CryptoPayment(String wallet, double amount) implements Payment {}
record BankWire(String iban, double amount) implements Payment {}
static void process(Payment p) {
switch (p) {
case CreditCard cc -> System.out.println("Charging card *" + cc.last4());
case CryptoPayment cp -> System.out.println("Sending to wallet " + cp.wallet());
case BankWire bw -> System.out.println("Wiring to IBAN " + bw.iban());
}
}
process(new CreditCard("4242", 99.99));
process(new CryptoPayment("0xABCD", 0.05));Casting to Number for Generic Math
The Number superclass lets you perform generic numeric operations on any number type by upcasting to Number and calling doubleValue().
import java.util.List;
List<Number> numbers = List.of(1, 2.5, 3L, 4.0f);
double sum = 0;
for (Number n : numbers) {
sum += n.doubleValue(); // works for int, double, long, float
}
System.out.printf("Sum: %.1f%n", sum); // 10.5Safe Cast Utility Method
A reusable utility method that returns an empty Optional instead of throwing on bad casts — great for pipeline-style code.
import java.util.Optional;
public static <T> Optional<T> safeCast(Object obj, Class<T> clazz) {
return clazz.isInstance(obj)
? Optional.of(clazz.cast(obj))
: Optional.empty();
}
// Usage
Object val = "hello";
safeCast(val, String.class)
.ifPresent(s -> System.out.println(s.toUpperCase())); // HELLO
safeCast(val, Integer.class)
.ifPresentOrElse(
n -> System.out.println(n),
() -> System.out.println("Not an Integer") // prints this
);Common Mistakes to Avoid
Watch out for these common casting mistakes:
- Forgetting to cast before division:
int/intalways gives an integer - Downcasting without instanceof check → ClassCastException
- Confusing upcasting (safe) with downcasting (risky)
- Casting wrapper types:
(int) longValvslongVal.intValue()
// Mistake 1: integer division
double avg = 7 / 2; // 3.0 — WRONG
double fixed = 7.0 / 2; // 3.5 — correct
// Mistake 2: unwrapping Long as int
Long bigId = 1234567890123L;
// int id = (int) bigId; // compiles but truncates!
long id = bigId; // correct
System.out.println(avg); // 3.0
System.out.println(fixed); // 3.5
System.out.println(id); // 1234567890123Quick Check
What is the output of this code?
int a = 7; int b = 2; double result = (double) a / b; System.out.println(result);
Recap: Type Casting in Practice
Key takeaways:
- Upcast (subtype → supertype) is implicit and always safe
- Downcast (supertype → subtype) requires an explicit cast; use instanceof first
- Pattern matching instanceof combines check and cast in one expression
- Cast numerator to double before dividing to avoid integer truncation
- Use switch pattern matching for clean type-based dispatch
- Build safeCast utilities to work with Optional instead of exceptions
Frequently asked questions
Is the “Type Casting in Practice” lesson free?
Yes — the full text of “Type Casting in Practice” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Type Casting in Practice”?
Apply type casting in real-world scenarios including numeric calculations and OOP hierarchies. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Type Casting in Practice” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Primitive vs Reference Types
- Widening and Narrowing Conversions
- The instanceof Operator
- Type Casting in Practice