How to convert an int to a String in Java

In this section, we will show you how to convert an int to a String in Java.

Following ways can be used for converting int to String:

1. By using Integer.toString() method

2. By using String.valueOf() method 

NoteInteger.toString() method is faster than String.valueOf(). String.valueOf() method internally invokes the Integer.toString() method.

public static String valueOf(int i) {
return Integer.toString(i);
}

Example 1: Using Integer.toString() method

The java.lang.Integer.toString() is an inbuilt method in Java which is used to returns the string object of the particular Integer value. By default, the argument is converted to signed decimal (radix 10) in string format.

public class Main {

// Driver code
public static void main(String[] args)
{
int val = 9;
String str = Integer.toString(val);
System.out.println("String => "+str);
}
}


Console Output:
String => 9


Example 2: Using String.valueOf()

The java.lang.String.valueOf(int i) returns the string representation of the int argument. It internally invokes the Integer.toString() so the representations are always exactly the same.

public class Main {

// Driver code
public static void main(String[] args)
{
int val = 9;
String str = String.valueOf(val);
System.out.println("String => "+str);
}
}


Console Output:
String => 9

More related topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete