Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Type conversions in Java

Type conversions in Java: Java performs implicit widening conversions, while primitive narrowing and reference casts require explicit syntax; boxing connects a primitive with its wrapper.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

type conversion

Java performs implicit widening conversions, while primitive narrowing and reference casts require explicit syntax; boxing connects a primitive with its wrapper.

Use Integer.parseInt for text, check numeric ranges before narrowing, and use pattern instanceof before operating on an uncertain reference type.

Casting int to byte discards high bits without an exception, a bad reference cast throws ClassCastException, and unboxing null throws NullPointerException.

A long-to-float widening conversion can still lose precision, NaN has special comparison rules, and autoboxing can hide allocation and overload selection.

Widening yields widened=130, narrowing gives narrowed=-126, boxing/unboxing gives unboxed=130, parsing gives parsed=42, and the bad cast prints bad-cast=true.

Examples

public class Main {
  public static void main(String[] args) {
    int value=130; long widened=value; byte narrowed=(byte)value;
    Object boxed=value; int unboxed=(Integer)boxed;
    System.out.println("widened="+widened); System.out.println("narrowed="+narrowed);
    System.out.println("unboxed="+unboxed); System.out.println("parsed="+Integer.parseInt("42"));
    try { String ignored=(String)boxed; } catch(ClassCastException ex) { System.out.println("bad-cast=true"); }
  }
}

Result

widened=130
narrowed=-126
unboxed=130
parsed=42
bad-cast=true

Widening yields widened=130, narrowing gives narrowed=-126, boxing/unboxing gives unboxed=130, parsing gives parsed=42, and the bad cast prints bad-cast=true.

Sources