This content originally appeared on DEV Community and was authored by haytam_7
When it comes to converting a string of numbers, like: "1234" into a number the first question that jumps to your mind is:
"They look like a number! why do I need to convert a number to a number?!"
Well, the computer doesn't see things the way we see them, a string consists of numbers is not a number! or at least according to the computer.
A string of numbers is a bunch of characters and they do not present a numeric value.
So in Java we have two ways to convert a string of 'numbers' to a real number, and here is how this could be done:
In this post I'm going to talk about converting string to int
Using Integer.parseInt()
This method will return the primitive numeric value of a string that contains only numbers, otherwise it will throw an error (NumberFormatException)
For example:
String testStr = "150";
try{
System.out.println(Integer.parseInt(testStr));
} catch (NumberFormatException e) {
System.out.print("Error: String doesn't contain a valid integer. " + e.getMessage());
}
Using Integer.valueOf()
This method will return an integer object of the passed parameter,
if the passed parameter isn't valid it will throw an error.
For example:
String testStr = "200";
try{
System.out.println(Integer.valueOf(testStr));
} catch (NumberFormatException e) {
System.out.print("Error: String doesn't contain a valid integer. " + e.getMessage());
}
This content originally appeared on DEV Community and was authored by haytam_7
haytam_7 | Sciencx (2021-09-29T19:21:50+00:00) Java: Convert String to a Number. Retrieved from https://www.scien.cx/2021/09/29/java-convert-string-to-a-number/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.