How to Convert Integers to Strings in Java

One confusing fact that faces many new programmers in Java -- or most other languages, for that matter -- is that the computer stores literal integers and the English text of those integers in different ways to save memory. It is up to the programmer to remember which form a given piece of data is in and to handle conversions between the two types when necessary. Thankfully, the "Integer" class helps with the job.

Instructions

    • 1

      Open your Java Integrated Development Environment.

    • 2

      Paste the following into your Java IDE to create an integer:

      int i = 123;

      This defines an integer as a number. While the integer is stored as a number, math can be performed upon it. But if you try to send the integer into a method that expects a String, you will get an error. To give a trivial example, the following command will not work:

      String s = new String(i);

    • 3

      Paste the following on the text line to convert the integer to a String:

      String s = Integer.toString(i);

      As you see, the primitive data type "int" is moved into its object-based version "Integer." Since "Integer" is actually a Java class, it provides a variety of useful methods, including the ubiquitous "toString" method.

Tips & Warnings

  • You aren't restricted to the ordinary base-10 numerals when using Integer's "toString" method. "toString" has an optional second argument that allows you to specify the radix, or the base, for the resulting String. For example, if you want the binary (base-2) form of an integer, type:

  • String s = Integer.toString(i, 2);

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured