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);
}
}