int to String Conversion Example Java


We know earlier, parsing is the operation on strings to convert into data types. This parsing, we used in command-line arguments and User Password validation. Now we think the other way. Sometimes, it is required to convert data types to string; exactly opposite of parsing. For this purpose, the String class comes with valueOf() static method. valueOf() is overloaded to take any data type as parameter and converts into string; it converts even objects into strings. Here, int to String is converted.

The following program does the job of converting int to String.

public class IntToString
{
  public static void main(String args[])
  {
    int i1 = 10;
    String str = String.valueOf(i1);
    System.out.println("int i1 in string form is " + str);
  }
}


int to String
Output screen on int to String Example

The int i1 is passed as parameter to valueOf() method. This method converts int i1 to string form. Anywhere i1 is required as string, str can be used. For example, to display anything thing in TextField, it must be in string form. Now str can be displayed in TextField as follows.

t1.setText(str);

where t1 is an object of TextField.

A string can also be converted to byte, short, int, long, float, double, char and boolean.

Note: The other way, string to int can be done in Java.

4 thoughts on “int to String Conversion Example Java”

    1. One good example is TextField in Java. If you retrieve a value from TextField with getText() method, it returns a string always. An integer value you entered in the TextField like marks, it comes in string form. For arithmetic operations, you need to convert into int value. Similarly, to display an int value in the TextField, it is required to convert int to string as setText() method takes string value as parameter.

      Another example, is command-line arguments are taken as string array values and is required to convert in data types.

Leave a Comment

Your email address will not be published.