0
  • char c = '1';
  • char res = '0' + '1'; // no error
  • char res2 = '0' + c; // compile error

The last line will throw compile error. Each part of the expression is char, why the expression itself is promoted to an int?

Thanks

Edit: Found why the 3rd statement failed. The reason is explained in In Java, is the result of the addition of two chars an int or a char?

But the knowledge that char + char = int does not explain why the 2nd of your three examples does compile. Any ideas?

Community
  • 1
  • 1
psbox2021
  • 43
  • 5
  • I believe it's context sensitive..i.e. it will read a char as an int when arithmetic is the use case. Though don't quote me on it. Maybe my comment will anger someone enough to come out and correct us :) – CubeJockey Aug 04 '15 at 19:19
  • (The duplicate is for `byte` rather than `char`, but it's basically the same) – Jon Skeet Aug 04 '15 at 19:20
  • Ah! Good guess on my part. – CubeJockey Aug 04 '15 at 19:20
  • I'm not convinced that duplicate answers this. Try this: `char a = 60000;` `char b = 70000;`. The first compiles whereas the second one doesn't. That is because, even though the assigned values are both `int` literals, the compiler can see that the first does not exceed `Character.MAX_VALUE`. In your case, the difference between `'0' + '1'` and `'0' + c` is that, even though the addition is `int` addition for **both** cases, in the first case the compiler is able to see that the result does not exceed `Character.MAX_VALUE` because it is a constant expression. I think that's it anyway. – Paul Boddington Aug 04 '15 at 19:46
  • I believe I found the anser here http://stackoverflow.com/questions/8688668/in-java-is-the-result-of-the-addition-of-two-chars-an-int-or-a-char thanks all – psbox2021 Aug 04 '15 at 20:08
  • @paracicy But the knowledge that `char + char = int` does not explain why the 2nd of your three examples *does* compile. I don't think either of those posts are great duplicates for this. – Paul Boddington Aug 04 '15 at 20:15
  • @PaulBoddington good point. still need answer. – psbox2021 Aug 05 '15 at 20:58
  • @JonSkeet is it possible to reopen this? – psbox2021 Aug 10 '15 at 06:22
  • The second example is a compile-time constant within the relevant bounds of the type. Look at the JLS on constant values for more details. If you're interested in just that part, I'd create a new question - asking a question which has mostly been answered elsewhere, and adding emphasis on new parts later, doesn't really work well. – Jon Skeet Aug 10 '15 at 06:25
  • You want to read http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.2 and http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28 – Jon Skeet Aug 10 '15 at 07:38

0 Answers0