The java.lang.Integer.toString() method is an inbuilt method in Java used to convert an integer value into its corresponding String representation. The Integer class provides multiple overloaded versions of this method for different use cases.
1. Integer.toString()
This method returns a String object representing the value of the current Integer object.
Syntax
public String toString();
- Parameters: This method does not accept any parameters.
- Return Value: Returns a String representing the value of the Integer object.
Example: This example shows how to convert an Integer object into a String using the toString() method in Java.
public class GFG {
public static void main(String[] args) {
Integer num = 25;
String str = num.toString(); // Convert Integer to String
System.out.println(str);
}
}
Output
25
Explanation:
- Integer num = 25; creates an Integer object with the value 25.
- num.toString() converts the integer value into a String.
- System.out.println(str); prints the string value to the console.
2. Integer.toString(int a)
This method returns a String representation of the specified integer value.
Syntax
public static String toString(int a);
- Parameters: 'a' an integer value that needs to be converted to a string.
- Return Value: Returns the string representation of the given integer.
Example: This example demonstrates how to convert a primitive integer value into a string using the Integer.toString() method.
public class GFG{
public static void main(String[] args) {
int a = -787;
String result = Integer.toString(a); // Convert int to String
System.out.println(result);
}
}
Output
-787
Explanation:
- int a = -787; declares an integer variable.
- Integer.toString(a) converts the integer value into a string.
- System.out.println(result); prints the string value to the console.
3. Integer.toString(int a, int base)
This overloaded method returns a string representation of the integer a in the specified radix (base).If the base is less than Character.MIN_RADIX (2) or greater than Character.MAX_RADIX (36), base 10 is used by default.
Syntax
public static String toString(int a, int base);
- Parameters: "a" the integer value to be converted, "base" the radix/base used for conversion.
- Return Value: Returns a string representation of the integer in the specified base.
- Digits Used: 0-9 and a-z (for bases up to 36).
Example: This example demonstrates how to convert an integer value into a string using different number bases (radix).
public class GFG {
public static void main(String[] args) {
int binaryValue = 71;
String binaryResult = Integer.toString(binaryValue, 2);
System.out.println(binaryResult); // Output: 1000111
int hexValue = 314;
String hexResult = Integer.toString(hexValue, 16);
System.out.println(hexResult); // Output: 13a
}
}
Output
1000111 13a
Explanation:
- Integer.toString(value, base) converts an integer into a string using the specified base.
- Base 2 converts the number to binary.
- Base 16 converts the number to hexadecimal.