Course contentsShow
← Java
Lesson 79 of 2,8702. Variables and Primitive TypesFree lesson

Explicit Cast Syntax: (type) expression

Master the syntax for explicit type casting using parentheses to force narrowing conversions.

Explicit Cast Syntax: (type) expression

What You'll Learn

You'll learn the exact syntax for forcing Java to perform a narrowing conversion when the compiler won't do it automatically.

The Cast Syntax

When you need to convert from a larger type to a smaller one (a narrowing conversion), Java requires you to explicitly tell it "I know what I'm doing." You do this by placing the target type in parentheses directly before the value or expression you want to convert.

The syntax looks like this:

(targetType) expression

How It Works

Think of the cast operator as a filter or funnel. You're saying, "Take this value and squeeze it through the targetType shape, even if some information might be lost."

Here are concrete examples:

long bigNumber = 1000L;
int smallerNumber = (int) bigNumber;  // Explicit cast required

double decimal = 9.75;
int wholeNumber = (int) decimal;  // Explicit cast, loses .75

float price = 19.99f;
int dollars = (int) price;  // Explicit cast, result is 19

Without the (int) cast in these examples, you'd get compilation errors because the conversions are narrowing—they risk data loss.

Cast in Expressions

You can cast entire expressions, not just variables:

int result = (int) (10.5 + 3.7);  // Casts the sum to int

The parentheses around the expression ensure the addition happens first, then the cast applies to the result.

Why the Syntax Matters

The cast operator has high precedence, so placement matters. Always put the type in parentheses, and use additional parentheses around complex expressions to ensure correct order of operations.

Key Takeaway: Use (targetType) directly before a value or expression to explicitly force a narrowing conversion, acknowledging potential data loss.