How to convert a Java string into a number (stringtonumber)

public class StringToNumber {
    public static void main(String[] args) {
        String str = "123";

        Integer num1 = new Integer(str);

        int num2 = Integer.parseInt(str);

        Integer num3 = Integer.valueOf(str);



if it’s a single character or a string you have to cut it and convert it to char and then convert it to char otherwise it will be null pointer exception

like above

String a = "ABC";


char[] b = a.toCharArray();


for (char c : b) {



principle analysis:

Interger class constructor

directly into the source code, look at this constructor:

  1. public Integer(String s) throws NumberFormatException {

  2. this.value = parseInt(s, 10);

  3. }

What is

this this.value?Continue tracing source:

 private final int value;

from this, we can find a characteristic of the packaging class:

inside the wrapper, the corresponding primitive data type of the wrapper class is treated as a private attribute, and the value of the primitive data type is wrapped externally into an object of the corresponding wrapper class.

in the constructor of an Integer, we find that the parseInt (String s) method is called, and we continue our tracing, which leads us to the second method demonstrated at the beginning of this article:

parseInt (String s) method

  1. public static int parseInt(String s) throws NumberFormatException {

  2. return parseInt(s,10);

  3. }

  4. // a: the first method of encapsulation,

  5. // a:

  6. public static int parseInt(String s, int radix)throws NumberFormatException

valueOf (String s) method

  1. public static Integer valueOf(String s) throws NumberFormatException {

  2. return Integer.valueOf(parseInt(s, 10));

  3. }

The last method,

, actually calls the parseInt() method (the second)

Read More: