Java for Beginners, Lesson 9: Type Conversion and Casting

Java for Beginners · Module 2: Building Blocks


🎯 Why Do Types Need Converting?

Pouring water from a small glass into a big jug always works. Pouring a big jug into a small glass may spill. Java treats numbers the same way. Moving a value into a bigger type is safe, so Java does it for you. Moving it into a smaller type can lose data, so Java makes you say so with a cast.

📌 Type conversion changes a value from one data type to another. Widening is automatic. Narrowing needs an explicit cast written as (type).

1️⃣ Widening: Automatic and Safe

byte
➜
short
➜
int
➜
long
➜
float
➜
double
char
➜joins at int
Widening (left to right) is automatic and safe. Narrowing (right to left) needs a cast, because data may be lost.

Figure 1: The widening path of numeric types.

Program 1: Widening in action

public class WideningDemo {
    public static void main(String[] args) {
        byte b = 25;
        int i = b;           // byte to int: automatic
        long l = i;          // int to long: automatic
        float f = l;         // long to float: automatic
        double d = f;        // float to double: automatic

        System.out.println("byte   : " + b);
        System.out.println("int    : " + i);
        System.out.println("long   : " + l);
        System.out.println("float  : " + f);
        System.out.println("double : " + d);

        char c = 'A';
        int code = c;        // char to int
        System.out.println("char 'A' as int: " + code);
    }
}
🖥️ Output:
byte : 25
int : 25
long : 25
float : 25.0
double : 25.0
char ‘A’ as int: 65
  • No cast is written, and nothing is lost. Each value simply moves into a bigger box.
  • When the value reaches float, it prints as 25.0, because floats always show a decimal point.
  • A char widens to its numeric code: ‘A’ becomes 65.

2️⃣ Narrowing: You Must Cast

Widening (implicit)Narrowing (explicit)
Directionsmall type ➜ big typebig type ➜ small type
Cast needed?No, Java does it for youYes: write (type) in front
Data loss?No (except tiny precision loss for long ➜ float)Possible: fraction cut off, or value wraps
Exampledouble d = 5;int n = (int) 5.9;

Figure 2: Implicit and explicit conversion compared.

99.99
double
(int) ➜
99
int: fraction cut off, not rounded
-2.7
(int) ➜
-2
cut towards zero

Figure 3: Casting a decimal to int truncates the fraction.

Program 2: Casting down

public class NarrowingDemo {
    public static void main(String[] args) {
        double price = 99.99;
        int rupees = (int) price;            // fraction is cut off, not rounded
        System.out.println("(int) 99.99      = " + rupees);
        System.out.println("(int) -2.7       = " + (int) -2.7);
        System.out.println("Math.round(99.99) = " + Math.round(price));

        int big = 130;
        byte small = (byte) big;             // 130 does not fit in a byte
        System.out.println("(byte) 130       = " + small);

        long huge = 3_000_000_000L;
        int shrunk = (int) huge;
        System.out.println("(int) 3000000000L = " + shrunk);

        int code = 66;
        System.out.println("(char) 66        = " + (char) code);
    }
}
🖥️ Output:
(int) 99.99 = 99
(int) -2.7 = -2
Math.round(99.99) = 100
(byte) 130 = -126
(int) 3000000000L = -1294967296
(char) 66 = B
  • (int) 99.99 gives 99. The fraction is cut off, not rounded. For negative numbers it moves towards zero, so -2.7 becomes -2.
  • To round properly, use Math.round(99.99), which gives 100.
  • 130 is outside the byte range (-128 to 127), so it wraps around to -126. A cast never warns you about this.
  • 3,000,000,000 does not fit in an int, so the cast keeps only the lower 32 bits and gives a surprising negative number.
  • Casting a number to char gives the character with that code: 66 is ‘B’.

3️⃣ Division: The Most Common Casting Trap

When both numbers are int, Java does integer division and drops the remainder. To get a decimal answer, make at least one operand a double before dividing.

