View RSS Feed

Java String

Converting Strings to Numbers

Rate this Entry
by , 04-26-2012 at 06:32 PM (380 Views)
In a string object, usually a program would be ending up with numeric data, a value which user will enter. For example:
Primitive numeric types (Short, Integer, Byte, Double, Long and Float) are being wrapped by the Number subclasses. A class method known as valueOf is provided by each which makes a string to be converted into object of that type. For example, ValueOfDemo will be getting 2 strings to convert them into no. and then performing the arithmetic operations at values.

Java Code:
public class ValueOfDemo {
    public static void main(String[] args) {

        // this program requires two 
        // arguments on the command line 
        if (args.length == 2) {
            // convert strings to numbers
            float a = (Float.valueOf(args[0])).floatValue(); 
            float b = (Float.valueOf(args[1])).floatValue();

            // do some arithmetic
            System.out.println("a + b = " +
                               (a + b));
            System.out.println("a - b = " +
                               (a - b));
            System.out.println("a * b = " +
                               (a * b));
            System.out.println("a / b = " +
                               (a / b));
            System.out.println("a % b = " +
                               (a % b));
        } else {
            System.out.println("This program " +
                "requires two command-line arguments.");
        }
    }
}

Submit "Converting Strings to Numbers" to Facebook Submit "Converting Strings to Numbers" to Digg Submit "Converting Strings to Numbers" to del.icio.us Submit "Converting Strings to Numbers" to StumbleUpon Submit "Converting Strings to Numbers" to Google

Categories
String

Comments