This week's book giveaway is in the Functional programming forum.
We're giving away four copies of Functional Design and Architecture and have Alexander Granin on-line!
See this thread for details.
Win a copy of Functional Design and Architecture this week in the Functional programming forum!
  • 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Casting Problem

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could some one please clarify me:
Why char c = 100; is true while
int i =100; char c = i; is false.
Similarly c= c+ i; is false but c+=i; is true.
Thanks in advance for ur help.
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
char c = 100; //ok in declaration as long as value w/in range
int i = 100;
char c = i; //need cast...I think because you're not using a literal here, so compiler can't check
c = c + i; //need cast
c += i; //ok, but I'm not sure why.
I know that c += 1 is fine because automatic promotion of the literal to int doesn't happen with +=, but I'm confused with c += i not needing a cast.
Anyone?
 
Ranch Hand
Posts: 289
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just to add more:
char c = 100;//Ok because 100 is constant and valid within char's range.
int i =100;
char c = i;//invalid because i is a variable, whose value could go out of bounds of char's range
Similarly c= c+ i;invalid because the result of an arithmetic operation is at least an int, which is wider that char
c+=i;Ok because for op= type, an implicit cast takes place
That's it, in brief.
Herbert.
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class MyClass {
public static void main(String[] args) {
final int i =200;
char c = i;
System.out.println(c);
}
}
This will compile in jdk1.3, note final.
 
Clowns were never meant to be THAT big! We must destroy it with this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic