Tsallaka zuwa abun ciki
Justice Tech School

Type Casting

Widening (small to large type) happens automatically. Narrowing needs an explicit cast in parentheses and can lose data. Use Integer.parseInt and Double.parseDouble to read numbers from text, and String.valueOf to go the other way.

Example
int a = 9;
double b = a;
double c = 9.78;
int d = (int) c;
System.out.println(b);
System.out.println(d);
int n = Integer.parseInt("42") + 1;
System.out.println(n);
System.out.println(String.valueOf(3.5) + "!");

Result

9.0
9
43
3.5!

Exercise

Convert text to an int.

int n = Integer.("12");

Quiz Test

What does (int) 9.78 give?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.