Module 2 · Java Basics — topic 3 of 5
Type Conversion and Casting
Widening and narrowing conversions, explicit casts, numeric promotion in expressions, and converting between strings and numbers.
Learning objectives
- Distinguish widening from narrowing conversions
- Predict the results of casts that truncate or overflow
- Convert strings to numbers and back
Definition
Type conversion changes a value from one type to another. Widening conversions (e.g. int to long) happen automatically because no information is lost; narrowing conversions (e.g. double to int) require an explicit cast because they may lose information.
Introduction
Values often need to move between types: an average must be computed as a double from int totals, a price read from the keyboard arrives as text, and a character code needs to become a letter. Java does safe conversions for you and makes you ask explicitly for risky ones.
Why it matters
Silent truncation is a classic bug — (int) 2.99 is 2, not 3.
Every program that reads user input or files must convert text to numbers and handle bad input.
Detailed explanation
Widening (automatic). byte → short → int → long → float → double, and char → int. The compiler inserts these whenever a smaller type is used where a larger one is expected. (long → float or double may lose precision for very large values, but never magnitude.)
Narrowing (explicit cast). Going the other way needs a cast in parentheses: int n = (int) 9.99; gives 9 — the fraction is truncated toward zero, not rounded. Casting an integer to a smaller integer keeps only the low bits: (byte) 200 is −56.
Numeric promotion. In an arithmetic expression, byte, short and char operands are promoted to int first, and if either operand is long, float or double, the other is promoted to match. That is why byte a = 1, b = 2; byte c = a + b; does not compile: a + b is an int.
Rounding. To round instead of truncate, use Math.round(x) (returns long for double), Math.floor, Math.ceil, or format with printf("%.2f").
Strings and numbers. Integer.parseInt("42"), Double.parseDouble("3.5") and Long.parseLong turn text into numbers and throw NumberFormatException for invalid text. In the other direction, String.valueOf(42), Integer.toString(42) or simply "" + 42 produce text.
char and int. A char is a number: (int) 'A' is 65 and (char) 66 is 'B'. 'a' + 1 is the int 98, so cast back to char if you want a letter.
Syntax
- Casts bind tightly:
(double) a / bcasts a, then divides. (int) (a / b)casts the result of an integer division — too late to keep the fraction.- parse methods throw NumberFormatException on bad input.
Code examples
Widening and narrowing
7.0 99 100 -56 -2
Characters are numbers
65 66 B 7
digit - '0' is the standard way to turn a digit character into its numeric value.
More examples
Averages and safe parsing
wrong: 91 right: 91.4 rounded: 91.4 '42' -> 42 ' 17 ' -> 17 '3.5' is not a whole number 'abc' is not a whole number 7.0
Step-by-step explanation
total / subjectsdivides two ints, so the fraction is lost (91).(double) total / subjectscaststotalfirst, so the division is done in double (91.4).%.1fformats the double with one decimal place.s.trim()removes surrounding spaces before parsing, so" 17 "succeeds.Integer.parseIntrejects "3.5" and "abc" with a NumberFormatException, which the catch block reports instead of crashing.
Expected output
Running “Averages and safe parsing” prints exactly:
Practical applications
- Computing averages and percentages from integer totals
- Parsing numbers from text files, forms and command-line arguments
- Rounding prices for display
- Converting between character codes and letters in ciphers and parsers
Best practices
- Cast one operand, not the result, when you need floating-point division.
- Validate or catch NumberFormatException whenever you parse user input.
- Use Math.round, floor or ceil to state your rounding intent explicitly.
Common mistakes
Casting after the integer division
Avoid
Prefer
The parentheses make the int division happen first; casting its truncated result can't bring the fraction back.
Assuming casts round
Avoid
Prefer
Casting truncates toward zero. Use Math.round when you want the nearest whole number.
Important notes
Integer.valueOf("42")returns anIntegerobject whileparseIntreturns a primitiveint.- Casting a double that is too large for int gives
Integer.MAX_VALUE, not wrap-around; casting NaN gives 0.
Key takeaways
- Widening is automatic; narrowing needs a cast and may lose information.
- byte, short and char are promoted to int in arithmetic.
- Use parseInt/parseDouble to read numbers from text and handle NumberFormatException.
Try it yourself
- 1Read a temperature in Fahrenheit as a string, parse it and print Celsius rounded to one decimal.
- 2Print the letters A to Z using a loop over int values cast to char.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
7 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat is printed?
- BeginnerWhat is printed?