简体   繁体   中英

Why should I use Integer.toString() instead of just printing the Integer?

I was following a Java tutorial and it was having me do something like:

int k = 5;
System.out.println("The number is " + Integer.toString(k));

So like a good sport I followed along, but I can't help but wonder, why use that method at all? Seems like a lot of extra typing to get the same functionality as:

int k = 5;
System.out.println("The number is " + k);

Is there a good reason to use the toString() method for non-string data types? And in my specific example, are there any int values that can't be auto toString'ed?

It's one of many "safe programming" practices you can adopt to improve clarity and prevent subtle errors which you or a future maintainer of your code could introduce. Take the following example:

private static void printMessage(int k) {
    System.out.println("number" + '=' + k);
}

output: number=5

Now suppose you want to print the number first and the text last. All I'm doing is swapping the first and last items in the string concatenation:

private static void printMessage2(int k) {
    System.out.println(k + '=' + "number");
}

output: 66number

Oops! The int value of = was added to k instead of being concatenated. One solution is to make the = into a String . Another solution is to explicitly convert the int to a String :

private static void printMessage2Safe(int k) {
    System.out.println(Integer.toString(k) + '=' + "number");
}   

output: 5=number

"Oh, but I'd never do that, anyway," you say. "Anyone in their right mind would have just made the = part of the other String." But what if you're implementing part of a basic calculator app, and you want to output the expression and its result? If you're really trying to be careful, I suppose you'll use StringBuilder.append() to concatenate the parts of the expression. But if not, then I hope you don't write the first implementation of the display method below.

public class Calculator {

    public static void main(String[] args) {
        display(2, '+', 3, 5);
        displaySafe(2, '+', 3, 5);
    }

    public static void display(int num1, char operator, int num2, int result) {
        System.out.println(num1 + operator + num2 + '=' + result);
    }

    public static void displaySafe(int num1, char operator, int num2, int result) {
        System.out.println(Integer.toString(num1) + operator + Integer.toString(num2) + "=" + result);
    }

}

output:

114
2+3=5

Is there a good reason to use the toString() method for non-string data types?

Some people believe it is clearer. esp for beginners who may not realised they do basically the same thing.

Note: In Java 7 update 9, it doesn't create the String first as append(int) looks like this

// from AbstractStringBuilder 
public AbstractStringBuilder append(int i) {
    if (i == Integer.MIN_VALUE) {
        append("-2147483648");
        return this;
    }
    int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
                                 : Integer.stringSize(i);
    int spaceNeeded = count + appendedLength;
    ensureCapacityInternal(spaceNeeded);
    Integer.getChars(i, spaceNeeded, value);
    count = spaceNeeded;
    return this;
}

It converts the number strait into the StringBuilder avoiding the need to create a String first.

And in my specific example, are there any int values that can't be auto toString'ed?

No. All primitive values can be toString'ed.

The only exception I know of is signalling and quiet Not-A-Number values as Java doesn't care about such things. Both appear as "NaN" and there is no way to tell the difference from the toString() (or most functions in Java)

System.out.println("The number is " + Integer.toString(k));

In the above print "The number is " is string, so String+(anything) is String only.So in that case no need to call toString() at all.So if you want to print k value only then also no need to call toString() as SOP internaqlly calls toString().

So finally , we can say unless specifically you want to convert Integer to String you should not call toString() method.

Use the second version. For string concatination expressions like

"The number is " + k;

javac builds the actual code using StringBuilder as

new StringBuilder("The number is ")).append(Integer.toString(k)).toString());

so System.out.println simply prints the resulting string, the full code is

System.out.println((new StringBuilder("The number is ")).append(Integer.toString(k)).toString());

It allows the number to become a String data type so it is all a string. As Mob said though, it's not even an integer to start with. You would have to parse it to an integer before it would become one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM