Java StringToLongConverter

1. Introduction

Converting a string to a long in Java is a necessary task when you need to handle larger integers that exceed the capacity of int. Java provides Long.parseLong() for obtaining a primitive long value and Long.valueOf() for getting a Long object. This tutorial will cover both methods and their uses.

Key Points

- Long.parseLong(String s) converts a string to a primitive long.

- Long.valueOf(String s) converts a string to a Long object.

- Both methods can throw NumberFormatException if the string does not contain a parsable long.

2. Program Steps

1. Define a string that represents a long value.

2. Convert the string to a primitive long using Long.parseLong().

3. Convert the string to a Long object using Long.valueOf().

4. Print both converted values.

3. Code Program

public class StringToLongExample {
    public static void main(String[] args) {
        // String to be converted
        String longString = "9223372036854775807"; // Maximum value for a long

        // Convert string to primitive long
        long longPrimitive = Long.parseLong(longString);

        // Convert string to Long object
        Long longObject = Long.valueOf(longString);

        // Print the results
        System.out.println("Converted to primitive long: " + longPrimitive);
        System.out.println("Converted to Long object: " + longObject);
    }
}

Output:

Converted to primitive long: 9223372036854775807
Converted to Long object: 9223372036854775807

Explanation:

1. String longString = "9223372036854775807": Initializes a string that represents the maximum value a long can hold.

2. long longPrimitive = Long.parseLong(longString): Converts the string to a primitive long. This is the most direct method when you need to use the value in numerical operations.

3. Long longObject = Long.valueOf(longString): Converts the string to a Long object. This approach is often used when you need to pass a long as part of an object collection such as a List or Set.

4. System.out.println("Converted to primitive long: " + longPrimitive) and System.out.println("Converted to Long object: " + longObject): Outputs both conversions to verify correctness, displaying the conversion of the string to both primitive and object form.


Comments