← Chapter 2 — Core Syntax & Data

9. Type Casting

mixed

Description

Type casting converts a value from one type to another. Widening conversions, such as int to double, are safe and happen automatically.

Narrowing conversions, such as double to int, need an explicit cast because information can be lost. Check whether that loss is acceptable before casting.

Subtopics

Widening

Description

A smaller numeric type can become a larger compatible type.

Explanation

No explicit cast is needed because the destination can represent the original value.

Example

double average = 87;

Narrowing

Description

A larger numeric type can be forced into a smaller type.

Explanation

The fractional part is removed when casting double to int.

Example

int wholeScore = (int) 87.9;

Explanation

Casting does not round a decimal value. If you need rounding, use Math.round and understand that it returns a long for a double argument.

Example

public class CastingDemo {
    public static void main(String[] args) {
        double score = 87.9;
        int displayedScore = (int) score;
        System.out.println(displayedScore);
    }
}

Key points

  • Widening is usually automatic.
  • Narrowing requires an explicit cast.
  • Casting double to int removes decimals.

Open reference