In this tutorial, you will learn how to convert String to long in Java. There are following three ways to convert a String to a long value.
- Long.parseLong() Method
- Long.valueOf() Method
- Long(String s) Constructor of Long class
1. Java – Convert String to long using Long.parseLong(String)
Long.parseLong(String): All the characters in the String must be digits except the first character, which can be a digit or a minus ‘-‘. For example: long var = Long.parseInt("-123");
is allowed and the value of var after conversion would be -123.
Java Program
In this example, the string str2
has minus sign ‘-‘ in the beginning, which is why the value of variable num2
is negative in the output.
public class JavaExample { public static void main(String[] args) { String str = "21111"; String str2 = "-11111"; //Conversion using parseLong(String) method long num = Long.parseLong(str); long num2 = Long.parseLong(str2); System.out.println(num+num2); } }
Output:

2. Java – Convert String to long using Long.valueOf(String)
Long.valueOf(String): Converts the String to a long value. Similar to parseLong(String) method, this method also allows minus ‘-‘ as a first character in the String.
Java Program
public class JavaExample { public static void main(String[] args) { String str = "11111"; String str2 = "88888"; //Conversion using valueOf(String) method long num = Long.valueOf(str); long num2 = Long.valueOf(str2); System.out.println(num); System.out.println(num2); } }
Output:
11111 88888
3. Java – Convert String to long using the constructor of Long class
Long(String s) constructor: Long class has a constructor that allows String argument and creates a new Long object representing the specified string in the equivalent long value. The string is converted to a long
value in exactly the manner used by the parseLong(String)
method for radix 10.
Java Program
public class JavaExample { public static void main(String[] args) { String str = "10000"; String str2 = "22222"; //Conversion using Long(String s) constructor long num = new Long(str); long num2 = new Long(str2); System.out.println(num); System.out.println(num2); } }
Output:
10000 22222
Recommended Posts
- Java long to String Conversion
- Java String to int Conversion
- Java String to double Conversion
- Java String to char Conversion
- Java String to Object Conversion
- Java String to float Conversion
- Java String to Date Conversion
- Java String to boolean Conversion
Reference: Long class JavaDoc
Leave a Reply