Type Conversion
Programs often receive a value in one type and need it in another. Parsing converts text to a number, while casting requests a numeric conversion that Java will not perform implicitly.
Integer.parseInt validates and converts decimal text. The cast (int) narrows a double to an int by discarding the fractional part.
Two direct conversions
public class Main {
public static void main(String[] args) {
String ticketText = "12";
int tickets = Integer.parseInt(ticketText);
double rating = 4.8;
int wholeRating = (int) rating;
System.out.println("Tickets: " + tickets);
System.out.println("Whole rating: " + wholeRating);
}
}
Output:
Tickets: 12
Whole rating: 4
The text "12" becomes the integer 12. The cast turns 4.8 into 4 by discarding its fractional part.
A narrowing cast can lose information. It truncates rather than rounds, so use it only when dropping the fractional part makes sense.
Cast a decimal distance to a whole number.