Java String to int, Java int to String With Examples

Today we will look at Java String to int conversion and then java int to String conversion. Java provides several ways to convert String to int and int to String.

Java String to int

  • Using Integer.parseInt method
  • Using Integer.valueOf method
  • Using above methods with different radix.

Java String to int example

Let’s write a simple java program to convert String to an int, note that String is an Object whereas int is a primitive data type. An integer can be written in Decimal, Hexadecimal, Octal Binary or any other nonstandard formats.

Java 7 one of the feature is Binary Literals. In this example, we will explore how to convert String to int using different radix values.

Output of the above program is:

  • Interegr.parseInt(String str) is the most commonly used method to convert String to int, if String represents int in decimal format. Internally, it invokes method Interegr.parseInt(String str, int radix) with radix value as 10.
  • By passing redix value as 2, we can convert Binary int representation String to int, same is true for other known formats Octal, Hexadecimal also.
  • Minimum radix value is 2 and maximum radix value is 36. For radix 36, it includes 0 to 9 and then A(10) to Z(36). The conversion from String to int is case insensitive.
  • Integer.valueOf(String str) is also a way to convert String to int. There is also an overloaded method where we can pass radix, as you can see from above example code.
  • If the String representation does not contain a parsable integer, both above methods throw NumberFormatException.
  • The String representation should only contain the value and not the radix prefix associated with int, like 0x, 0b etc.

Java int to String

  • Using + operator to concatenate int to string.
  • Using String.valueOf method.
  • Using String.format method

Java int to String example

Let’s write a simple program to convert java int to String object using different methods.

The output of the above program is:

  • +” operator is overloaded for String and it can be used to convert int to String. It also takes care of different formats like Hexadecimal, Octal, Binary and convert them to decimal format before returning the final String object.
  • String.valueOf(int i) can be used to convert int to String. valueOf() method is overloaded to accept float, long, double etc. Internally it uses Integer.toString(int i) method to return the String object.
  • String.format(String format, Object... args) is also another way to convert int to String object.
  • Before converting int to string, value is always converted to decimal format and then assigned to string. As you can see from the output above, all the string representations are in the decimal format.

That’s all for Java String to int and int to String conversion, we will cover more java interview questions in future posts.

Reference: Integer API Doc

By admin

Leave a Reply