← Java from Scratch
Lesson 7 of 88 · 10 XP
Type casting
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Widening happens automatically: byte → short → char → int → long → float → double.
int a = 7;
double d = a; // 7.0
Narrowing is done by hand, with the type in parentheses, and data can be lost:
double price = 9.99;
int whole = (int) price; // 9 — the fractional part is DROPPED
System.out.println(7 / 2); // 3 — both are ints
System.out.println((double) 7 / 2); // 3.5
System.out.println((char) 65); // A
System.out.println((int) 'A'); // 65
System.out.println((byte) 200); // -56 — the extra bits are cut off
Strings are turned into numbers not by casting but with methods: Integer.parseInt("42"), Double.parseDouble("3.5");
the other way — String.valueOf(42) or "" + 42.
Task. Read two integers a and b. Print on three lines: the integer quotient, the exact quotient
and the letter with the code a + b ((char)).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.