杰瑞科技汇

Java中int与String如何转换?

Of course! This is a fundamental and very common task in Java. Converting between int (a primitive integer) and String (an object representing text) is essential for user input, file I/O, and displaying data.

Here’s a complete guide covering all the main methods, from the simplest to the most flexible.


Summary Table

Conversion Method Description
int to String String.valueOf(int i) Recommended. Simple, clear, and handles null gracefully if using an Integer object.
Integer.toString(int i) Also excellent. A direct static method on the Integer wrapper class.
"" + int Works, but can be less efficient and slightly less clear. Not recommended for production code.
String to int Integer.parseInt(String s) Recommended. Throws NumberFormatException if the string is not a valid integer.
Integer.valueOf(String s) Also excellent. Returns an Integer object (autoboxing to int happens). Also throws NumberFormatException.

Converting int to String

There are two primary, recommended ways to do this. A third, less common way also exists.

Method 1: String.valueOf(int i) (Recommended)

This is the most straightforward and idiomatic way. You are explicitly asking the String class to create a representation of your integer.

int number = 123;
String strNumber = String.valueOf(number);
System.out.println(strNumber);      // Output: "123"
System.out.println(strNumber.getClass().getName()); // Output: java.lang.String
// It also works with the Integer object
Integer integerObject = 456;
String strFromObject = String.valueOf(integerObject);
System.out.println(strFromObject); // Output: "456"

Why it's recommended: It's clean, readable, and part of the core String class. It also safely handles null Integer objects, returning the string "null".

Method 2: Integer.toString(int i)

This method is also perfectly fine and very common. It's a static method on the Integer wrapper class that does the exact same thing as String.valueOf() for an int.

int number = 789;
String strNumber = Integer.toString(number);
System.out.println(strNumber); // Output: "789"

Method 3: Concatenation (The "Easy but Not Best" Way)

You can simply concatenate the int with an empty string. Java automatically calls the toString() method behind the scenes.

int number = 101;
String strNumber = "" + number;
System.out.println(strNumber); // Output: "101"

Why it's not recommended:

  • Performance: It can be slightly less efficient because it involves creating a StringBuilder implicitly.
  • Readability: It's less explicit about your intent. String.valueOf(number) clearly states "convert this to a string."
  • Style: Many style guides (like Google's) discourage this practice for clarity.

Converting String to int

This is more complex because the string might not contain a valid number. You must handle potential errors. The two main methods both throw a NumberFormatException if the conversion fails.

Method 1: Integer.parseInt(String s) (Recommended)

This is the most direct way to get a primitive int from a String. It parses the string and returns the integer value.

String strNumber = "2025";
int number = Integer.parseInt(strNumber);
System.out.println(number);      // Output: 2025
System.out.println(number + 10); // Output: 2034
// It will fail if the string is not a valid integer
try {
    String invalidStr = "hello";
    int invalidNumber = Integer.parseInt(invalidStr);
} catch (NumberFormatException e) {
    System.out.println("Error: Cannot convert '" + invalidStr + "' to an integer.");
    // Output: Error: Cannot convert 'hello' to an integer.
}

Crucial: You must wrap this call in a try-catch block if the string's content is not guaranteed to be a valid integer.

Method 2: Integer.valueOf(String s)

This method also converts a String to an int, but with a key difference: it returns an Integer object (the wrapper class for int).

Due to autoboxing, Java will automatically convert the Integer object to a primitive int in most contexts, so it often looks the same as parseInt.

String strNumber = "3030";
// Integer.valueOf() returns an Integer object
Integer integerObject = Integer.valueOf(strNumber);
// Autoboxing converts the Integer object to an int primitive
int number = integerObject; // This is what Java does for you
System.out.println(number);      // Output: 3030
System.out.println(integerObject); // Output: 3030 (the object's toString() is called)

When to use which?

  • Use parseInt() when you definitely need a primitive int.
  • Use valueOf() when you might want to keep the Integer object, for example, to use it in a collection that doesn't accept primitives (like List<Integer>).

Both methods will throw a NumberFormatException for invalid input, so the error-handling logic is identical.


Complete, Runnable Example

Here is a full class demonstrating all the conversions with proper error handling.

public class IntStringConversion {
    public static void main(String[] args) {
        // =================================================================
        // PART 1: Converting int to String
        // =================================================================
        int myInt = 9876;
        // Recommended Method 1: String.valueOf()
        String strFromValueOf = String.valueOf(myInt);
        System.out.println("Using String.valueOf(): " + strFromValueOf);
        // Recommended Method 2: Integer.toString()
        String strFromToString = Integer.toString(myInt);
        System.out.println("Using Integer.toString(): " + strFromToString);
        // Less Recommended Method 3: Concatenation
        String strFromConcat = "" + myInt;
        System.out.println("Using concatenation: " + strFromConcat);
        System.out.println("\n----------------------------------------\n");
        // =================================================================
        // PART 2: Converting String to int
        // =================================================================
        String validStr = "555";
        String invalidStr = "Java";
        String anotherInvalidStr = "12.34"; // Not a whole number
        // Recommended Method 1: Integer.parseInt()
        try {
            int parsedInt = Integer.parseInt(validStr);
            System.out.println("Successfully parsed '" + validStr + "' to: " + parsedInt);
        } catch (NumberFormatException e) {
            System.out.println("Error: Could not parse '" + validStr + "'");
        }
        // This will fail and be caught by the catch block
        try {
            int invalidInt = Integer.parseInt(invalidStr);
            System.out.println("This line will not be reached for '" + invalidStr + "'");
        } catch (NumberFormatException e) {
            System.out.println("Error parsing '" + invalidStr + "': " + e.getMessage());
        }
        // This will also fail
        try {
            int anotherInvalidInt = Integer.parseInt(anotherInvalidStr);
        } catch (NumberFormatException e) {
            System.out.println("Error parsing '" + anotherInvalidStr + "': " + e.getMessage());
        }
        // Recommended Method 2: Integer.valueOf()
        try {
            int valueOfInt = Integer.valueOf(validStr); // Returns Integer, auto-boxed to int
            System.out.println("\nSuccessfully used valueOf() on '" + validStr + "' to get: " + valueOfInt);
        } catch (NumberFormatException e) {
            System.out.println("Error: Could not use valueOf() on '" + validStr + "'");
        }
    }
}

Key Takeaways

  • int to String: Use String.valueOf() or Integer.toString(). They are clear, efficient, and the standard.
  • String to int: Use Integer.parseInt() or Integer.valueOf().
  • Error Handling: Always be prepared for a NumberFormatException when converting a String to an int. Use try-catch blocks if the input is not guaranteed to be a valid integer.
分享:
扫描分享到社交APP
上一篇
下一篇