Variables and Data Types · Lesson 6 of 42
Type Casting and Conversion
Because every Java variable has a fixed type, you often need to convert values: an int into a double for an average, a double into an int for a page count, or text typed by a user into a number. Java does some conversions automatically and asks you to be explicit about the risky ones.
In this lesson
- Widening (automatic) and narrowing (explicit) casts
- Type promotion inside expressions
- Converting between strings and numbers
- Casting pitfalls that appear in interviews
Widening: small to large, automatic
When the target type can hold every value of the source type, Java converts automatically. Nothing can be lost.
Widening order (automatic)
- byte8-bit
- short / char16-bit
- int32-bit
- long64-bit
- float → doubledecimals
public class Main {
public static void main(String[] args) {
int marks = 450;
long big = marks; // int → long
double avg = marks; // int → double
char grade = 'B';
int code = grade; // char → int
System.out.println(big + " " + avg + " " + code);
}
}
450 450.0 66
Narrowing: large to small, explicit
When information could be lost, Java refuses to convert unless you write a cast: the target type in brackets. You are telling the compiler "I know, do it anyway".
public class Main {
public static void main(String[] args) {
double price = 99.99;
int rupees = (int) price; // decimal part is cut off
System.out.println(rupees);
System.out.println((int) -7.9); // truncates towards zero
System.out.println(Math.round(99.99)); // rounds instead
long big = 3_000_000_000L;
int wrapped = (int) big; // too big for int
System.out.println(wrapped);
int n = 300;
byte b = (byte) n; // keeps only the low 8 bits
System.out.println(b);
}
}
99 -7 100 -1294967296 44
Common mistake: expecting a cast to round
(int) 9.99 is 9, not 10. Casting a decimal to an integer type truncates. Use Math.round(), Math.ceil() or Math.floor() when you mean rounding.
Type promotion in expressions
In arithmetic, Java first promotes byte, short and char to int, and then converts both operands to the larger type. This explains two common surprises:
public class Main {
public static void main(String[] args) {
int total = 7, count = 2;
System.out.println(total / count); // int / int → int
System.out.println((double) total / count); // cast first → double division
System.out.println((double) (total / count)); // too late: 3 → 3.0
byte a = 10, b = 20;
// byte c = a + b; → error: a + b is an int
byte c = (byte) (a + b);
System.out.println(c);
a += 5; // compound assignment casts automatically
System.out.println(a);
}
}
3 3.5 3.0 30 15
Interview angle
"Why does byte c = a + b; fail but a += b; compile?" Because a + b is promoted to int, while compound operators like += include an implicit cast back to the variable's type.
Strings ↔ numbers
Text from users, files and web requests always arrives as a String. Convert it with the wrapper classes:
public class Main {
public static void main(String[] args) {
int qty = Integer.parseInt("12");
double rate = Double.parseDouble("49.50");
long id = Long.parseLong("9876543210");
boolean flag = Boolean.parseBoolean("TRUE");
System.out.println(qty * rate + " " + id + " " + flag);
String s1 = String.valueOf(qty); // number → String
String s2 = "" + rate; // quick but less clear
String s3 = Integer.toString(255, 16); // hex text
System.out.println(s1 + "|" + s2 + "|" + s3);
}
}
594.0 9876543210 true 12|49.5|ff
If the text is not a valid number, parseInt throws NumberFormatException:
public class Main {
public static void main(String[] args) {
try {
int n = Integer.parseInt("12a");
System.out.println(n);
} catch (NumberFormatException e) {
System.out.println("Not a number: " + e.getMessage());
}
}
}
Not a number: For input string: "12a"
char ↔ int ↔ String
public class Main {
public static void main(String[] args) {
char digit = '7';
int value = digit - '0'; // '7' → 7
int alsoValue = Character.getNumericValue(digit);
char back = (char) ('0' + 4); // 4 → '4'
String text = Character.toString('J');
System.out.println(value + " " + alsoValue + " " + back + " " + text);
}
}
7 7 4 J
digit - '0' is a classic trick in coding interviews for converting digit characters in a string to numbers.
Practice
Try it yourself
Calculate the exact average of the int marks 78, 85 and 90.
Show solution
public class Main { public static void main(String[] args) { int a = 78, b = 85, c = 90; double avg = (a + b + c) / 3.0; System.out.printf("%.2f%n", avg); } }84.33
Add up the digits of the string "40927".
Show solution
public class Main { public static void main(String[] args) { String s = "40927"; int sum = 0; for (char ch : s.toCharArray()) { sum += ch - '0'; } System.out.println(sum); } }22
Quick check
What is (int) 3.99?
3 – narrowing truncates.
What is 5 / 2 * 2.0?
4.0: 5 / 2 is int division (2), then 2 * 2.0 = 4.0.
Which exception does Integer.parseInt("abc") throw?
NumberFormatException.
Summary
- Widening is automatic and safe; narrowing needs a cast and may lose data.
- Arithmetic promotes small types to
int; cast before dividing to get decimals. - Use
Integer.parseInt,Double.parseDoubleandString.valueOfto convert text.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.