Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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

like image 430
user2988464 Avatar asked May 23 '26 13:05

user2988464


1 Answers

'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
like image 182
Christian Tapia Avatar answered May 26 '26 03:05

Christian Tapia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!