开发者

How to concisely create a String that begins with a primitive value without using an empty double-quote?

To get a newString value of "99 bottles":

int x = 99;
String fruit = " bottles";

To form a new String I do this:

String newString = "" + x + fruit;

since this is not allowed:

String newString = x + fruit;

But there's something about using the 开发者_JS百科double quotes here that doesn't seem right.

Is there a better way to do this (without using the "" + x)?


To be clear the following is perfectly legal Java:

    String fruit = " bananas";
    int x = 99;
    String newString = x + fruit; // "99 bananas"

The diadic + operator is String concatenation if either the left or right operand expression's type is String; see JLS 15.18.

The following is equivalent in this case:

    String newString = "" + x + fruit;

The initial "" is a common idiom that makes it crystal clear to the reader that string concatenation is involved. (I personally wouldn't use it though, since it looks clunky to me. IMO, it is like adding redundant parentheses to help programmers who don't know the operator Java precedence rules. Icck.)

In the example above, the "" makes no semantic difference. However, there are occasions where the leading "" changes the meaning of the expression. For example:

    int x = 1;
    String fruit = " bananas";
    String newString = x + x + fruit;  // "2 bananas"
    String newString2 = "" + x + x + fruit; // "11 bananas".

(Note that the javac compiler is permitted by the JLS to aggressively optimize a sequence of String concatenations, so the apparent concatenation with "" will be optimized away.)


One alternative is the String#format() function. Use it as follows:

final String newString = String.format("%d bottles", x);

Another alternative is Integer#toString():

final String newString = Integer.toString(x) + " bottles";


Use Integer.toString():

int x = 99;
String fruit = " bottles";
String newString = Integer.toString(x) + fruit;

There is a Float.toString(float val), Double.toString(double val), and Long.toString(long val) as well. Personally, I don't like the use of "" when doing concatenation. I think it's sloppy-ish, for lack of a better word.


String newString = x + fruit;

is allowed in Java.

Another way of doing it is:

String newString = String.format("%d bottles", x);


I tried:

int x = 99;
String fruit = " bottles";
String newString = x + fruit;
System.out.println(newString);

on Eclipse and it does work... but if the above doesn't work for you, String has a valueOf() method:

String newString = String.valueOf(x) + fruit;

However, the "" is actually more common, as 動靜能量 stated.


The usage

String newString = "" + x + fruit;

is common enough that people know what you are doing. In some language, you can do

$str = 3 . 'foo';   # in PHP

And in some language, you can do

str = "#{x} foo"   # in Ruby

both of which look more natural.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