• 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

JQ+ question

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am a little confused...on one of the explanations on a JQ+
question it stated that a char value can be assigned to an int variable: i = c; //valid
But cannot assign an int to a char:
c = i;//invalid
However, I saw on another question where a int was assigned to a char value, and it was a valid answer. Can anyone clear this up for me?
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It works if the int is final. That causes the int to become a constant and the compiler knows FOR SURE that it will always FIT into the char.
 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Marc,
The rules applicable for the conversions here in your example are:
1) Conversions from char to int are always valid as they are widening conversions.
2) Conversions from int to char obviously require an cast as they are narrowing conversions.
3) Implicit narrowing conversions occurs from int to char in two cases:
--> When the int literal is in the range of the char (0 to 65535)
--> If the int variable is declared as final and its value is in the range of char (0 to 65535).
So,
int i=100;
final int j=200;
char c='c';
i=c; //valid - widening conversion
//c=i; //compile error - requires cast as it is narrowing conversion
c=100; //valid - implicit conversion of the int literal 100 to char
c=j; //valid - j is a final variable
Hope this helps,
Priya
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks guys...cleared things up : )
 
reply
    Bookmark Topic Watch Topic
  • New Topic