Friday, 15 July 2016

5 great ways of converting String to Int in Java

How to convert String to Int in Java

Converting a String to Int in Java is a common scenario which we face everyday.
Now this can be achieved in multiple ways.

Integer.parseInt()
Integer.parseInt() returns a primitive int datatype.

String num = "12345";
int number = 0;

try {  
number = Integer.parseInt(num);   
} 
catch (NumberFormatException e) {
}


Integer.valueOf()
The Integer.valueOf() method returns an cached instance of java.lang.Integer.

String num = "12345";
Integer number = 0;
try {
      number = Integer.valueOf(num);
    } 
catch (NumberFormatException e) {
}


Integer.decode()
This basically decodes a String into an Integer.It returns a wrapper object of type java.lang.Integer.
It accepts Strings in the formats like DecimalNumeral, HexDigits, and OctalDigits.
DecimalNumeral, HexDigits, and OctalDigits are as defined in section 3.10.1 of The Java™ Language
Specification, except that underscores are not accepted between digits.

String num = "12345";
Integer number = 0;
try {
      number = Integer.decode(num);
    } 
catch (NumberFormatException e) {
}


Integer.decode() for Octal numbers

String num = "022";
Integer number = 0;
try {
      number = Integer.decode(num); //18
    } 
catch (NumberFormatException e) {
}


Integer.decode() for Hexadecimal numbers

String num = "0X12A";
Integer number = 0;
try {
      number = Integer.decode(num); //298
    } 
catch (NumberFormatException e) {
}