Phoenix
Phoenix

Reputation: 8933

Reason to explicitly cast from char to int in Java?

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);

Upvotes: 1

Views: 1737

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1504162

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...

Upvotes: 9

Michael
Michael

Reputation: 3342

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

Upvotes: 0

Related Questions