+91 81900 98289

Java Casting

Widening happens on its own when no information is lost, such as storing an int in a double. Narrowing needs a cast, because a double may not fit in an int. The cast drops the fraction. It does not round.

Casting a reference does not convert an object into a different kind of object. It only tells the compiler which type you believe the reference already is. A wrong cast throws ClassCastException at run time.

Example

(int) 18.9 is 18, not 19. The int 18 stored in a double prints as 18.0.

public class Casts { public static void main(String[] args) { double score = 18.9; int whole = (int) score; double wide = 18; System.out.println(whole + " " + wide); } }
If you need the nearest whole number, use Math.round, then cast the long it returns. A bare (int) cast always truncates toward zero.