Start learning free

LESSON 14 OF 671 · VARIABLES

Type Conversion in Java

Lesson

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