Skip to main content

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 of 1.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!