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