• 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

Looks silly and crazy but....

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
PL look at the following code:
public void amethod(){
int i=4;
char c=1;
c+=i;// success with this code but when replaced with c=c+i compilation fails.
System.out.println(c);
}
This code compiles successfully and prints a character in pictorial representation.But when tried to compile with c=c+i..the compilation fails with message "explicit cast required".Oooh boy..am I crazy or is that the compiler??
Reason please.
Thanx
 
Sheriff
Posts: 7001
6
Eclipse IDE Python C++ Debian Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Interesting. I think it has to do with the implicit casting that's going on. Let's analyse what you've got.
In the c += i case, the casting is pretty clear. The operator for += on a char is being passed an int.
In the c = c + i case, there is an implicit cast of (int)c before the addition (now of two integers). This then leads to the same as if you had called c = i.
Now assigning a non-literal integer to a char is a 'narrowing' conversion, which requires an explicit cast, hence the message.
The real question, then is "why isn't this narrowing picked up by the += operator?".
Has anyone tried this with various compilers and/or the language spec? Any other suggestions?
 
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
Java lang specification says like this...
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1.
According to this, in the example above...expression should be:
c = (char) (c + i);
which is right.
Does this answer ur question !!!
Shiva
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic