문제

Why is this right?

char c1 = 125;

And why is this wrong?

char c2 = c1 + 1;

The right way of the codes above should be:

char c2 = (char)(c1 + 1);

I am confused. Thank you very much!

도움이 되었습니까?

해결책 2

It's wrong because char is smaller than int. In c1 + 1 the c1 is promoted to an int to be added to 1. When you try to put it back in a char java complains because it can't promise that an int will fit in a char

-edit-

In the case of char c = 123 the 123 part is known, so java can really promise that it will always fit in a char. This will work as well:

final char c0 = 123;
char c1 = c0 + 1;

and this:

final int i0 = 123;
char c1 = i0 + 1;

다른 팁

In Java, you need to be aware of the type of the result of a binary (+) arithmetic operator.Below are the rules

1.If either operand is of type double, the other is converted to double.
2.Otherwise, if either operand is of type float, the other is converted to float.
3.Otherwise, if either operand is of type long, the other is converted to long.
4.Otherwise, both operands are converted to type int.

Your statement c1 + 1 falls into 4th rule, so the result is of type int and then you need to cast it char explicitly to assign it to char variable.

char c2 = c1 + 1;

The Java language specification defines exactly how integer numbers are represented and how integer arithmetic expressions are to be evaluated. Arithmetic expression on the right-hand side of the assignment operator evaluates to int by default. int has bigger storage size than short. That is why you have to explicitly tell that you know what you are doing by using casting.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top