2

When I have the following:

char a = 'a';
System.out.println(++a);             //returns b
System.out.println(a + 1);           //returns 98
System.out.println('a' + 1);         //returns 98
System.out.println(1 + a);           //returns 98
System.out.println(1 + 'a');         //returns 98

Why does the ++ operator return the next (larger) letter, but adding 1 doesn't? The OCA/OCP book I'm using does not mention this (except that char would be implicitly cast to an int).

Is there a good book or other resource that details this?

  • @SotiriosDelimanolis That question is for a post-increment operation. – OneCricketeer Aug 09 '16 at 15:40
  • 1
    @cricket_007 They behave the same way. – Sotirios Delimanolis Aug 09 '16 at 15:41
  • @SotiriosDelimanolis So, am I interpreting this right? "The type of the prefix increment expression is the type of the variable" -- [JLS 15.15.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.1). – OneCricketeer Aug 09 '16 at 15:44
  • 1
    Which is `char` @cricket_007, in the first example. So you get a `char` back with the prefix increment. The other perform binary numeric promotion of char to int. – Tunaki Aug 09 '16 at 15:46
  • @cricket_007 Yes, and _Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3)_. – Sotirios Delimanolis Aug 09 '16 at 15:46

0 Answers0