Difference between '.' and "." in java

Is there any 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.

+6
java
source share
10 answers

Literals enclosed in double quotes, for example. "foo" , strings , while single quotes, for example. 'c' , characters . There will be no differences in terms of concatenation behavior.

However, it is worth remembering that strings and characters are not interchangeable in all scenarios, and you cannot have one single quoted string consisting of several characters.

+24
source share
 System.out.println('a'+'b'+'c'); > 294 System.out.println("a"+"b"+"c"); > abc 

What happens here is (char) + (char) = (int) In other words. Use "" for text to avoid surprises.

+12
source share

"" is a string, '.' is char.

+9
source share

You can just look in 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 examining the bytecode, it boils down to two AbstractStringBuilder.append (String) versus AbstractStringBuilder.append (char) .

Both methods reference AbstractStringBuilder.expandCapacity (int)) , which will eventually highlight the new char [] and System.arraycopy old first.

Subsequently, AbstractStringBuilder.append (char) just needs to put the given char into an array, while AbstractStringBuilder.append (String) should check for a few restrictions and calls to String.getChars (int, int, char [], int) , which executes another System.arraycopy from the added row.

+4
source share

"" is a string consisting of only one character. '' is a symbol.

Once you combine them together, there is no difference.

+3
source share

'' for character literals.

So you cannot do this:

"Osc" + 'ar' + "Reyes"

Since ar is not a character literal.

In your example, this is not a big deal because

 '/' 

is a char literal and

  "/" 

- A string literal containing only one character.

In addition, you can use any UTF character with the following syntax

 '\u3c00' 

So you can also use:

 "Osc" + '\u3c00' + "ar 
+3
source share

Adding char is about 25% faster than adding a single character string. Often it doesn’t matter, for example,

 String s = "hello" + "/" + "world"; 

This is converted to a single String by the compiler, so that at run time there will be no String concatenation / addition.

+2
source share

It is theoretically faster to add a char string to a string - Java 6 seems to create StringBuffers under covers, and I remember reading through the Java Performance website that char concatenation would be a little faster.

+1
source share

You will probably find the following helpful articles:

+1
source share

char theLetterA = 'A'; string myString = "string";

0
source share

All Articles