Skip to content

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.

Beginner 12 min read·Lesson 6 of 39 in Java Programming

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

Java
double d = 42; // widening: 42.0
int n = (int) 3.99; // narrowing: 3
long r = Math.round(3.5); // rounding: 4
int parsed = Integer.parseInt("123");
String text = String.valueOf(3.14);
char next = (char) ('a' + 1); // 'b'
  • Casts bind tightly: (double) a / b casts 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

Java
public class Casts {
public static void main(String[] args) {
int i = 7;
double d = i; // widening
System.out.println(d);
double price = 99.99;
int whole = (int) price; // narrowing truncates
System.out.println(whole);
System.out.println(Math.round(price));
System.out.println((byte) 200);
System.out.println((int) -2.7);
}
}
Output
7.0
99
100
-56
-2

Characters are numbers

Java
public class Chars {
public static void main(String[] args) {
char c = 'A';
System.out.println((int) c);
System.out.println(c + 1);
System.out.println((char) (c + 1));
char digit = '7';
System.out.println(digit - '0');
}
}
Output
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

Java
public class Parse {
public static void main(String[] args) {
int total = 457, subjects = 5;
System.out.println("wrong: " + total / subjects);
System.out.println("right: " + (double) total / subjects);
System.out.printf("rounded: %.1f%n", (double) total / subjects);
String[] inputs = {"42", " 17 ", "3.5", "abc"};
for (String s : inputs) {
try {
int value = Integer.parseInt(s.trim());
System.out.println("'" + s + "' -> " + value);
} catch (NumberFormatException e) {
System.out.println("'" + s + "' is not a whole number");
}
}
System.out.println(Double.parseDouble("3.5") * 2);
}
}
Output
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 / subjects divides two ints, so the fraction is lost (91).
  • (double) total / subjects casts total first, so the division is done in double (91.4).
  • %.1f formats the double with one decimal place.
  • s.trim() removes surrounding spaces before parsing, so " 17 " succeeds.
  • Integer.parseInt rejects "3.5" and "abc" with a NumberFormatException, which the catch block reports instead of crashing.

Expected output

Running “Averages and safe parsing” prints exactly:

TextOutput
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

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

double avg = (double) (total / count);

Prefer

double avg = (double) total / count;

The parentheses make the int division happen first; casting its truncated result can't bring the fraction back.

Assuming casts round

Avoid

int marks = (int) 89.9; // expecting 90

Prefer

long marks = Math.round(89.9); // 90

Casting truncates toward zero. Use Math.round when you want the nearest whole number.

Important notes

  • Integer.valueOf("42") returns an Integer object while parseInt returns a primitive int.
  • 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

  1. 1
    Read a temperature in Fahrenheit as a string, parse it and print Celsius rounded to one decimal.
  2. 2
    Print 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?
Practise this topic