关于字符变量的增量

Regarding Increment of Character Variable

下面的代码不起作用,编译器说 'Possible Lossy Conversion from int to char'

public class Main
{
    public static void main(String[] args) {
        char ch;
        ch = 65;
        ch=ch+1;
        System.out.println(ch);
    }
}

那为什么下面的代码没有任何错误:

public class Main
{
    public static void main(String[] args) {
        char ch;
        ch = 65;
        ch+=1;
        System.out.println(ch);
    }
}

虽然这两个代码的唯一区别仅仅是 'ch=ch+1''ch+=1' ?

如果 ch+=1

内部类型转换将由编译器自动执行

如果 ch=ch+1

开发人员必须进行显式类型转换,否则我们将在编译时出错

CE:可能失去岁差
发现:整数
必填:字符

规则:- 如果我们应用任何算术运算符 b/w 2 个操作数 'a' & 'b' 结果类型是 max(int , type of a , type of b)

In Java doing ch = ch + 1 is a form of implicit narrowing conversion. This is why the compiler throws a possible lossy conversion. You can google more about this

"If the type of the result is identical to the type of the variable, the cast has no effect. If, however, the type of the result is wider than that of the variable, the compound assignment operator performs a silent narrowing primitive conversion" JLS 513

//The best thing to do is the following
ch += 1;

因为 += 的结果转换为左侧变量的类型,所以您的操作 ch+=1; 将像这样工作:

ch += 1;
^     ^ ------- right hand (int)
+-------------- left hand  (char)

这会将 ch 转换为 int,例如使用 ((int) ch) :

然后将 ((int) ch)1 求和并将其转换为 char 以支持原始类型,所有这些都可以作为 :

ch = (char) ((int) ch + 1);

在java中,一个char变量的大小是:2个字节, 而一个int变量的大小是:4字节。

N.B:一个字节由8位组成,最多可容纳256个数值。

在第一个代码片段中,当您执行 (ch +1) 时,编译器默认认为 1 是一个 int 值,因此也将最终值视为一个 int。然后编译器尝试将最终值放入 ch 中,它是一个字符...操作...它试图将 4 个字节表示的值放入一个大小为 2 个字节的变量中!

如果您这样做,这个问题可以得到解决: Ch =(字符)(ch+1)

在第二个片段中,您直接递增变量 ch,无论它的大小是多少。因此,您不会 运行 尝试将 int 值放入 char 变量中。