String to Integer and Integer to String conversion in Java

In this Java tutorial, we are going to learn how to convert string to integer and integer to string using pre-defined functions in Java. So in the same tutorial post we will see how to convert string to integer and ineger to string in Java easily with some easy examples.

Convert Integer to String in Java

1.) Converting using Integer.toString(int)

   Syntax :- Integer.toString(value);

where argument value is converted and returned as a string instance. If the number is negative sign will be preserved.

To know some more ways to convert an integer to string in Java click this post – convert Integer to String in Java various methods

        Java code to convert Integer to String

  class Codespeedy

{
   public static void main ( String args[] )
    
     {
        int a=12;
        
        int b=-12;

                String s1 = Integer.toString(a);
                
                String s2 = Integer.toString(b);

            System.out.println("String s1=" +s1);
            
            System.out.println("String s2=" +s2);
     }
}

Output

String s1=12;

String s2=-12;

2.) Converting using String.valueof(int)

Java code to convert integer to string

class Codespeedy
 
 { 
    public static void main ( String args[] )
           
      {
              int a=1234;

               String s = String.valueof(a);

                   System.out.println("String s2=" +s2);
            
       }
 }

Output

String s2=1234

Convert String to Integer in Java using parseInt()

While operating upon strings, there are times when we need to convert a number represented as a string into an integer type.

Syntax :- parseInt( string s ) throws NumberFormatException

                 parseInt( string s , int radix ) throws NumberFormatException

NumberFormatException is thrown by this method if :-

  • String is null or of zero length.
  • Value represented by string is not a value of type int.
  • The second argument radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.

  Java code to convert string to integer

class codespeedy

{
   public static void main ( String[] args )
    
{
      int result1 = Integer.parseInt("1001");

        int result2 = Integer.parseInt("20",16);

           System.out.println(result1);

            System.out.println(result2);
     }
}

Output

1001
32

Similarly, we can use

parseLong() :- parse the string to Long.

parseDouble() :- parse the string to Double.

You may also learn,

Leave a Reply

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