ExpressionTypesResultWhy
7 / 2int ÷ int3integer division drops the remainder
7 / 2.0int ÷ double ➜ double3.57 is widened to 7.0 first
(double) 7 / 2double ÷ int ➜ double3.5cast applies to 7, then division
(double) (7 / 2)cast after division3.07 / 2 is already 3 when cast happens

Figure 4: Where you place the cast matters.

public class DivisionDemo {
    public static void main(String[] args) {
        int a = 7, b = 2;
        System.out.println("7 / 2          = " + (a / b));
        System.out.println("7 / 2.0        = " + (a / 2.0));
        System.out.println("(double) 7 / 2 = " + ((double) a / b));
        System.out.println("(double) (7 / 2) = " + (double) (a / b));
        System.out.println("7 % 2          = " + (a % b));
    }
}
🖥️ Output:
7 / 2 = 3
7 / 2.0 = 3.5
(double) 7 / 2 = 3.5
(double) (7 / 2) = 3.0
7 % 2 = 1
  • The cast (double) a binds tighter than /, so it converts a first and then divides.
  • (double) (a / b) divides first (giving 3) and casts afterwards, so it is too late: the answer is 3.0.
  • % gives the remainder: 7 = 3 × 2 + 1.

Program 3: Average of marks, with and without a cast

public class AverageMarks {
    public static void main(String[] args) {
        int total = 431;
        int subjects = 5;

        double wrong = total / subjects;
        double right = (double) total / subjects;

        System.out.println("Without cast: " + wrong);
        System.out.println("With cast   : " + right);
        System.out.printf("Rounded     : %.2f%n", right);
    }
}
🖥️ Output:
Without cast: 86.0
With cast : 86.2
Rounded : 86.20
  • Even though wrong is a double, the division 431 / 5 is done in integers first and gives 86, which is then stored as 86.0.
  • With the cast, the division is done in decimals and gives the true average 86.2.

4️⃣ Type Promotion Inside Expressions

Rule: operands in an expressionResult type
byte, short or char with anythingat least int
int with longlong
int or long with floatfloat
anything with doubledouble
Java picks the widest type in the expression. This is called type promotion.

Figure 5: Type promotion inside expressions.

Program 4: Promotion rules

public class PromotionDemo {
    public static void main(String[] args) {
        byte x = 10, y = 20;
        int sum = x + y;                    // byte + byte becomes int
        byte small = (byte) (x + y);        // cast needed to store back in a byte
        System.out.println("byte + byte = " + sum + " and " + small);

        char letter = 'A';
        System.out.println("'A' + 1      = " + (letter + 1));
        letter += 1;                        // compound assignment casts for you
        System.out.println("letter += 1  = " + letter);

        int count = 3;
        double rate = 2.5;
        System.out.println("int * double = " + (count * rate));

        long big = 10L;
        float small2 = 2.5f;
        System.out.println("long + float = " + (big + small2));
    }
}
🖥️ Output:
byte + byte = 30 and 30
‘A’ + 1 = 66
letter += 1 = B
int * double = 7.5
long + float = 12.5
  • Adding two byte values gives an int, so storing it back into a byte needs a cast.
  • 'A' + 1 is the number 66, not a character. But letter += 1 keeps the type char, because compound assignment operators (+=, -= and so on) include a hidden cast.
  • int * double becomes double, and long + float becomes float.

5️⃣ Converting To and From Strings

Text and numbers are different types. Use Integer.parseInt and Double.parseDouble to turn text into numbers, and String.valueOf to turn a number into text.

ExpressionStep 1Step 2Result
"5" + 3 + 2“5” + 3 = “53”“53” + 2 = “532”532
5 + 3 + "2"5 + 3 = 88 + “2” = “82”82
+ works left to right. Once a String appears, every later + joins text.

Figure 6: Why the order of + and text matters.

