Java Long toString(long i,int radix) Method
Java toString()
method is a part of the Long
class of the java.lang
package. This method is used to return the String equivalent of the long value passed as argument in the base(radix) passed.
If the first argument is negative, the first element of the result is the ASCII minus sign '-'
('\u002d'
). If the first argument is not negative, no sign character appears in the result. It must also 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(long i, int radix)
Parameters:
The parameters passed are long i
whose converted String is to be returned and int radix
which defines the base for the String conversion.
Returns:
The String equivalent of the long value passed in accordance with the radix value passed as the parameter.
Example 1:
Here, the long values are converted into its equivalent String representations in accordance with the radix value.
import java.lang.Long;
public class StudyTonight
{
public static void main(String[] args)
{
long a = 78L;
int d = 10;
int h = 16;
int o = 8;
int b = 2;
String s1 = Long.toString(a,d); //Returns the string representation of the long value with radix 10
System.out.println("Equivalent String Value = " + s1);
String s2 = Long.toString(a,h); //Returns the string representation of the long value with radix 16
System.out.println("Equivalent String Value = " + s2);
String s3 = Long.toString(a, o); //Returns the string representation of the long value with radix 8
System.out.println("Equivalent String Value = " + s3);
String s4 = Long.toString(a, b); //Returns the string representation of the long value with radix 2
System.out.println("Equivalent String Value = " + s4);
}
}
Equivalent String Value = 78
Equivalent String Value = 4e
Equivalent String Value = 116
Equivalent String Value = 1001110
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);
long val = sc.nextLong();
int b = sc.nextInt();
System.out.println("Output: "+Long.toString(val, b)); //returns string with equivalent base
}
catch(Exception e)
{
System.out.println("Invalid Input!!");
}
}
}
Enter the value and base
7955 8
Output: 17423
*********************************
Enter the value and base
808 16
Output: 328
*********************************
Enter the value and base
0x67 8
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.