How to cast between types

Use widening conversion

Java automatically converts a narrower numeric type to a compatible wider type.

int count = 12;
double measurement = count;
System.out.println(measurement); // 12.0

Use an explicit cast

A narrowing conversion needs a cast and can discard a fractional part or overflow the destination range.

double price = 19.95;
int whole = (int) price;
System.out.println(whole); // 19

Parse text

Parsing converts numeric text to a number and throws NumberFormatException when the format is invalid.

int age = Integer.parseInt("21");
double cost = Double.parseDouble("9.95");

Convert values to text

Use String.valueOf for explicit conversion. Concatenation also converts values when one operand is a string.

String scoreText = String.valueOf(95);
String label = "Score: " + 95;