What type conversion is
Every value in Java has a type, and the compiler enforces it. An int holds a whole number, a double holds a number with a fractional part, and a String holds text. The text "42" and the number 42 are different things, and you can't use one where the other is expected.
Type conversion changes a value from one type into another. You need it whenever data arrives in one form and the code needs another: a number you want to join into a message, or digits that were read as text and now have to be added together.
The four conversions in this lesson
| Goal | Code |
|---|---|
number to String | String.valueOf(x) |
String to int | Integer.parseInt(s) |
String to double | Double.parseDouble(s) |
double to int | (int) x |
Number to String with String.valueOf
int score = 42;
String scoreStr = String.valueOf(score);
System.out.println(scoreStr + 1); // 421
System.out.println(score + 1); // 43
Once the value is a String, + means concatenation, so scoreStr + 1 glues the characters "1" on the end and gives 421. The original int is unchanged. String.valueOf also accepts a double or a boolean: String.valueOf(2.50) gives "2.5".
String to number with parseInt and parseDouble
String count = "100";
int countInt = Integer.parseInt(count);
double ratio = Double.parseDouble("3.14");
System.out.println(countInt + 1); // 101
System.out.println(ratio + 1); // 4.140000000000001
The second line of output looks odd because a double stores binary approximations of decimal fractions. It is normal and not a bug in the conversion.
Parsing is strict. Integer.parseInt("abc") throws a NumberFormatException with the message For input string: "abc". So do "3.5" (use Double.parseDouble for that) and " 42", which has a leading space. A sign is allowed: Integer.parseInt("-17") is -17, and leading zeros are fine, so "007" parses as 7.
double to int with a cast
double weight = 70.8;
int weightInt = (int) weight;
System.out.println(weightInt); // 70
A cast is a type name in parentheses in front of a value. Casting a double to int throws the fractional part away. It does not round: 70.8 becomes 70, not 71. For negative numbers it still cuts toward zero, so (int) -2.7 is -2. If you want rounding, use Math.round, which returns a long for a double argument: Math.round(9.99) is 10.
Why the direction matters
Text and numbers behave differently with the same operator. Suppose three numbers arrive as the text "10 20 30" and you split it into the pieces "10", "20" and "30":
String[] parts = "10 20 30".split(" ");
int total = 0;
for (String p : parts) total += Integer.parseInt(p);
System.out.println(total); // 60
String joined = "";
for (String p : parts) joined += p;
System.out.println(joined); // 102030
With parseInt, the loop adds numbers and gets 60. Without it, += on strings concatenates and gets 102030. Choosing the right type decides which of the two you get.
The lesson's exercise
The starting code declares three variables:
int age = 25;
double price = 9.99;
String year = "2024";
Each new variable is a conversion of one of them.
- Convert
ageto text. Declare aStringnamedageStrand set it withString.valueOf(age). It holds"25". - Cast
priceto an integer. Declare anintnamedpriceIntand set it to(int) price. The result is9, because the cast drops.99instead of rounding up. - Parse
year. Declare anintnamedyearIntand set it withInteger.parseInt(year). It holds the number2024.
The complete solution is:
int age = 25;
double price = 9.99;
String year = "2024";
String ageStr = String.valueOf(age);
int priceInt = (int) price;
int yearInt = Integer.parseInt(year);
Each variable is declared with the type it ends up with. The right-hand side calls the conversion, and the original variables stay as they were.
Gotchas
- Java won't convert narrowing types for you.
int priceInt = price;is a compile error, because adoublemay lose information. The cast(int) priceis how you say you accept that. - Widening is automatic.
double d = age;compiles and gives25.0, because everyintfits in adouble. - Casting a large value wraps or clamps. A
longthat doesn't fit wraps around:(int) 3_000_000_000Lis-1294967296. Adoublethat is too big clamps to the maximum:(int) 1e10is2147483647. - Integer division happens before a cast on the result.
7 / 2is3. Writing(double) 7 / 2casts the 7 first and gives3.5, but(double) (7 / 2)converts the already truncated3to3.0. - Characters are numbers too.
(int) 'A'is65, and(char) 66isB.
Key takeaways
- Use
String.valueOfto turn a number into text. - Use
Integer.parseIntandDouble.parseDoubleto turn text into numbers. They throwNumberFormatExceptionon input that isn't a valid number. - Use
(int)to turn adoubleinto anint. It truncates toward zero and never rounds. - Each conversion produces a new value; the source variable is not changed.