Reason to explicitly cast from char to int in Java?

谁说胖子不能爱 提交于 2020-08-11 17:57:48

问题


I have seen in Java code in many places, people tend to cast between primitives int and char.

Is this necessary? Are they not implicitly converted.
For e.g. I tried this and exactly got what I should. Then why do people explicitly cast? Am I missing something?

char a = 'a';
int index = (int) a;
index = 98;
a = 98;
System.out.println(index);
System.out.println(a);

回答1:


Sometimes people will cast for clarity, sometimes for overloading reasons, and sometimes for reasons of ignorance.

For example:

System.out.println((int) a);

will work differently to

System.out.println(a);

due to overload resolution. But in the exact code you've given, it's definitely not required. If you want to know exactly why a particular developer has chosen to write redundant code, you'd need to ask them...




回答2:


Casting in this case removes ambiguity, and makes the code easier to read.



来源:https://stackoverflow.com/questions/12991896/reason-to-explicitly-cast-from-char-to-int-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!