Java – Convert int to String and vice versa

Overview

This document describes different ways to convert different number data types to String and vice versa.

Integer to String (Integer –> String)

Primitive type int can be converted to String using either of following methods – 

 String str = String.valueOf(7);
 String str = Integer.toString(7);
 String str = ""+i;

 

Integer object can be directly converted to String using toString() method

 Integer integer = 7; integer.toString();

 

Integer to String uring radix

Integers can be converted to String in other number systems as well. In Integer.toString() method, an optional second parameter can be added as radix. 

Below example shows integer to String from decimal to octal number system. 

 int i = 12; String str = Integer.toString(i, 8);

Output: String containing “14” 

 

Below example shows integer to String containing hexa decimal number

 int i = 25; String str = Integer.toString(i, 16);

Output: String containing “19”

 

String to Integer (String –> Integer)

String containing integer values can be converted to int datatype using either of following methods –

 String str = "5"; int i = Integer.valueOf(str);

 

In case invalid string is passed to valueOf method to convert to int, it throws 

 String str = "5gs"; int i = Integer.valueOf(str);

Output: Exception in thread “main” java.lang.NumberFormatException: For input string: “5gs”
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

 

String to Integer using radix

Radix can be used while converting back from String to integer as well. As in one of the above examples where integer present in decimal was converted to String containing octal or hexadecimal number, we can do reverse while converting from String containing number in octal or hexadecimal to decimal.

In below example, string containing “12” is converted to integer using radix 8. It means “12” in octal (redix 8) is converted to integer containing decimal equivalent.

 String str = "14"; int i = Integer.valueOf(str, 8);

  Output: 12

 

Similarly in below example String containing “19” is converted to integer using radix 16. It means “16” in hexadecimal (redix 16) is converted to integer containing decimal equivalent. 

 String str = "19"; int i = Integer.valueOf(str, 16);

Output: 25

{jcomments on}


Leave a Reply

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