How To Convert String To Int (Integer) In Java? – POFTUT

How To Convert String To Int (Integer) In Java?

Java programming language provides different variable type. One of the most used types are String and Int or integer. During the usage of these variable types we may need to convert them. In this tutorial we will examine string to int and int to string variables types conversion in Java programming language.

Convert with parseInt() Function

parseInt() is a function which can be used to convert string to int. parseInt() is provided by Integer class which is mainly created to parse and convert different variable types into Integer . In this  example we will create a string type variable named age and then convert to the integer.

parseInt() will return a primitive int value which is not an object.

Convert with valueOf() Function

There is alternative way and function to convert string to int which is named valueOf(). valueOf() function is provided by Integer class and can be used like parseInt() function. In this  example we will create a string type variable named age and then convert to the integer.

valueOf() function will return Integer Object which is more complex then primitive integer value.

Convert with decode() Function

Intger class also provides the decode() function. decode() function can be used like other functions where we will provide the string variable to the static decode() function.

LEARN MORE  Linux Bash Shell Printf Command Examples

Convert with toInt() Function

Another alternative for String to Int conversion is toInt() function .toInt() function is provided by NumberUtils class. We will just provide the string variable or value like below.

Catch Convert Exceptions

During the convert operation of string to int we may get exceptions about conversion. If provided string variable contain non numeric values like letter, punctuation etc. the given functions parseInt() and valueOf() will throw exception about the convert operation. In this example we will get NumberFormatException because given string provides letter like B.

Valid and Invalid Conversions

There are different possibilities during string to int convert. Here some of them which are valid and convert to int and some of them invalid which will not convert into int and throw exception. We will use parseInt() function but given string values will throw same error for other string to int conversion functions like decode() , valueOf() , parseInt() .

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)