A long value can be converted into a String using any of the following methods:
1) Method 1: Using String.valueOf(long l): This method takes a long value as an argument and returns a string representation of it.
Method declaration:
public static String valueOf(long l)
parameters:
l – long value which we want to convert
returns:
String representation of long l
long lvar = 123; String str = String.valueOf(lvar);
2) Method 2: Using Long.toString(long l): This method works same as String.valueOf(long) method. It returns the string that represents the long value that we pass to this method. For e.g. if the passed value is 1202 then the returned string would be “1202”.
Method declaration:
public static String toString(long l)
parameters:
l – this represents the long value that we are passing to the method as argument.
returns:
The string representing the passed long value.
long lvar2 = 200; String str2 = Long.toString(lvar2);
Example: Converting boolean to String
This program demonstrates the use of both the above mentioned methods. Here we have two long variables(lvar & lvar2) and we are converting one of them using String.valueOf(long l) method and other one using Long.toString(long l) method.
package com.beginnersbook.string; public class LongToString { public static void main(String[] args) { /* Method 1: using valueOf() method * of String class. */ long lvar = 123; String str = String.valueOf(lvar); System.out.println("String is: "+str); /* Method 2: using toString() method * of Long class */ long lvar2 = 200; String str2 = Long.toString(lvar2); System.out.println("String2 is: "+str2); } }
Output:
String is: 123 String2 is: 200
Leave a Reply