parseInt is the way to go. The Integer documentation says
Use parseInt(String) to convert a string to a int primitive, or use valueOf(String) to convert a string to an Integer object.
parseInt is likely to cover a lot of edge cases that you haven't considered with your own code. It has been well tested in production by a lot of users.
Hello, i have started learning java recently by mooc. But during this course, it uses Integer.valueOf while taking integer inputs, I use same way but whenever i do it intellij suggests me parseint(). And I wonder if it is better to use parseint?
Videos
parseInt is the way to go. The Integer documentation says
Use parseInt(String) to convert a string to a int primitive, or use valueOf(String) to convert a string to an Integer object.
parseInt is likely to cover a lot of edge cases that you haven't considered with your own code. It has been well tested in production by a lot of users.
I invite you to look at the source code of the parseInt function. Your naïve function is faster, but it also does way less. Edge cases, such as the number being to large to fit into an int or not even being a number at all, will produce undetectable bogus results with your simple function.
It is better to just trust that the language designers have done their job and have produced a reasonably fast implementation of parsing integers. Real optimization is probably elsewhere.