杰瑞科技汇

Java String与Integer互转如何实现?

Of course! In Java, converting between String and int is a fundamental and common task. Here’s a comprehensive guide covering the standard methods, best practices, and important edge cases.

Java String与Integer互转如何实现?-图1
(图片来源网络,侵删)

Converting a String to an Integer (int)

This is the most frequent conversion. You need to take a sequence of characters (e.g., "123") and turn it into a primitive integer value (123).

The Best and Most Common Way: Integer.parseInt()

This is the standard, most efficient method for converting a String to a primitive int.

Syntax:

int myInt = Integer.parseInt(String s);

Example:

Java String与Integer互转如何实现?-图2
(图片来源网络,侵删)
String numberStr = "123";
int number = Integer.parseInt(numberStr);
System.out.println("The integer is: " + number); // Output: The integer is: 123
System.out.println(number + 10); // Output: 133

Important: Handling Errors (The NumberFormatException)

If the String does not contain a valid integer representation, Integer.parseInt() will throw a NumberFormatException. This is a critical point to handle in your code.

Example of an error:

String invalidStr = "hello world";
try {
    int number = Integer.parseInt(invalidStr); // This line will throw an exception
    System.out.println(number);
} catch (NumberFormatException e) {
    System.out.println("Error: Cannot convert '" + invalidStr + "' to an integer.");
    // Output: Error: Cannot convert 'hello world' to an integer.
}

Common cases that cause NumberFormatException:

  • Non-numeric characters: "abc"
  • A number with decimal points: "123.45"
  • An empty string:
  • A string with whitespace: " 123" (unless trimmed first)
  • A number that is too large for an int: "2147483648" (which is Integer.MAX_VALUE + 1)

Converting an Integer (int) to a String

This is the reverse operation. You have an integer value and you want to represent it as a sequence of characters.

Java String与Integer互转如何实现?-图3
(图片来源网络,侵删)

The Best and Most Common Way: String.valueOf()

This is the most direct and readable way. It's generally preferred over concatenation.

Syntax:

String myString = String.valueOf(int i);

Example:

int number = 987;
String numberStr = String.valueOf(number);
System.out.println("The string is: " + numberStr); // Output: The string is: 987
System.out.println(numberStr.length()); // Output: 3

Alternative 1: Using Concatenation (Simple but less flexible)

You can simply concatenate the integer with an empty string. The Java compiler handles the conversion for you.

Example:

int number = 42;
String numberStr = "" + number;
System.out.println("The string is: " + numberStr); // Output: The string is: 42
  • Downside: This is less explicit about the conversion's intent and can be slightly less performant in some very specific scenarios (though it's often optimized by the JVM).

Alternative 2: Using Integer.toString()

This method is also very good and efficient. It directly converts the integer to a String.

Syntax:

String myString = Integer.toString(int i);

Example:

int number = 1001;
String numberStr = Integer.toString(number);
System.out.println("The string is: " + numberStr); // Output: The string is: 1001

The Integer Wrapper Class vs. the int Primitive

It's important to understand the difference:

  • int: A primitive data type. It holds a simple value (e.g., 5). It is not an object and cannot be null.
  • Integer: A wrapper class for int. It is an object that can hold an int value. It can be null, which is useful for representing the absence of a value (e.g., in databases or APIs).

Converting String to Integer (the wrapper)

Use Integer.valueOf(). It returns an Integer object.

String numberStr = "555";
Integer numberObj = Integer.valueOf(numberStr);
System.out.println("The Integer object is: " + numberObj);
System.out.println("Is it an object? " + (numberObj instanceof Integer)); // Output: true

Difference between parseInt() and valueOf():

  • Integer.parseInt(String s): Returns a primitive int.
  • Integer.valueOf(String s): Returns an Integer object.

In modern Java (Java 5+), this difference is often blurred because of autoboxing. The compiler will automatically convert an Integer to an int and vice versa when needed. However, understanding the underlying types is still crucial for avoiding NullPointerException and for performance in some cases.

Converting Integer (the wrapper) to String

The methods are the same as for the primitive int because String.valueOf() and Integer.toString() are overloaded to accept both.

Integer numberObj = 777;
String str1 = String.valueOf(numberObj); // Perfectly fine
String str2 = numberObj.toString();      // Also perfectly fine
System.out.println(str1); // Output: 777
System.out.println(str2); // Output: 777

Summary Table

Conversion Goal Recommended Method Returns Type Example
String → int (primitive) Integer.parseInt() int int i = Integer.parseInt("123");
String → Integer (object) Integer.valueOf() Integer Integer i = Integer.valueOf("123");
int → String String.valueOf() String String s = String.valueOf(123);
Integer → String String.valueOf() or Integer.toString() String String s = String.valueOf(myIntObj);

Best Practices and Key Takeaways

  1. Use try-catch for String-to-Integer conversions. Always assume the input string might be invalid and wrap your Integer.parseInt() or Integer.valueOf() calls in a try-catch (NumberFormatException) block.
  2. Prefer String.valueOf() for Integer-to-String conversions. It's clear, concise, and the standard approach.
  3. Be aware of null. If you have a String that might be null, calling any method on it (like parseInt()) will result in a NullPointerException. Always check for null first.
    String maybeNull = null;
    if (maybeNull != null) {
        int number = Integer.parseInt(maybeNull);
    } else {
        // Handle the null case
    }
  4. Handle whitespace. If your string might have leading or trailing spaces (e.g., " 123 "), use the trim() method first.
    String paddedStr = "  456  ";
    int number = Integer.parseInt(paddedStr.trim()); // Works correctly
分享:
扫描分享到社交APP
上一篇
下一篇