11

So I have this code

char [] a = {'a','b','c'};

char c = 'a' + 'b'; //works
char c2 = 98 + 97; //works
char c3 = a[0] + a[1]; //compile time error

So all of them are the same functionality but upon getting and using an array value it is giving me a compile time error. What is the cause of this??

The result of the additive operator applied two char operands is an int.

then why can I do this?

char c2 = (int)((int)98 + (int)97);
7
  • @ScaryWombat it is commented above. I think he is saying that why all of them work but not the array part Commented Aug 8, 2014 at 5:53
  • @ScaryWombat Required char found int Commented Aug 8, 2014 at 5:54
  • @ScaryWombat Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: possible lossy conversion from int to char Commented Aug 8, 2014 at 5:54
  • @Rod_Algonquin My eyes must be seriously bad - where is it commented? Commented Aug 8, 2014 at 5:56
  • @ScaryWombat char c3 = a[0] + a[1]; //compile time error Commented Aug 8, 2014 at 5:58

1 Answer 1

2

The result of the additive operator applied two char operands is an int.

Binary numeric promotion is performed on the operands. The type of an additive expression on numeric operands is the promoted type of its operands

The first two are constant expressions where the resulting value is an int that can be safely assigned to a char.

The third is not a constant expression and so no guarantees can be made by the compiler.

Similarly

then why can I do this?

char c2 = (int)((int)98 + (int)97);

That is also a constant expression and the result can fit in a char.

Try it with bigger values, 12345 and 55555.

Sign up to request clarification or add additional context in comments.

11 Comments

@Kick Yes. It's in the JLS, give me a second. I'm on my phone.
@KickButtowski it is the java specification language more like the rule book of java
@game That is still a constant expression where the result is guaranteed to fit in a char.
@Kick Yes additive op means + applied to numeric types. Binary numeric means that two numbers (numeric values) are involved.
@kick When applied to numeric types, the + operator is binary numeric additive operator. When applied to at least one operand of type String, it is the string concatenation operator. Please go through the JLS that I've linked.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.