乐闻世界logo
搜索文章和话题

How to convert String to long in Java?

1个答案

1

In Java, the most common way to convert a String to a long is by using the parseLong method of the Long class. This method parses the string argument as a signed decimal long and returns the numeric value it represents.

Here are the specific steps and examples:

Step 1: Ensure the string can be parsed

First, ensure the string represents a valid numeric value within the range of a long type (-9223372036854775808 to 9223372036854775807). If the string contains non-digit characters (except for the leading negative sign), parseLong will throw a NumberFormatException.

Example Code

java
public class Main { public static void main(String[] args) { String numberStr = "123456789"; try { long number = Long.parseLong(numberStr); System.out.println("Converted long value: " + number); } catch (NumberFormatException e) { System.out.println("Invalid string format; conversion failed!"); } } }

Step 2: Handle exceptions

When using the parseLong method, it is recommended to handle potential NumberFormatException exceptions using a try-catch block to enhance program robustness. This prevents the program from terminating unexpectedly due to exceptions.

Step 3: Using the valueOf method (Alternative option)

In addition to the parseLong method, you can use the valueOf method of the Long class. This method not only converts a string to a long type but also returns a Long object, which is useful when you need a Long object rather than a primitive type.

java
public class Main { public static void main(String[] args) { String numberStr = "987654321"; try { Long numberObject = Long.valueOf(numberStr); System.out.println("Converted Long object: " + numberObject); } catch (NumberFormatException e) { System.out.println("Invalid string format; conversion failed!"); } } }

Summary

Both methods can meet different requirements: parseLong directly returns the primitive long type, while valueOf returns a Long object. Choose the appropriate method based on specific needs. In actual development, proper handling of data validation and exceptions is crucial for ensuring program stability and robustness.

2024年8月8日 03:05 回复

你的答案