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().
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
