0

I was going through Java questions,and then I found this one. I am unable to understand why for this code-

public class File 
{
    public static void main(String[] args) 
    {
        System.out.println('H'+'I');
    }
}

Output is 145 and for this code-

public class File
{
    public static void main(String[] args) 
    {
        System.out.print('H');
        System.out.print('I');
    }
}

Output is HI.

In the first case,I know the output is the addition of the ASCII values of 'H' and 'I' but for second case it is not displaying ASCII values,why so? Thanks!!

Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42
  • 'H' and 'I' are each one literal char value, which is a primitive datatype for [Character](https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html). Both datatypes use UTF-16, not ASCII. See the docs. – Tom Blodget Aug 31 '16 at 23:38

1 Answers1

2

As described in JLS Sec 15.18:

If the type of either operand of a + operator is String, then the operation is string concatenation. ...

The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.

In the first case, you've got two chars (not strings), so they are widened to ints, and added, and then passed to System.out.print(int) to be printed.

In the second case, you are invoking the System.out.print(char) method, which prints the char as a character. You invoke this twice, so you get two chars.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243