File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes cast of int to char Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "cast of int to char" Watch "cast of int to char" New topic

cast of int to char

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
please consider this:
public class As{
int i = 10;
char z= 10;
char c= i;
Why is it possible to say „char z=10“ but when I say char c = i (and i is also 10)
then there is a compile-time error:
C:\Java\EigeneJavaProgramme>javac possible loss of precision
found : int
required: char
char c= i;
1 error
(note: it is also possible to say „char z = 1587“
raju vegiraju

Joined: Sep 24, 2002
Posts: 5
conversions Are performed automatically when mixed numeric types appear within an expression. Variables and constants are not altered, but their values are copied to intermediate areas of larger size or precision to prevent possible data loss during the calculation. This is known as a "widening" conversion. The order of conversion (from narrowest to widest) is as follows:
short char

The data type resulting from an expression is that of the largest or most precise variable or constant appearing in the expression but is never smaller than int.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
It's possible for an int to be a value not in the range of values that can be assigned to a char. Even though your code doesn't provide for such a condition, it would be a tall order for a compiler to be able to determine what some non-final value will be during the entire runtime of a program. So, even when a person can reasonably determine the possible values of some data item, the compiler says that it's not even going to try and guess the actual possible values and it's just going to make sure that you are aware of the situation (that you do indeed want to risk a cast from an int to a char).
Were you to declare the int variable as final, then the compiler can be certain of its value and it will perform the assignment without an explicit cast if the value is within an acceptable range.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: cast of int to char
It's not a secret anymore!