Introduction
Converting a String
to a Long
in Java is a common task that can be useful in various scenarios such as parsing user input, reading data from files, or handling configuration parameters. In Java, this conversion can be done using several methods. This blog post will explore different methods to convert a String
to a Long
in Java.
Table of Contents
- Using
Long.parseLong()
- Using
Long.valueOf()
- Complete Example Program
- Conclusion
1. Using Long.parseLong()
The Long.parseLong()
method parses the string argument as a signed decimal long
.
Example:
public class StringToLongUsingParseLong {
public static void main(String[] args) {
String strValue = "123456789";
// Convert string to long using Long.parseLong()
long longValue = Long.parseLong(strValue);
System.out.println("String value: " + strValue);
System.out.println("Long value: " + longValue);
}
}
Output:
String value: 123456789
Long value: 123456789
Explanation:
Long.parseLong(strValue)
converts the string value to its long representation.
2. Using Long.valueOf()
The Long.valueOf()
method returns a Long
instance representing the specified string value. This method can also be used to convert a String
to a long
.
Example:
public class StringToLongUsingValueOf {
public static void main(String[] args) {
String strValue = "987654321";
// Convert string to long using Long.valueOf()
long longValue = Long.valueOf(strValue);
System.out.println("String value: " + strValue);
System.out.println("Long value: " + longValue);
}
}
Output:
String value: 987654321
Long value: 987654321
Explanation:
Long.valueOf(strValue)
converts the string value to its long representation.
3. Complete Example Program
Here is a complete program that demonstrates both methods discussed above to convert a String
to a Long
.
Example Code:
public class StringToLongExample {
public static void main(String[] args) {
String strValue1 = "123456789";
String strValue2 = "987654321";
// Using Long.parseLong() Method
long longValue1 = Long.parseLong(strValue1);
System.out.println("Using Long.parseLong():");
System.out.println("String value: " + strValue1 + " -> Long value: " + longValue1);
// Using Long.valueOf() Method
long longValue2 = Long.valueOf(strValue2);
System.out.println("\nUsing Long.valueOf():");
System.out.println("String value: " + strValue2 + " -> Long value: " + longValue2);
}
}
Output:
Using Long.parseLong():
String value: 123456789 -> Long value: 123456789
Using Long.valueOf():
String value: 987654321 -> Long value: 987654321
4. Conclusion
Converting a String
to a Long
in Java can be accomplished in several ways. The Long.parseLong()
and Long.valueOf()
methods are both straightforward and widely used. By understanding these different methods, you can choose the one that best fits your needs and coding style.
Happy coding!
Comments
Post a Comment
Leave Comment