This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "cast of int to char" Watch "cast of int to char" New topic
Author

cast of int to char

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
Hello,
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 As.java
As.java:5: 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
Greenhorn

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:
byte
|
short char
\
/

int
|
long
|
float
|
double
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
Sheriff

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]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: cast of int to char
 
Similar Threads
conversion question
How to implement hashCode()
Automatic Conversion / Cast
Question regarding "for" loops
Create a package for source file "Vector.java"