简体   繁体   中英

How does Java concatenate 2 strings?

Why does the following print 197, but not 'bc'?

System.out.println('b' + 'c');

Can someone explain how to do proper concatenation on Java?

PS I learnt some Python, and now transforming to learn Java.

'b' and 'c' are not String s, they are char s. You should use double quotes "..." instead:

System.out.println("b" + "c");

You are getting an int because you are adding the unicode values of those characters:

System.out.println((int) 'b'); // 98
System.out.println((int) 'c'); // 99
System.out.println('b' + 'c'); // 98 + 99 = 197

'b' is not a String in Java it is char . Then 'b'+'c' prints 197 .

But if you use "b"+"c" this will prints bc since "" used to represent String .

System.out.println("b" + "c"); // prints bc

Concatenating chars using + will change the value of the char into ascii and hence giving a numerical output. If you want bc as output, you need to have b and c as String. Currently, your b and c are char in Java.

In Java, String literals should be surrounded by "" and Character are surrounded by ''

Yes single quotation is Char while double quote represent string so:

System.out.println("b" + "c");

Some alternatives can be:

"" + char1 + char2 + char3;

or:

new StringBuilder().append('b').append('c').toString();

In Java, Strings literals are represented with double quotes - ""

What you have done is added two char values together. What you want is:

System.out.println("b" + "c"); // bc

What happened with your code is that it added the ASCII values of the chars to come up with 197 .

The ASCII value of 'b' is 98 and the ASCII value of 'c' is 99 .

So it went like this:

System.out.println('b' + 'c'); // 98 + 99 = 197

As a note with my reference to the ASCII value of the chars :

The char data type is a single 16-bit Unicode character.

From the Docs . However, for one byte (0-255), as far as I'm aware, chars can also be represented by their ASCII value because the ASCII values directly correspond to the Unicode code point values - see here .

The reason I referenced ASCII values in my answer above is because the 256 ASCII values cover all letter (uppercase and lowercase) and punctuation - so it covers all of the main stuff.

Technically what I said is correct - it did add the ASCII values (because they are the same as the Unicode values). However, technically it adds the Unicode codepoint decimal values.

'b' and 'c' are not Strings they are characters. 197 is sum of unicode values of b and c

For Concatinating String you can use following 2 ways:

  • System.out.println("b"+"c");
  • System.out.println("b".concat("c"));

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