How to convert or parse a number String to Integer in Java

919
Mar 24, 2016

There are multiple ways to convert a number string to equivalent Integer value in Java. Below are the ways to get it done.

All of following methods will create integer from string.

Method 1:

new Integer("12345");


Method 2:

Integer.parseInt("12345");


Method 3:

Integer.valueOf("12345");


Question: If all above can convert string to integer then which method should is choose ?

Answer: This depends on the requirement.

If you want a Integer object from string, then you may use Method 1 or Method 3. These two methods returns Integer object. But if you want a primitive int value then Method 2 is best choice. Method 2 return primitive int, so this will save boxing of int to Integer.



comments powered by Disqus

© Copyright 2017