Understanding Type Casting in Java


Use casting carefully to avoid unexpected precision loss or overflow.

Source Code

// Widening casting
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

// Narrowing casting
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myInt); // Outputs 9
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments