Convert String to long in Java

Tags: String long Convert

In this Java core tutorial, we learn how to convert String value into long value in Java via different solutions.

Parse a String into long using Long.parseLong() static method

ConvertStringToLongExample1.java

public class ConvertStringToLongExample1 {
    public static void main(String[] args) {
        String value1 = "123456789";
        long value2 = Long.parseLong(value1);

        System.out.println("String value: " + value1);
        System.out.println("long value: " + value2);
    }
}
The output is:
String value: 123456789
long value: 123456789

Using Long.valueOf() method to instantiate long from a String value

ConvertStringToLongExample2.java

public class ConvertStringToLongExample2 {
    public static void main(String[] args) {
        String value1 = "987654321";
        long value2 = Long.valueOf(value1);

        System.out.println("String value: " + value1);
        System.out.println("long value: " + value2);
    }
}
The output is:
String value: 987654321
long value: 987654321

Happy Coding 😊