杰瑞科技汇

Java与String、Long如何高效转换?

Of course! The relationship between String and long in Java is a fundamental concept. It involves two main operations:

Java与String、Long如何高效转换?-图1
(图片来源网络,侵删)
  1. Parsing a String to a long: Converting text like "12345" into the numeric value 12345L.
  2. Converting a long to a String: Converting the numeric value 98765L into the text "98765".

Let's break down each part with clear examples and best practices.


Parsing a String to a long (String → long)

This is the process of reading a number from a string representation. Java provides a few ways to do this.

Method 1: Long.parseLong(String s) - The Standard Way

This is the most common and efficient method. It takes a String as input and returns a primitive long. It throws a NumberFormatException if the string does not contain a valid long integer.

Example:

Java与String、Long如何高效转换?-图2
(图片来源网络,侵删)
public class StringToLongExample {
    public static void main(String[] args) {
        String numberStr = "123456789";
        try {
            // Parse the string to a long
            long number = Long.parseLong(numberStr);
            System.out.println("Original String: " + numberStr);
            System.out.println("Parsed long: " + number);
            System.out.println("Type of parsed value: " + ((Object)number).getClass().getSimpleName()); // long
            // Example with a negative number
            String negativeStr = "-987654321";
            long negativeNumber = Long.parseLong(negativeStr);
            System.out.println("\nParsed negative long: " + negativeNumber);
        } catch (NumberFormatException e) {
            System.err.println("Error: Invalid number format in the string.");
        }
    }
}

Output:

Original String: 123456789
Parsed long: 123456789
Type of parsed value: long
Parsed negative long: -987654321

Method 2: Long.valueOf(String s) - The Object-Oriented Way

This method also converts a String to a long, but it returns a Long object (the wrapper class for the primitive long), not a primitive long. This is useful when you need an object, for example, to store it in a collection that doesn't accept primitives (like List<Long>).

Internally, Long.valueOf() often uses a cache for small values, so it can be more memory-efficient than creating a new Long object every time.

Example:

public class StringToLongObjectExample {
    public static void main(String[] args) {
        String numberStr = "255";
        try {
            // Parse the string to a Long object
            Long numberObject = Long.valueOf(numberStr);
            System.out.println("Original String: " + numberStr);
            System.out.println("Parsed Long object: " + numberObject);
            System.out.println("Type of parsed value: " + numberObject.getClass().getSimpleName()); // Long
            // You can easily get the primitive long from the object
            long primitiveValue = numberObject;
            System.out.println("Primitive long from object: " + primitiveValue);
        } catch (NumberFormatException e) {
            System.err.println("Error: Invalid number format in the string.");
        }
    }
}

Output:

Original String: 255
Parsed Long object: 255
Type of parsed value: Long
Primitive long from object: 255

Handling Different Number Bases (Radix)

Both parseLong and valueOf have an overloaded version that lets you specify the radix (base) of the number in the string.

  • Radix 2: Binary
  • Radix 8: Octal
  • Radix 10: Decimal (default)
  • Radix 16: Hexadecimal

Example:

public class StringToLongRadixExample {
    public static void main(String[] args) {
        String binaryStr = "1010";  // Represents 10 in decimal
        String octalStr = "12";     // Represents 10 in decimal
        String hexStr = "A";        // Represents 10 in decimal
        long fromBinary = Long.parseLong(binaryStr, 2);
        long fromOctal = Long.parseLong(octalStr, 8);
        long fromHex = Long.parseLong(hexStr, 16);
        System.out.println("Binary '1010' (base 2) is: " + fromBinary); // 10
        System.out.println("Octal '12' (base 8) is: " + fromOctal);   // 10
        System.out.println("Hex 'A' (base 16) is: " + fromHex);      // 10
    }
}

Converting a long to a String (long → String)

This is the reverse operation and is also very straightforward.

Method 1: String.valueOf(long l) - The Recommended Way

This is the most direct and efficient way to convert a primitive long to a String. It's generally preferred over concatenation ("" + l) because it avoids creating an intermediate StringBuilder object.

Example:

public class LongToStringExample {
    public static void main(String[] args) {
        long number = 9876543210L;
        // Convert the long to a String
        String numberStr = String.valueOf(number);
        System.out.println("Original long: " + number);
        System.out.println("Converted String: " + numberStr);
        System.out.println("Type of converted value: " + numberStr.getClass().getSimpleName()); // String
        // Example with a negative number
        long negativeNumber = -12345L;
        String negativeStr = String.valueOf(negativeNumber);
        System.out.println("\nConverted negative long: " + negativeStr);
    }
}

Output:

Original long: 9876543210
Converted String: 9876543210
Type of converted value: String
Converted negative long: -12345

Method 2: Long.toString(long l) - The Object-Oriented Way

If you have a Long object, you can use its toString() method. You can also use the static Long.toString(long l) method, which is functionally identical to String.valueOf().

Example:

public class LongObjectToStringExample {
    public static void main(String[] args) {
        long primitiveLong = 777;
        // Convert the primitive to a Long object first
        Long longObject = Long.valueOf(primitiveLong);
        // Now use the toString() method of the object
        String numberStr = longObject.toString();
        System.out.println("Original long: " + primitiveLong);
        System.out.println("Converted String: " + numberStr);
        // Or use the static method directly
        String staticStr = Long.toString(primitiveLong);
        System.out.println("Converted via static method: " + staticStr);
    }
}

Output:

Original long: 777
Converted String: 777
Converted via static method: 777

Summary Table

Operation Method What it Does Return Type When to Use
String → long Long.parseLong(s) Converts a String to a primitive long. long The most common choice. Use when you need the primitive value for calculations.
String → long Long.valueOf(s) Converts a String to a Long object. Long Use when you need an object, e.g., for collections (List<Long>).
long → String String.valueOf(l) Converts a primitive long to a String. String The recommended way. It's clear and efficient.
long → String Long.toString(l) Converts a primitive long to a String. String A perfectly valid alternative to String.valueOf().

Key Takeaways

  1. Use Long.parseLong() when you have a String and need the primitive long for math.
  2. Use String.valueOf() when you have a primitive long and need a String representation.
  3. Always handle NumberFormatException when parsing user input or data from external sources, as the format might be invalid.
  4. Remember the difference between primitive long and its wrapper class Long. The choice between parseLong and valueOf often depends on which one you need.
分享:
扫描分享到社交APP
上一篇
下一篇