Chapter 2b - Typecasting
Typecastingβ
Casting
We can sort of do something similar in Java, but with Variable Types
| Images extracted from P Akthy and machinemfg
π Explicit & Implicit?
- Explicit: stated clearly and in detail, leaving no room for confusion or doubt.
- Implicit: implied though not plainly expressed.
Example Implicit Typecastingβ
public class Main {
public static void main(String args[]) {
int x = 10; // integer x
// x is implicitly converted to float
float z =x + 1.0f;
System.out.println("x = " + x );
System.out.println("z = 'x+1.0f'(x=10) = " + z );
}
}
Output
x = 10
z = 'x+1.0f'(x=10) = 11.0
π§ͺ Try the code out!
Example Explicit Typecastingβ
public class Main {
public static void main(String args[]) {
double d=1.6;
int val=(int)d; //casting from double to int
System.out.println("val = "+val );
}
}
Output
val = 1
π§ͺ Try the code out!
πββοΈ Analysis
- Why do you think that the code prints
1instead of1.6?
Typecasting might lead to loss of precision
In Implicit conversions, one data type is automatically converted into another if found compatible, but it should be in the right order else it may lead to loss of precision.
char->short-> int->float->double->long
Potential Errors When Typecastingβ
Avoiding Errors: This will throw you an errorβ
public class Main {
public static void main(String args[]) {
int val=(int)2.4 - 2.1;
System.out.println("val = " +val);
}
}

π§ͺ Try the code out! - This will throw an error
Do this insteadβ
public class Main {
public static void main(String args[]) {
int val=(int)(2.4 - 2.1);
System.out.println("val = " +val);
}
}
π§ͺ Try the code out!
Try it: explicit castingβ
Typecasting
1 / 2int x = (int) 9.9; What is x?
int x = (int) 9.9;
Pick an answer to see if you are right.
Chapter summaryβ
Key takeaways
- Implicit casting happens automatically when no data can be lost (
intβdouble). Explicit casting β(type) valueβ is required when data could be lost (doubleβint). - Casting a
doubletointtruncates toward zero; it does not round. - Wrap an expression in parentheses before casting it (
(int)(2.4 - 2.1)), otherwise the cast only applies to the first value, not the whole expression. - The safe widening order is
char β short β int β float β double β long; going the other way risks losing precision or overflowing.
Exercisesβ
Activity: Round vs truncate
Read a double. Print two lines: the truncated int value ((int)), then the rounded value using Math.round.