Text to numbers and back
Java converts a value to a bigger type automatically (widening) because nothing can be lost, but makes you write a cast like (int) to convert to a smaller type (narrowing), because digits or bits may be thrown away. Knowing exactly what a cast keeps and drops, and when Java promotes types inside expressions, explains most 'lossy conversion' errors and many silent bugs.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Compute the average of the ints 7, 8 and 10 as a double and print it rounded to the nearest whole number as an int.
Print what (byte), (short) and (char) casts do to the int 65601.
Convert the String "1250" to a number, add 10% using integer arithmetic only, and print the result as a String with " rupees" appended.
Explain it without notes
What is the difference between widening and narrowing, and why does only one need a cast?
Why does byte c = a + b; fail when a and b are both byte?
Explain the result of (byte) 200 step by step.
Why does double avg = sum / count; give a whole number when sum and count are ints, and how do you fix it?
Expected output
43
7.5
9000000
43!
255
11111111