In this tutorial, we will see how to convert String to long in Java. There are three ways to convert a String to a long value.
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 to Convert String to long using Long.parseLong(String)
In this example, the string str2 has minus sign ‘-‘ in the beginning, which is why the the value of variable num2 is negative.
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 to Convert String to long using Long.valueOf(String)
public class Example { 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+num2); } }
Output:
99999
3. Java – Convert String to long using the constructor of Long class
Long(String s) constructor : Long class has a constructor which 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 for String to long conversion using new Long(String)
public class Example { 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*num2); } }
Output:
222220000
Leave a Reply