How to convert an int to String in Java? 4 Examples Tutorial

Hello guys, if you new to Java programming and wondering how to convert an int to a String object in Java then don't worry, you have come to the right place. Earlier, I have shown you how to convert an Integer to a String and in this article, I will show you how to convert an int variable to a String in Java. The difference between an Integer and an int is that the former is an object while an int variable is a primitive value. You can use the String.valueOf() or Integer.toString() method to convert an int value to a String object in Java. Remember, String is not just a char array but a full feature object in Java. 


The standard way to convert one object to String in Java is just calling the toString() method, but since here we need to convert primitive int to String, I prefer to use String.valueOf(int) method. It reads better because we are converting an int to String and not an Integer to String.

There is a difference between them, int is a primitive value while Integer is a wrapper object in Java. BTW, there is one more way to convert an int value to String in Java, the easiest one, String concatenation.

Even though Java doesn't support operator overloading, the + operator behaves differently with integer and string operands. If one of the arguments to this binary operator is String then it performs String concatenation, otherwise, it does addition. So you can convert an int value like 10 to a String value "10" by just doing "" + 10.

Btw, I don't recommend that as the preferred way because it looks like code smell and there is a chance of error if there is more argument like 10 + 10 + "" will produce "20" and not "1010" because + is the right-associative operator and it will first perform addition of 10 + 10 and then String concatenation between 20 + "".

Btw, if you are new to the Java Programming world then I also suggest you join a comprehensive Java course to learn Java in a structured way. Java is vast but you can learn better and quicker by following a curriculum which is provided by an online course. If you need a suggestion, I personally found The Complete Java Masterclass by Tim Buchalka on Udemy a great course to start with. This 80-hour long course covers many latest Java features and it's also very affordable as you can get it for just $10 on a Udemy sale. 





4 Ways to Convert an int value to a String in Java

Here are four different ways you can use to convert an int to String in Java. Most of them are very similar to what we have used to convert an Integer to a String because you can easily convert an int to Integer using Autoboxing. Some method reuses each other like valueOf(), which is also my favorite way to convert an int to String in Java. 

1. int to String using String.valueOf() in Java

It's no doubt my favorite way for int to String conversion because you can use the same approach to convert other data types to String as well like. you can call String.valueOf(long) to convert a long to String, String.valueOf(double) to convert a double value to String and String.valueOf(float) to convert a float value to String in Java.

Now let's see how to use this method, here is an example of using String.valueOf() for int to String conversion in Java:

String hundred = String.valueOf(100); // you can pass int constant

int ten = 10;
String ten = String.valueOf(ten) // You can also pass int variable

Most importantly It reads well. It's also a good example of the static factory method, which provides some significant advantages over the constructor for creating an object. Btw, Internally valueOf() also calls the Integer.toString() method for conversion, as shown below:

public static String valueOf(int i) {
  return Integer.toString(i, 10);
}
This is also the best way, in my opinion, to convert int to String, and more often than not you will find that Java developers use this method to convert int to String in production code. 


2. Using Integer.toString() to convert int to String

Another way to convert an int value to String is by using Integer.toString() method. This method converts the passed argument into int primitive as shown below:

String two = Integer.toString(20); // returns "20"
String one = Integer.toString(01); // returns "1"
String twentyOne = Integer.toString(-21); // returns -21
String seven = Integer.toString(+7); // returns 7

You can pass this method a signed int value but it will preserve sign only for the negative number. Even if you pass +7, it will create String as "7" without a plus sign.

Integer.toString() by default converts int to String in decimal format i.e. base 10 if you want to convert int to String in any other number system like binary, octal, or hexadecimal you can use an overloaded version of Integer.toString(int value, int radix) which also accepts a radix. 

You can pass radix as 16 to convert int to hexadecimal String, 8 to convert int value to Octal String, and 2 to convert int value to binary String as shown in the following example:

String hexa = Integer.toString(20,16); // "14"
String ocatal = Integer.toString(20, 8); // "24"
String binary = Integer.toString(20, 2); // "10100"

