Pages

Saturday 15 June 2013

String To Int and Int To String Conversion In Java

       HOW TO CONVERT STRING TO INTEGER AND INTEGER TO STRING IN JAVA

String to Integer Conversion in Java

1 ) By using Integer.parseInt( String str) method.

This is preferred way of converting it, extremely easy and most flexible way of converting String to Integer.

Example :
      // using Integer.parseInt()
      int i = Integer.parseInt("12345");
      System.out.println(i);

This method will throw NumberFormatException if string provided is not a proper number. Same technique can be used to convert data type like float and double to String in Java. Java API provides static methods like Float.parseFloat() and Double.parseDouble() to perform data type conversion.

2 ) Second way, using Integer.valueOf().

Example :
      //How to convert number string = "000000081" into Integer value = 81
      int i = Integer.valueOf("00000081");
      System.out.println(i);

It will ignore the leading zeros and convert the string into int. This method also throws NumberFormatException.

Integer to String Conversion

1 ) Int to String in java using "+" operator
It is a simplest way to convert. Just use "+" operator with int value.

Example
      String price = ""+123;

2 ) Use String.valueOf() method which is static method to convert any integer value to String. In fact String.valueOf(0 method is overloaded to accept almost all primitive type so you can use it convert char, double, float, or any other data type into String.

Example :
      String price = String.valueOf(123);

3 ) Using String.format()
This is a new way of converting an int primitive to String object and introduced in JDK 1.5 along-with several other important features like Enum, Generics and Variable arguments methods. String.format() is even more powerful and can be used in variety of way to format String in Java.

Example :
      String price = String.format("%d",123);

 

No comments:

Post a Comment