Why does the following print 197, but not 'bc'?
System.out.println('b' + 'c');
Can someone explain how to do proper concatenation on Java?
P.S. I learnt some Python, and now transforming to learn Java.
'b' and 'c' are not Strings, they are chars. 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
chars as UTF-16 code-units encoding Unicode code-points, not ASCII values.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();
.append("") is redundant.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' as 98. I'm just saying it's easier to point people in the ASCII direction for this sort of question because the ASCII values (for a byte, I think) are the same thing.
197is sum of unicode values ofbandc, Python is different then Java in Python'b'and'c'are strings In Java they are char literals, string literals has to be double quoted""