All for Joomla All for Webmasters

Java int to String

We can convert int to String in java using String.valueOf() and Integer.toString() methods.

Scenario

It is generally used if we have to display number in textfield because everything is displayed as a string in form.


1) String.valueOf()

The String.valueOf() method converts int to String. The valueOf() is the static method of String class. The signature of valueOf() method is given below:

  1. public static String valueOf(int i)

Java int to String Example using String.valueOf()

Let’s see the simple code to convert int to String in java.

  1. int i=10;
  2. String s=String.valueOf(i);//Now it will return “10”

Let’s see the simple example of converting String to int in java.

  1. public class IntToStringExample1{
  2. public static void main(String args[]){
  3. int i=200;
  4. String s=String.valueOf(i);
  5. System.out.println(i+100);//300 because + is binary plus operator
  6. System.out.println(s+100);//200100 because + is string concatenation operator
  7. }}

Output:

300
200100

2) Integer.toString()

The Integer.toString() method converts int to String. The toString() is the static method of Integer class. The signature of toString() method is given below:

  1. public static String toString(int i)

Java int to String Example using Integer.toString()

Let’s see the simple code to convert int to String in java using Integer.toString() method.

  1. int i=10;
  2. String s=Integer.toString(i);//Now it will return “10”

Let’s see the simple example of converting String to int in java.

  1. public class IntToStringExample2{
  2. public static void main(String args[]){
  3. int i=200;
  4. String s=Integer.toString(i);
  5. System.out.println(i+100);//300 because + is binary plus operator
  6. System.out.println(s+100);//200100 because + is string concatenation operator
  7. }}

Output:

300
200100
PinIt
submit to reddit

Leave a Reply

Top