LAST UPDATED: NOVEMBER 5, 2020
Java Integer toString(int i,int radix) Method
Java toString()
method is a part of the Integer
class of the java.lang
package. This method is used to return the String equivalent of the integer value passed as argument in the base(radix) passed. For example, toString(65,10)
will return 65 because the value of 65 in base 10 is 65 while toString(65,8)
will return 101 as the value of 65 in base 8 is 101.
It must be noted that if the radix value is less than Character.MIN_RADIX
or more than Character.MAX_RADIX
then base 10 is used.
Syntax:
public static String toString(int i, int radix)
Parameters:
The parameters passed are int i
whose String equivalent is to be returned and int radix
which defines the base for the String conversion.
Returns:
The String equivalent of the integer value passed in accordance with the radix value passed as the parameter.
Example 1:
Here, the integer values are converted into its equivalent String representations in accordance with the radix value.
public class Main
{
public static void main(String[] args)
{
int a = 40;
int b = 8;
int c = 40;
int d = 16;
System.out.println("Equivalent String is : "+Integer.toString(a,b));
System.out.println("Equivalent String is : "+Integer.toString(c,d));
}
}
Equivalent String is : 50
Equivalent String is : 28
Example 2:
Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
System.out.println("Enter the value and base ");
Scanner sc = new Scanner(System.in);
int val = sc.nextInt();
int b = sc.nextInt();
System.out.println("Output: "+Integer.toString(val, b)); //returns string with equivalent base
}
catch(Exception e)
{
System.out.println("Invalid Input!!");
}
}
}
Enter the value and base
67 8
Output: 103
*******************************
Enter the value and base
91 16
Output: 5b
*******************************
Enter the value and base
0x34
Invalid Input!!
Live Example:
Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.