2. Number and String Conversion Functions
Converting Strings to Numbers
Because we cannot cast from strings to numbers, we must use these functions:
public class MyProgram { public static void main(String[] args) { int a = Integer.parseInt("1"); //converts "1" to 1 double b = Double.parseDouble("3.14"); //converts "3.14" to 3.14 //There is also: //Byte.parseByte //Short.parseShort //Long.parseLong //Float.parseFloat //Boolean.parseBoolean //we will learn the charAt method for getting individual char types } }
Note that these functions will throw errors if the string cannot be parsed. For example, Integer.parseInt("Hello") will throw a NumberFormatException .
Converting non-decimal Strings to Numbers
The parseInt and similar functions also can take two inputs ("arguments","parameters"). The second input is the base or "radix". For example, we can use this to parse numbers in binary, octal, hex, or any other base:
public class MyProgram { public static void main(String[] args) { //These are all 42: System.out.println(Integer.parseInt("101010", 2)); System.out.println(Integer.parseInt("52", 8)); System.out.println(Integer.parseInt("2A", 16)); System.out.println(Integer.parseInt("33", 13)); } }
Converting from Numbers to Strings in a certain base:
We will learn later that you can concatenate strings with numbers, so that "x"+123 becomes "x123", and ""+123 becomes "123". However, there are also toString functions that take a number and an optional base ("radix"):
public class MyProgram { public static void main(String[] args) { System.out.println(Integer.toString(42, 2)); //101010 System.out.println(Integer.toString(42, 8)); //52 System.out.println(Integer.toString(42, 13)); //33 System.out.println(Integer.toString(42, 16)); //2A String a = Double.toString(42.0); //42.0 String b = Float.toString(42.0f); //42.0 System.out.println(a); System.out.println(b); System.out.println(Integer.toString(6*9, 13)); //6*9 is 42 in base 13 } }