0

I cant print two char in one system.out.print code as it is shown in below. I would like to know how java works in that case since it is summing up ASCII conversions of these chars.

System.out.println('a'+'b');
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
mumun
  • 51
  • 1
  • 8
  • For reference: [JLS Table 2.11.1-B](https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-2.html#jvms-2.11.1-320) shows the actual runtime-types of java primitives. Since `char`s are `int`s (at runtime), the addition adds the ASCII (or, to be more precise, the Unicode-values). – Turing85 Jul 26 '19 at 20:12
  • Try `System.out.println(""+'a'+'b');` – Butiri Dan Jul 26 '19 at 20:17
  • or just `System.out.println("ab");` ??! [:-) – user85421 Jul 26 '19 at 21:10

2 Answers2

3

This is Java, not JavaScript.

In Java, the single quote is reserved for char data. You must use the double quote for a String value.

As stated in the @Sean Bright comment, char + char is math, not string concatenation.

There are many ways to output two char values. Here is an example of one such way:

final String output;

output = String.format("%c %c\n", 'a', 'b');

System.out.println(output);
DwB
  • 37,124
  • 11
  • 56
  • 82
  • maybe without the space between both `%c`s; and no `\n` since already using `println`, even better, use `printf` (with `\n` or `%n`) directly – user85421 Jul 26 '19 at 21:13
0

The output of the last one is 195, because you are doing an addition of char values in the ASCII table (97+98) . you first sum all the values as explained before, then convert it to a String adding "" to the sum of the ASCII values of the chars. However, the println method expect a Strin Y

  • Java's (as well as VB4/5/6/A/Script, JavaScript, .NET, etc) char and string datatypes use the UTF-16 character encoding of the Unicode character set; Not ASCII. – Tom Blodget Jul 26 '19 at 23:47