On this page (10 sections)
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.
1️⃣ Widening: Automatic and Safe
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);
}
}
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
charwidens to its numeric code: ‘A’ becomes 65.
2️⃣ Narrowing: You Must Cast
| Widening (implicit) | Narrowing (explicit) | |
| Direction | small type ➜ big type | big type ➜ small type |
| Cast needed? | No, Java does it for you | Yes: write (type) in front |
| Data loss? | No (except tiny precision loss for long ➜ float) | Possible: fraction cut off, or value wraps |
| Example | double d = 5; | int n = (int) 5.9; |
Figure 2: Implicit and explicit conversion compared.
99.99double
99int: fraction cut off, not rounded
-2.7-2cut 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);
}
}
(int) 99.99 = 99
(int) -2.7 = -2
Math.round(99.99) = 100
(byte) 130 = -126
(int) 3000000000L = -1294967296
(char) 66 = B
(int) 99.99gives 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
chargives 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.
| Expression | Types | Result | Why |
7 / 2 | int ÷ int | 3 | integer division drops the remainder |
7 / 2.0 | int ÷ double ➜ double | 3.5 | 7 is widened to 7.0 first |
(double) 7 / 2 | double ÷ int ➜ double | 3.5 | cast applies to 7, then division |
(double) (7 / 2) | cast after division | 3.0 | 7 / 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));
}
}
7 / 2 = 3
7 / 2.0 = 3.5
(double) 7 / 2 = 3.5
(double) (7 / 2) = 3.0
7 % 2 = 1
- The cast
(double) abinds tighter than/, so it convertsafirst 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);
}
}
Without cast: 86.0
With cast : 86.2
Rounded : 86.20
- Even though
wrongis adouble, the division431 / 5is 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 expression | Result type |
| byte, short or char with anything | at least int |
| int with long | long |
| int or long with float | float |
| anything with double | double |
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));
}
}
byte + byte = 30 and 30
‘A’ + 1 = 66
letter += 1 = B
int * double = 7.5
long + float = 12.5
- Adding two
bytevalues gives anint, so storing it back into abyteneeds a cast. 'A' + 1is the number 66, not a character. Butletter += 1keeps the typechar, because compound assignment operators (+=,-=and so on) include a hidden cast.int * doublebecomesdouble, andlong + floatbecomesfloat.
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.
| Expression | Step 1 | Step 2 | Result |
"5" + 3 + 2 | “5” + 3 = “53” | “53” + 2 = “532” | 532 |
5 + 3 + "2" | 5 + 3 = 8 | 8 + “2” = “82” | 82 |
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"));
}
}
parseInt : 124
parseDouble : 91.0
valueOf : 99!
“5” + 3 = 53
5 + 3 = 8
“5” + 3 + 2 = 532
5 + 3 + “2” = 82
"123"is text, sotext + 1would be “1231”. AfterparseIntit is the number 123, and adding 1 gives 124."5" + 3joins text and gives “53”.5 + 3adds numbers and gives 8.+works left to right: in5 + 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);
}
}
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 anint.
A decimal stored in an int
public class Lossy2 {
public static void main(String[] args) {
int rupees = 99.99;
System.out.println(rupees);
}
}
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);
}
}
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
| Mistake | Problem | Fix |
|---|---|---|
double avg = total / count; (both int) | Integer division happens first | (double) total / count |
| Casting after dividing | Fraction is already lost | Cast one operand before dividing |
Expecting (int) 2.9 to be 3 | Cast truncates | Use Math.round(2.9) |
byte c = a + b; | The sum is an int | Cast or use int |
Writing "5" + 3 expecting 8 | Text joining, not addition | Convert with parseInt first |
| Casting large values to smaller types | Silent wrap-around | Check 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
intcuts the fraction; useMath.roundto round. - In
int / intthe result is an int. Cast one operand todoublebefore dividing. - Expressions are promoted to the widest type involved, and at least
int. - Use
parseInt,parseDoubleandString.valueOfto convert between text and numbers.
🎓 Practice questions: (1) What is the value of(int) 7.9andMath.round(7.9)? (2) Why doesdouble d = 10 / 4;store 2.0? How would you get 2.5? (3) What does"1" + 2 + 3print, and what does1 + 2 + "3"print? (4) Write a program that reads two integers as text, converts them withparseIntand prints their sum. (5) Explain whybyte c = a + b;fails even when a and b are small.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java