java int to str

Converting a primitive int , or its respective wrapper class Integer , to a String is a common and simple operation. The same goes for the other way around, converting a String to Integer.

Converting Integer to String

When converting an int or Integer to a String, there are four approaches. The String class provides a couple of methods — valueOf() and format() for this purpose, though the already mentioned Integer class also offers a toString() method that takes care of this problem. Additionally, you could also rely on StringBuilder ‘s append() method, though this isn’t a commonly used scenario:

  • String.valueOf(int i) — This approach is considered best practice due to simplicity. This method accepts other types as well — boolean , char , char[] , double , float , long , Object
  • Integer.toString(int i) — This approach is older than valueOf() and simply utilizes the method every Java object has to return a String representing the given int. This approach, unlike the previous, can return a NullPointerException though.
  • String.format(String format, Object. args) — Returns a String formatted according to the format specifier and the following arguments
  • StringBuilder.append(int i).toString() — Same as the valueOf() method, this method accepts all primitive types with the addition of some other types like String , StringBuffer and CharSequence .

String.valueOf()

The valueOf() method is the static method of String class that returns the String representation of the specified type.

There are many types allowed here:

But we’ll be focusing on int for this tutorial. The representation returned exactly matches the representation returned by Integer.toString() when passing the same argument:

Running this piece of code will yield:

This makes sense since both of these methods return a new String. The equals() method returns true, because their value is the same, whereas == returns false since their reference variables don’t point to the same object in memory.

Using valueOf() keeps your code consistent across conversion of one data type to another. In the case of an Integer, the valueOf() method is also able to cache frequently used numbers e.g. from -127 to 128, in order to speed up the conversion and reduce memory.

Because of this, it’s encouraged to use the valueOf() method for both String and Integer conversion.

Integer.toString()

This approach utilizes one of the most common Java methods — toString() shared amongst all objects.

The method has many usages and warrants a detailed explanation. If you’d like to read more about it, we’ve got a great article already covering it!

In this case, the method returns a String object representing the specified int. The argument is converted to signed decimal representation and returned as a String:

Running this piece of code will yield:

If your variable is of primitive type (int), it is better to use Integer.toString(int) or String.valueOf(int) . But if your variable is already an instance of Integer (wrapper class of the primitive type int), it is better to just invoke its toString() method as shown above.

String.format()

Returns a String formatted according to the format specifier and the following arguments. While the purpose of this method isn’t exactly to convert, but rather format a String, it can also be used for conversion.

There are quite a few specifiers to choose from:

  • %a — Hex output of a floating point number
  • %b — true if not null, false if null
  • %c — Unicode character
  • %d — Decimal Integer
  • %e — Scientific notation of a decimal Integer
  • %f — Decimal floating point number
  • %g — Same as above, but possibly scientific, depending on the value
  • %h — Hex String of hashCode() return value
  • %n — Line separator
  • %o — Octal Integer
  • %s — String
  • %t — Date/Time conversion
  • %x — Hex String

We’ll be focusing on %d for this tutorial:

Running this piece of code will yield:

The format() method throws an IllegalFormatConversionException if you pass an incompatible type e.g. passing Integer for specifier %s , which expects a String object.

Some of the most common specifiers are %s for String, %d for decimal integer and %n .

StringBuilder and StringBuffer

Both StringBuffer and StringBuilder are classes used to concatenate multiple values into a single String.

StringBuffer is thread safe but slower, whereas StringBuilder isn’t thread safe but is faster.

Running this piece of code will yield:

Conclusion

We’ve covered one of the fundamental topics of Java and common problem developers face — Converting an int or Integer to a String using tools shipped with the JDK.

Which would be the «best» way to convert this to a string:

I have tried searching (googling) for an answer but no many seemed «trustworthy».

7 Answers 7

There are multiple ways:

  • String.valueOf(number) (my preference)
  • «» + number (I don’t know how the compiler handles it, perhaps it is as efficient as the above)
  • Integer.toString(number)

Integer class has static method toString() — you can use it:

Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.

in Java Tutorials Comments Off on Convert String To int Java – Tutorial & Examples

How to Convert String to int in Java – The following article will let you know the complete information about string to int java, in case if you have any doubts do let me know.

We have different ways to convert a String to int in Java

  • Integer.parseInt()
  • Integer.valueOf()
  • Integer.parseUnsignedInt()

Our own logic equivalent to – Integer.parseInt()

String To Int Java

Integer.parseInt() – How It Works:

Syntax1 – int parseInt(String);

It converts the given String into an integer. Suppose we give a String “234” as argument to the method, then it returns the integer 234. As this is a static method, we can invoke this using its class name.

Example:

Algorithm for converting string to int without built-in method:

Implementation:

Output:

Integer.decode() – How It Works

An empty String or a String that contains non-digits will result in Number Format Exception.

Ex:

“234A”, “34.54”, “smile”, “”, etc.

Syntax2: int parseInt(String,int);

This is similar to normal parseInt(), but it takes an integer as second argument and this argument represents the radix of the content in the input String.

Suppose we want to convert an octal number (which is in String format) into its equivalent decimal integer then the second argument should be 8.

Similarly, if we want a hexa-decimal String to its decimal number then the second argument should be 16.

Eg: Integer.parseInt(“234”,10); will result in 234

Implementation:

Example:

Integer.parseInt(“234”,2); will result in NumberFormatException as allowed digits in binary(2) number system are 0 and 1 only.

Integer.parseInt(“789”,8); will result in NumberFormatException as allowed digits in octal(8) number system are from 0 to 7 only

string to int java – Integer.valueOf()

It can also be used similar to Integer.parseInt() to convert a String to int. This method also has an overloaded method to take an int (radix) as second argument where as the first argument is a String.

Integer.parseInt() returns the result as a basic (primitive) int type where as Integer.valueOf() returns the result an Integer object.

  • Integer.valueOf(“234”); will give 234 as Integer object
  • Integer.valueOf(“412”); will give 412 as Integer object
  • Integer.valueOf(“234”,8); will give 156 as Integer object
  • Integer.valueOf(“234”,16); will give 564 as Integer object

Integer.parseUnsignedInt()

This is also similar to Integer.valueOf() and Integer.parseInt() but it can work on positive values only.

  • Integer.parseUnsignedInt(“874”); returns 874
  • Integer.parseUnsignedInt(“+874”); returns 874
  • Integer.parseUnsignedInt(“-874”); raises NumberFormatException

Algorithm:

Syntax: Integer decode(String);

This method converts the given string into an int and returns an Integer object.

Оцените статью