public class StringConversion {
    public static void main(String[] args) {
        String text = "123";
        int number = Integer.parseInt(text);
        double decimal = Double.parseDouble("45.5");
        System.out.println("parseInt    : " + (number + 1));
        System.out.println("parseDouble : " + (decimal * 2));

        String back = String.valueOf(99);
        System.out.println("valueOf     : " + back + "!");

        System.out.println("\"5\" + 3     = " + ("5" + 3));
        System.out.println("5 + 3       = " + (5 + 3));
        System.out.println("\"5\" + 3 + 2 = " + ("5" + 3 + 2));
        System.out.println("5 + 3 + \"2\" = " + (5 + 3 + "2"));
    }
}
🖥️ Output:
parseInt : 124
parseDouble : 91.0
valueOf : 99!
“5” + 3 = 53
5 + 3 = 8
“5” + 3 + 2 = 532
5 + 3 + “2” = 82
  • "123" is text, so text + 1 would be “1231”. After parseInt it is the number 123, and adding 1 gives 124.
  • "5" + 3 joins text and gives “53”. 5 + 3 adds numbers and gives 8.
  • + works left to right: in 5 + 3 + "2" the numbers are added first (8), then joined to the text.

6️⃣ Errors You Will Meet

byte + byte stored in a byte

public class Lossy1 {
    public static void main(String[] args) {
        byte a = 10, b = 20;
        byte c = a + b;
        System.out.println(c);
    }
}
🖥️ Compiler message:
Lossy1.java:4: error: incompatible types: possible lossy conversion from int to byte
byte c = a + b;
^
1 error
  • Fix: byte c = (byte) (a + b); or store the result in an int.

A decimal stored in an int

public class Lossy2 {
    public static void main(String[] args) {
        int rupees = 99.99;
        System.out.println(rupees);
    }
}
🖥️ Compiler message:
Lossy2.java:3: error: incompatible types: possible lossy conversion from double to int
int rupees = 99.99;
^
1 error
  • Fix: int rupees = (int) 99.99; if you really want to drop the fraction.

Converting text that is not a number

public class BadParse {
    public static void main(String[] args) {
        int n = Integer.parseInt("abc");
        System.out.println(n);
    }
}
🖥️ Runtime error:
Exception in thread “main” java.lang.NumberFormatException: For input string: “abc”
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at BadParse.main(BadParse.java:3)
  • This compiles fine but fails while running. The last line shows where in your program it happened (BadParse.java:3). Lesson 28 shows how to handle such errors.

⚠️ Common Mistakes

MistakeProblemFix
double avg = total / count; (both int)Integer division happens first(double) total / count
Casting after dividingFraction is already lostCast one operand before dividing
Expecting (int) 2.9 to be 3Cast truncatesUse Math.round(2.9)
byte c = a + b;The sum is an intCast or use int
Writing "5" + 3 expecting 8Text joining, not additionConvert with parseInt first
Casting large values to smaller typesSilent wrap-aroundCheck the range first

❓ Frequently Asked Questions

Q1. Is casting the same as converting?
Casting is the way you ask for a conversion yourself. Java also converts automatically (widening) without a cast.

Q2. Can I cast a boolean to int?
No. boolean cannot be cast to any number type in Java.

Q3. Does a cast change the original variable?
No. (int) price creates a new value. The variable price still holds 99.99.

Q4. Why can long go to float automatically although it may lose digits?
Float has a bigger range than long, so Java allows it, but precision (about 7 digits) can be lost.

✅ Key Takeaways

  • Widening (small ➜ big) is automatic and safe.
  • Narrowing (big ➜ small) needs an explicit cast, such as (int) 5.9, and may lose data.
  • Casting a decimal to int cuts the fraction; use Math.round to round.
  • In int / int the result is an int. Cast one operand to double before dividing.
  • Expressions are promoted to the widest type involved, and at least int.
  • Use parseInt, parseDouble and String.valueOf to convert between text and numbers.
🎓 Practice questions: (1) What is the value of (int) 7.9 and Math.round(7.9)? (2) Why does double d = 10 / 4; store 2.0? How would you get 2.5? (3) What does "1" + 2 + 3 print, and what does 1 + 2 + "3" print? (4) Write a program that reads two integers as text, converts them with parseInt and prints their sum. (5) Explain why byte c = a + b; fails even when a and b are small.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision