CKTIS / Java
Type cast: (type)
The (type) operator explicitly converts a value to a specified type. Numeric casts can lose data, and reference casts can throw ClassCastException; they do not change an object's class.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
(type) expressionThe expression (type) expression explicitly requests a permitted conversion. Replace type with the target type, such as (int) value. The result is a value; casting alone does not modify the source variable. Conversions forbidden by the language rules cause a compile-time error.
Narrowing numeric conversions can lose data. (int) -7.9 produces -7: the fractional part is discarded toward zero, not rounded to the nearest integer. Narrowing an integer retains the lowest-order bits, so (byte) 130 produces -126. Numbers cannot be cast to boolean or vice versa.
A reference cast neither creates a new object nor changes its class. (String) text succeeds when text refers to a String; an incompatible reference can cause ClassCastException. Casting null to a reference type produces null.
Placement matters: (double) (5 / 2) produces 2.0, whereas (double) 5 / 2 produces 2.5 because conversion happens before division.
Examples
public class CastDemo {
public static void main(String[] args) {
double value = -7.9;
int truncated = (int) value;
int count = 130;
byte narrowed = (byte) count;
Object text = "Java";
String word = (String) text;
System.out.println(truncated);
System.out.println(narrowed);
System.out.println(word);
}
}Result
-7 -126 Java
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.