Convert String to numeric data type in Java

Beknazar
2 min readMay 4, 2021
Converting String to numeric values

To convert String data type to numeric data type we can use wrapper classes of numeric primitives.

public class Main {
public static void main(String[] args) {
String strNum = "12";
int num = Integer.parseInt(strNum);
System.out.println(num); // 12
}
}

We convert similarly for other numeric data types by using their wrapper class versions.

public class Main {
public static void main(String[] args) {
String strNum = "12av";
// NumberFormatException here
int num = Integer.parseInt(strNum);
System.out.println(num);
}
}

If we try to convert a string that is not a number(the content of the string is not a number), we will get NumberFormatException which is a runtime exception.

Converting numeric data type into String data type is quite easy.

public class Main {
public static void main(String[] args) {
int num = 10;
String str = "" + num;
}
}

The String is a special class and everything that concatenates with string will become a string. So the easiest way is to just concatenate.

public class Main {
public static void main(String[] args) {
int num = 10;
String str = String.valueOf(num);
}
}

Another way is using valueOf method of String to convert numeric data to String.

--

--