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!


Try it: explicit casting​

Quiz

Typecasting

1 / 2

int 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
  1. 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).
  2. Casting a double to int truncates toward zero; it does not round.
  3. 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.
  4. 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.