Java char is also an int?

前端 未结 7 1796
甜味超标
甜味超标 2020-12-04 02:12

I was trying to get some code done for class:

public int getValue(char value) {
    if (value == \'y\') return this.y;
    else if (value == \'x\') return th         


        
7条回答
  •  情深已故
    2020-12-04 02:53

    There is an implicit and natural conversion from int to char and vice-versa. Note that you thus have the usual arithmetic defined on charm which comes very handy when you want, let's say, to iterate on the alphabet :

    for (char c='a' ; c<='z' ; c++) { ... }
    

    However, note that a char is 2 bytes long whereas an int is 4 bytes long, so casting an int down to a char may result in an integer overflow.

提交回复
热议问题