How to convert a String to an int in Java?
Hello everyone! I just started learning Java and ran into a problem. I have a string that contains a number, for example "123". I need to perform arithmetic operations with this number, but I get a compilation error.
Here is my code:
```java
String numberStr = "123";
int result = numberStr + 10; // Error: cannot convert String to int
```
I understand that a string and a number are different data types. But how do I convert the string "123" into the integer 123 so I can work with it later? I tried writing `int number = (int) numberStr;`, but that doesn't work either, the compiler complains about type casting.
I've seen that some people use `Integer.parseInt()`, but I don't quite understand how it works and what to do if the string turns out to be not a number, for example "abc". Will the program crash with an error?
No answers yet.
Log in to leave an answer