Convert long to String in Java
Tags: String long Convert DecimalFormat
In this Java core tutorial, we learn how to convert long value into String value in Java via different solutions.
Using String.valueOf() method to return a String from long value
ConvertLongToStringExample1.java
public class ConvertLongToStringExample1 {
public static void main(String[] args) {
long value1 = 123456789;
String value2 = String.valueOf(value1);
System.out.println("long value: " + value1);
System.out.println("String value: " + value2);
}
}
long value: 123456789
String value: 123456789
Convert String to long value using Long.toString() method
ConvertLongToStringExample2.java
public class ConvertLongToStringExample2 {
public static void main(String[] args) {
long value1 = 987654321;
String value2 = Long.toString(value1);
System.out.println("long value: " + value1);
System.out.println("String value: " + value2);
}
}
long value: 987654321
String value: 987654321
Using Long.toString() method to return a String from a Long object
ConvertLongToStringExample3.java
public class ConvertLongToStringExample3 {
public static void main(String[] args) {
Long value1 = Long.valueOf(123456);
String value2 = value1.toString();
System.out.println("long value: " + value1);
System.out.println("String value: " + value2);
}
}
long value: 123456
String value: 123456
Format a long as String using String.format() method
ConvertLongToStringExample4.java
public class ConvertLongToStringExample4 {
public static void main(String[] args) {
long value1 = 987654;
String value2 = String.format("%d", value1);
System.out.println("long value: " + value1);
System.out.println("String value: " + value2);
}
}
long value: 987654
String value: 987654
Format a long value as a String using DecimalFormat class
ConvertLongToStringExample5.java
import java.text.DecimalFormat;
public class ConvertLongToStringExample5 {
public static void main(String[] args) {
long value1 = 200000;
DecimalFormat decimalFormat = new DecimalFormat("#");
String value2 = decimalFormat.format(value1);
System.out.println("long value: " + value1);
System.out.println("String value: " + value2);
}
}
long value: 200000
String value: 200000
Happy Coding 😊