To convert a Java String to a long, you can use the Long.parseLong()
method. Here’s an example:
String numberString = "123456789"; long number = Long.parseLong(numberString);
In this example, the numberString
variable contains the string “123456789”. The Long.parseLong()
method is then used to parse this string and convert it to a long
, which is assigned to the number
variable.
Note that Long.parseLong()
can throw a NumberFormatException
if the string cannot be parsed as a valid long. Therefore, you should always wrap the call to Long.parseLong()
in a try-catch block to handle this possibility.
Java String to long Example:
Sure, here’s an example of converting a Java String to a long using the Long.parseLong()
method:
public class StringToLongExample { public static void main(String[] args) { String numberString = "123456789"; long number = Long.parseLong(numberString); System.out.println(number); // Output: 123456789 } }
In this example, we create a String
variable called numberString
and assign it the value "123456789"
. We then use the Long.parseLong()
method to convert this string to a long
and assign it to the number
variable. Finally, we print the value of number
to the console using the System.out.println()
method.
When you run this code, the output will be 123456789
, which is the long
value that corresponds to the "123456789"
string.