Hi
Is there a difference between concatenating strings with '' and ""?
For example, what is the difference between:
String s = "hello" + "/" + "world";
and
String s = "hello" + '/' + "world";
Thanks in advance.
Hi
Is there a difference between concatenating strings with '' and ""?
For example, what is the difference between:
String s = "hello" + "/" + "world";
and
String s = "hello" + '/' + "world";
Thanks in advance.
Literals enclosed in double quotes, e.g. "foo"
, are strings, whereas single-quoted literals, e.g. 'c'
, are chars. In terms of concatenation behaviour, there'll be no discernible difference.
Nevertheless, it's worth remembering that strings and chars aren't interchangeable in all scenarios, and you can't have a single-quoted string made up of multiple characters.
"." is a String consisting of only one character. '.' is a character.
Once you concatenate them together there is no difference.
Theoretically it is quicker to add a char to a string - Java 6 seems to create StringBuffers under the covers and I remember reading on a Java Performance site that concatenating a char will be marginally quicker.
'' is for character literals.
So you cannot do this:
"Osc" + 'ar' + "Reyes"
Because ar is not a character literal.
In your example it doesn't make much difference because
'/'
is a char literal, and
"/"
is a String literal containing only one character.
Additionally you can use any UTF character with the following syntax
'\u3c00'
So you can also use:
"Osc" + '\u3c00' + "ar
Adding a char is about 25% faster than adding a one character String. Often this doesn't matter however, for example
String s = "hello" + "/" + "world";
This is converted to one String by the compiler so no String concatenation/append will occur at run-time in any case.
System.out.println('a'+'b'+'c');
> 294
System.out.println("a"+"b"+"c");
> abc
What's happening here is that (char)+(char)=(int) In other words. Use "" for text to avoid surprises.
You may just look into the JDK :-)
Given two functions:
public static String concatString(String cs) {
return "hello" + cs + "world";
}
public static String concatChar(char cc) {
return "hello" + cc + "world";
}
after examination of the bytecode it boils down to two AbstractStringBuilder.append(String) vs. AbstractStringBuilder.append(char).
Both methods invoke AbstractStringBuilder.expandCapacity(int)) which will allocate a new char[] eventually and System.arraycopy the old content first.
Afterwards AbstractStringBuilder.append(char) just has to put the given char in the array whereas AbstractStringBuilder.append(String) has to check a few constraints and calls String.getChars(int, int, char[], int) which does another System.arraycopy of the appended string.