Frequently, we have need to convert from a string type to a numeric type -- especially when collecting numeric input from the user through either the command line arguments or through a GUI (graphical user interface) object like the dialog boxes produced with the JOptionPane class.
For example, what if you want to write a java class called "SumFinder" that takes two integer arguments and outputs their sum.
The following, unfortunately will not give us what we seek:
public class SumFinder {
public static void main(String[] args) {
System.out.println(args[0] + args[1]); //<-- something bad happens here!
}
}
Instead, this is what the above produces:
$ java SumFinder 3 5 35
The problem is that the command-line arguments passed to the main method are always treated as strings. As such, when you try to add args[0]
and args[1]
together, java does what it always does when it sees a "+" between two strings -- it concatenates them together.
So what we really need to do is to first convert both arg[0]
and arg[1]
to numerical values (for example, two int
values) -- and only after that has happened, can we attempt to add them.
For some variable types, such a conversion can happen through a process called "casting" -- but unfortunately, strings can't be turned into numeric types by casting.
However, there are some classes that come to our aid in this circumstance. The "Integer" class, for example, comes with a static method called "parseInt" that can be used to translate a string into a variable of type "int". (We'll talk more about this later, but a "static" method is a method that belongs to the entire class, and not a specific object / instance of that class.)
Example
String myString = "1234"; int n = Integer.parseInt(myString); int m = 2 * n; Sytem.out.println(m); // prints 2468
Armed with this method, fixing "SumFinder" to add the two integer arguments it is given becomes easy:
public class SumFinder { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println(a + b); } }
What if we wanted "SumFinder" to work with decimal values you ask? Fear not -- the "Double" class (note the capital 'D', this is a different class than "double") also comes with a similar static method called "parseDouble" that can be used to translate a string representing some decimal value into a variable of type "double".
Example
String myString = "3.14"; double d1 = Double.parseDouble(myString); double d2 = d1 % 2; System.out.println(d2); // prints 1.14
Here's a "SumFinder" class that works with decimal values:
public class SumFinder { public static void main(String[] args) { double a = Double.parseDouble(args[0]); double b = Double.parseDouble(args[1]); System.out.println(a + b); } }