Careeroza
Converting Between Strings and Numbers
String to Number
Data from forms, files and APIs usually arrives as text. Use the wrapper class parse methods to convert.
Example
public class Main {
public static void main(String[] args) {
String qtyText = "3";
String priceText = "249.50";
int qty = Integer.parseInt(qtyText);
double price = Double.parseDouble(priceText);
boolean flag = Boolean.parseBoolean("true");
long phone = Long.parseLong("9876543210");
System.out.println(qty * price);
System.out.println(flag + " " + phone);
}
}Output
748.5 true 9876543210
Number to String
Example
public class Main {
public static void main(String[] args) {
int pin = 500081;
String a = String.valueOf(pin);
String b = Integer.toString(pin);
String c = "" + pin; // quick, works but less clear
System.out.println(a.length() + " digits");
System.out.println(b + c);
}
}Output
6 digits 500081500081
Invalid Input
Example
If the text is not a valid number, parseInt throws a NumberFormatException. You will learn to handle exceptions in the medium level.
public class Main {
public static void main(String[] args) {
String age = "twenty";
int value = Integer.parseInt(age);
System.out.println(value);
}
}Output
Exception: java.lang.NumberFormatException: For input string: "twenty"