Menu
Topics Index
...
`

Converting Strings to Number - Java Example Program


Converting Strings to Number
class StringstoNumberTest
{
    public static void main(String arg[])
    {
        String s1 = "25";
        int i1 = Integer.valueOf(s1); // LINE E
        int i2 = Integer.parseInt(s1); // LINE F
        System.out.println(i1 + " " + i2);
        
        float f1 = Float.valueOf(s1);
        float f2 = Float.parseFloat(s1);
        System.out.println(f1 + " " + f2);
        
        double d1 = Double.valueOf(s1);
        double d2 = Double.parseDouble(s1);
        System.out.println(d1 + " " + d2);
        
        System.out.print("The sum of all numbers is : ");
        System.out.println(i1 + i2 + f1 + f2 + d1 + d2); // LINE G
        
        String s2 = "ABCD";
        char c1[] = new char[s2.length()];
        for (int i = 0; i < s2.length(); i++) {
            c1[i] = Character.valueOf(s2.charAt(i)); // LINE H
        }
        for (int j = 0; j < c1.length; j++) {
            System.out.print(c1[j] + " ");
        }    
    }
}
OUTPUT

25 25
25.0 25.0
25.0 25.0
The sum of all numbers is : 150.0
A B C D

DESCRIPTION

In this program, at LINE E and LINE F, string s1 is converted into integer by using valueOf, parseInt methods respectively. Similarly float and double are converted from string s1. At LINE G all 6 numbers sum is printed. At LINE H the string s2 containing ABCD is converted into character array and all characters are displayed.

THINGS TO TRY
  • Try for the below code.
    double d = Double.parseDouble("10");
    System.out.println(d);
    The output should be 10.0, since we are using parseDouble and it is assigned to datatype double.
  • Try for the below code.
    int i = Integer.parseInt("1010", 2);
    System.out.println(i);
    The output will be 10, since here the paseInt method returns an integer value of the given string representation of binary radix.
    Try parseInt(String s , int radix) for decimal, Octal and Hexadecimal radices
.

© meritcampus 2019

All Rights Reserved.

Open In App