Start learning free

LESSON 14 OF 344 · VARIABLES

Type Conversion in Java: valueOf, parseInt and Casts

Lesson Read the full explanation

In Java, every value has a type: int, double, String, and so on. Sometimes you need to convert a value from one type to another.

Common type conversion methods:

String.valueOf(x)       // converts int or double → String
Integer.parseInt(s)     // converts String → int
Double.parseDouble(s)   // converts String → double
(int) x                 // casts double → int (drops decimal)

Here are some examples:

int score = 42;
String scoreStr = String.valueOf(score);    // "42"

double weight = 70.8;
int weightInt = (int) weight;               // 70  (decimal dropped)

String count = "100";
int countInt = Integer.parseInt(count);     // 100

Note that casting a double to int with (int) simply drops the decimal - it does not round.


Assignment
Follow the Coding Tutorial and convert each variable to a different type!


Hint
Use String.valueOf(), (int) casting, and Integer.parseInt().

STEP 1 OF 3
    Ctrl + Enter to check

    JAVA · VARIABLES

    Type Conversion in Java, explained

    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

    GoalCode
    number to StringString.valueOf(x)
    String to intInteger.parseInt(s)
    String to doubleDouble.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.

    1. Convert age to text. Declare a String named ageStr and set it with String.valueOf(age). It holds "25".
    2. Cast price to an integer. Declare an int named priceInt and set it to (int) price. The result is 9, because the cast drops .99 instead of rounding up.
    3. Parse year. Declare an int named yearInt and set it with Integer.parseInt(year). It holds the number 2024.

    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 a double may lose information. The cast (int) price is how you say you accept that.
    • Widening is automatic. double d = age; compiles and gives 25.0, because every int fits in a double.
    • Casting a large value wraps or clamps. A long that doesn't fit wraps around: (int) 3_000_000_000L is -1294967296. A double that is too big clamps to the maximum: (int) 1e10 is 2147483647.
    • Integer division happens before a cast on the result. 7 / 2 is 3. Writing (double) 7 / 2 casts the 7 first and gives 3.5, but (double) (7 / 2) converts the already truncated 3 to 3.0.
    • Characters are numbers too. (int) 'A' is 65, and (char) 66 is B.

    Key takeaways

    • Use String.valueOf to turn a number into text.
    • Use Integer.parseInt and Double.parseDouble to turn text into numbers. They throw NumberFormatException on input that isn't a valid number.
    • Use (int) to turn a double into an int. It truncates toward zero and never rounds.
    • Each conversion produces a new value; the source variable is not changed.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free