• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

cast of int to char

 
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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“
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic