5 Ways to Convert Integer into String in Java.

We can convert an integer into a String in Java using multiple ways and here in this article, we are going to learn 5 different ways to do so. Let's discuss each of them one by one.

Using the String.valueOf() method:

This method is a static method of the String class, which takes an int argument and returns a String representation of the integer value.

Example code:
int num = 42;
String str = String.valueOf(num);

Using the Integer.toString() method:

This method is a static method of the Integer class, which takes an int argument and returns a String representation of the integer value.

Example code:
int num = 42;
String str = Integer.toString(num);

Using concatenation with an empty string:

In Java, when a String is concatenated with another value, the other value is automatically converted to a String.

Example code:
int num = 42;
String str = "" + num;

Using the String.format() method:

This method is a static method of the String class, which takes a format string and an int argument, and returns a formatted String.

Example code:
int num = 42;
String str = String.format("%d", num);

Using StringBuilder or StringBuffer class:

Both StringBuilder and StringBuffer classes are used to create and manipulate strings in Java. They have methods to append various types of data to the string they are building.

Example code: 
int num = 42;
StringBuilder sb = new StringBuilder();
sb.append(num);
String str = sb.toString();

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS