杰瑞科技汇

Java Integer与String如何高效转换?

Of course! Converting between Integer (the object) and String (the object) is a fundamental task in Java. Here’s a comprehensive guide covering all the common methods, from the classic to the modern.

Java Integer与String如何高效转换?-图1
(图片来源网络,侵删)

Quick Summary

Goal Best Method (Modern Java) Alternative (Classic)
int to String String.valueOf(myInt) Integer.toString(myInt)
String to int Integer.parseInt(myString) new Integer(myString).intValue()

Converting an int or Integer to a String

You have several ways to do this. The most common and recommended methods are String.valueOf() and Integer.toString().

Method 1: String.valueOf() (Recommended)

This is a static method on the String class. It's versatile because it can handle not just integers but also other data types like double, boolean, and even Objects (by calling their toString() method).

Code:

int number = 123;
Integer numberObject = 456;
// Convert primitive int to String
String strFromInt = String.valueOf(number);
System.out.println("strFromInt: " + strFromInt); // Output: strFromInt: 123
System.out.println("Type: " + strFromInt.getClass().getSimpleName()); // Output: Type: String
// Convert Integer object to String
String strFromInteger = String.valueOf(numberObject);
System.out.println("strFromInteger: " + strFromInteger); // Output: strFromInteger: 456

Method 2: Integer.toString()

This is a static method on the Integer class. It's very explicit and clear in its intent: you are converting an integer-related value to a string.

Java Integer与String如何高效转换?-图2
(图片来源网络,侵删)

Code:

int number = 789;
Integer numberObject = 1011;
// Convert primitive int to String
String strFromInt = Integer.toString(number);
System.out.println("strFromInt: " + strFromInt); // Output: strFromInt: 789
// Convert Integer object to String
String strFromInteger = Integer.toString(numberObject);
System.out.println("strFromInteger: " + strFromInteger); // Output: strFromInteger: 1011

Method 3: Concatenation (The Easy Way)

You can simply use the operator. Java automatically handles the conversion behind the scenes. This is convenient for quick and simple code but can be less efficient in loops or performance-critical code.

Code:

int number = 2025;
String str = "The year is " + number;
System.out.println(str); // Output: The year is 2025

Method 4: Using String.format()

This is useful when you want more control over the formatting of the number (e.g., adding leading zeros, specifying a number base).

Java Integer与String如何高效转换?-图3
(图片来源网络,侵删)

Code:

int number = 42;
// Basic conversion
String str1 = String.format("%d", number);
System.out.println("Basic: " + str1); // Output: Basic: 42
// Format with leading zeros (to a width of 5)
String str2 = String.format("%05d", number);
System.out.println("Padded: " + str2); // Output: Padded: 00042
// Format as hexadecimal
String str3 = String.format("%x", number);
System.out.println("Hex: " + str3); // Output: Hex: 2a

Converting a String to an int or Integer

This process is called parsing. The key thing to remember is that parsing can fail if the String does not contain a valid integer representation. This will throw a NumberFormatException.

Method 1: Integer.parseInt() (Most Common)

This is a static method that takes a String and returns a primitive int. It's the most direct way to get an int value.

Code:

String numberStr = "123";
// Convert String to primitive int
int number = Integer.parseInt(numberStr);
System.out.println("number: " + number); // Output: number: 123
System.out.println("Type: " + ((Object)number).getClass().getSimpleName()); // Output: Type: int

Handling Errors (Crucial!)

If the string is not a valid number, a NumberFormatException is thrown. You must handle this with a try-catch block.

String invalidStr = "hello";
try {
    int number = Integer.parseInt(invalidStr);
    System.out.println("This line will not be printed.");
} catch (NumberFormatException e) {
    System.err.println("Error: Could not parse '" + invalidStr + "' to an integer.");
    // e.printStackTrace(); // Uncomment to see the full stack trace
}
// Output: Error: Could not parse 'hello' to an integer.

Method 2: Integer.valueOf()

This is also a static method, but it returns an Integer object. It uses a cache for small values (-128 to 127) to improve performance and memory usage.

Code:

String numberStr = "456";
// Convert String to Integer object
Integer numberObject = Integer.valueOf(numberStr);
System.out.println("numberObject: " + numberObject); // Output: numberObject: 456
System.out.println("Type: " + numberObject.getClass().getSimpleName()); // Output: Type: Integer

Error Handling

Like parseInt(), this method also throws a NumberFormatException for invalid input and should be wrapped in a try-catch block.

String invalidStr = "world";
try {
    Integer numberObject = Integer.valueOf(invalidStr);
    System.out.println("This line will not be printed.");
} catch (NumberFormatException e) {
    System.err.println("Error: Could not parse '" + invalidStr + "' to an Integer object.");
}
// Output: Error: Could not parse 'world' to an Integer object.

When to Use Which? (A Practical Guide)

Scenario Recommended Method Why?
I need a String for display or logging. String.valueOf() or Integer.toString() Clear, readable, and standard practice.
I have an int in a calculation and need to add it to a sentence. Concatenation ("Age: " + age) Quick and easy for simple cases.
I need to read a number from a file or user input. Integer.parseInt() or Integer.valueOf() This is parsing. You need to convert text to a number.
I need the result as a primitive int for a calculation. Integer.parseInt() Directly gives you the primitive type you need.
I need the result as an Integer object to store in a collection (like List<Integer>). Integer.valueOf() Returns an Integer object directly. More memory-efficient for small numbers due to caching.
I need to format the number with specific rules (padding, hex, etc.). String.format() Offers powerful and flexible formatting options.

Complete Example

Here is a full program demonstrating all the conversions and error handling.

public class IntegerStringConversion {
    public static void main(String[] args) {
        // ====================================================================
        // PART 1: int/Integer TO String
        // ====================================================================
        System.out.println("--- Converting TO String ---");
        int primitiveInt = 2025;
        Integer integerObject = 9876;
        // Recommended methods
        String str1 = String.valueOf(primitiveInt);
        String str2 = Integer.toString(integerObject);
        System.out.println("String from int: " + str1);
        System.out.println("String from Integer: " + str2);
        // Easy concatenation
        String str3 = "The number is " + primitiveInt;
        System.out.println("Via concatenation: " + str3);
        // Formatting
        String str4 = String.format("Year: %04d", primitiveInt);
        System.out.println("Formatted string: " + str4);
        System.out.println();
        // ====================================================================
        // PART 2: String TO int/Integer (with error handling)
        // ====================================================================
        System.out.println("--- Converting FROM String ---");
        String validNumberStr = "12345";
        String invalidNumberStr = "Java123";
        try {
            // Convert to primitive int
            int parsedInt = Integer.parseInt(validNumberStr);
            System.out.println("Successfully parsed to int: " + parsedInt);
            System.out.println("Type of parsedInt: " + ((Object)parsedInt).getClass().getSimpleName());
            // Convert to Integer object
            Integer valueOfInt = Integer.valueOf(validNumberStr);
            System.out.println("Successfully parsed to Integer object: " + valueOfInt);
            System.out.println("Type of valueOfInt: " + valueOfInt.getClass().getSimpleName());
        } catch (NumberFormatException e) {
            System.err.println("Error parsing '" + validNumberStr + "'. This shouldn't happen.");
分享:
扫描分享到社交APP
上一篇
下一篇