So, if you want to convert int to String in a different number system, you can use the Integer.toString() for that purpose. If you want to learn more about essential Java APIs like variables, Data Types, and operators then you can also check out Java Fundamentals: The Java Language course by Jim Wilson on Pluralsight. 

how to convert int to String in Java




Solution 3 - String concatenation

This is the easiest way to convert an int primitive to a String object in Java. All you need to do is concatenate the int value with an empty string like "" + 100 and this will return "100", no error, no issue, simple and easy.

here is an example of using String concatenation to convert int to String in Java. 
String thousand = "" + 1000;
String five = "" + 5;
While this is the easiest and simplest way to convert an int primitive to a String object in Java I don't like that in production code? Why? isn't it most readable as well? yes, it does but somehow it looks like a hack to me than a proper solution. another reason is that it internally uses StringBuilder for concatenation, which means one more temporary object for GC to cleanup. 

Nevertheless, if you like you can use this approach, feel free to use it, especially during testing.

Solution 4 - String.format() method

The format() method was introduced in java.lang.String class on JDK 1.5 and its primary use of nothing but to format numbers int to String. You can use also use this method to simply convert an int value to String as shown below:
String million = String.format("%d", 1000000)
It's especially useful for converting large int values to String. For more examples of formatting String in Java, see here.

And, if you want to learn Java Programming and Software Development in a structured and guided manager and need a course, I also recommend you to check out Java Programming and Software Engineering Fundamentals Specialization on Coursera. This program is offered by Duke University and you can audit courses for free. 






Java Program to convert int to String in Java

Here is our sample Java program to convert an int primitive to a String object. In this example, you will learn all three ways and one bonus way.

/**
 * Java Program to convert an int value to String object. In this article, we
 * will take a look at 4 different ways of converting int to String in Java. i)
 * String.valueOf() ii) Integer.toString() iii) String concatenation iv) String
 * format() method
 *
 * @author WINDOWS 8
 */
public class Int2String {

    public static void main(String args[]) {

        // 1st Example - by using String.valueOf() method
        String hundred = String.valueOf(100); // you can pass int constant
        int ten = 10;
        String str = String.valueOf(ten); // You can also pass int variable

        // 2nd Example - by using Integer.toString()
        String two = Integer.toString(20); // returns "20"
        String one = Integer.toString(01); // returns "1"
        String twentyOne = Integer.toString(-21); // returns -21
        String seven = Integer.toString(+7); // returns 7

        // 3rd Example - by using String concatenation
        String thousand = "" + 1000;
        String five = "" + 5;

        // 4th Example - by using String format() method
        String million = String.format("%d", 1000000);

    }

}



Here is a nice summary of all the ways to convert an int to String in Java:

How to convert int value to String object in Java



That's all about how to convert an int value to a String in Java. As I said, you can use either Integer.toString(), String.valueOf() or simply concatenation with empty String to do this task. Though it's better to use String.valueOf() method, it's more readable and also the standard way to convert any primitive data type to String in Java. You can also use the String.format() to get your int value as nicely formatted String, especially suitable to convert large int values like 1,000,000


Related Java Tutorials
If you like this tutorial and wants to learn more about how to convert one data type into another, Please check out the following Java programming tutorials:
  • How to convert String to Double in Java? (example)
  • How to convert char to String in Java? (tutorial)
  • 10 Free Courses to learn Data Structure in Java (free data structure courses)
  • How to convert Enum to String in Java? (example)
  • How to convert float to String in Java? (example)
  • How to convert byte array to String in Java? (program)
  • How to convert double to Long in Java? (program)
  • How to convert ByteBuffer to String in Java? (program)
  • How to convert String to Date in a thread-safe manner? (example)
  • How to convert String to int in Java? (example)
  • How to convert Decimal to Binary in Java? (example)
  • How to parse String into long in Java? (answer)
  • 10 Free Java Courses for Beginners to Join (free Java courses)

Thanks a lot for reading this article so far. If you like this tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.


P. S. - If you are new to the Java world and looking for a free online course to learn Java Programming then you can also join  Java Tutorial for Complete Beginners (FREE) course on Udemy. More than 1.2 million people have joined this course to learn Java online. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.