Java Reference
In-Depth Information
You want to have the ability to convert any numeric values that are stored as strings in-
to integers.
Solution #1
Use the Integer.valueOf() helper method to convert strings to int data types.
For example:
String one = "1";
String two = "2";
int result = Integer.valueOf(one) + Integer.valueOf(two);
As you can see, both of the string variables are converted into integer values. After
that, they are used to perform an addition calculation and then stored into an int .
Note A technique known as autoboxing is used in this example. Autoboxing is a fea-
ture of the Java language that automates the process of converting primitive values to
their appropriate wrapper classes. For instance, this occurs when you assign an int
value to an Integer. Similarly, unboxing automatically occurs when you try to convert in
the opposite direction, from a wrapper class to a primitive. For more information on
autoboxing, refer to the online documentation at http://docs.oracle.com/
javase/tutorial/java/data/autoboxing.html .
Solution #2
Use the Integer.parseInt() helper method to convert strings to int data types.
For example:
String one = "1";
String two = "2";
int result = Integer.parseInt(one)
+ Integer.parseInt(two);
System.out.println(result);
How It Works
Search WWH ::




Custom Search